java微信端html_H5微信网页授权java后端SpringBoot实现

论坛 期权论坛 编程之家     
选择匿名的用户   2021-6-2 01:36   11   0

转载请注明出处即可,感谢!本文地址:https://www.cnblogs.com/qupengblog/p/14105369.html

本文使用weixin4j工具包,实现SpringBoot中微信网页授权功能,并获取用户信息。

从微信文档中我们可以发现有以下几个步骤:

1262658fae51ed0d0a89736f315f35a9.png

在这里我整理了一个最简便的实现方式,请大家参考

首先在pom.xml中引入java工具包:

org.weixin4j.spring.boot

weixin4j-spring-boot-starter

1.0.0

com.github.liyiorg

weixin-popular

2.8.5

在 application.properties 文件中配置公众号 appid 和 Secret:

weixin4j.config.appid=yourappid

weixin4j.config.secret=yoursecret

Controller层需要接受的参数需要以下两个:

code:前端页面授权同意获取的code

url:微信js调用的url,也就是要授权的域名

Service层方法如下(核心):

@Resource

private WeixinTemplate weixinTemplate; //weixin4j工具模板

@Transactional

public Map login(Map param) throws WeixinException {

SnsUser snsUser = weixinTemplate.sns().getSnsUserByCode((String) param.get("code")); //通过code获取access_token信息

String subscribe = weixinTemplate.user().info(snsUser.getOpenid()).getSubscribe();

Map map = new HashMap<>(); //返回值map

String randomStr = UUID.randomUUID().toString().substring(0, 18);

map.put("appId", weixinTemplate.getAppId()); //appid,前端若不需要可忽略

Date date = new Date();

String sign = SignUtil.getSignature(weixinTemplate.getJsApiTicket().getTicket(), randomStr, new Long(date.getTime() / 1000).toString(), (String) param.get("url"));

//-----以下代码根据具体业务处理-----

map.put("subscribe",Integer.parseInt(subscribe)); //用户是否关注公众号 0-否,1-是

//拼装前端需要的返回结果

Map signature_dict = new HashMap<>();

signature_dict.put("nonceStr", randomStr);

signature_dict.put("signature", sign);

signature_dict.put("timestamp", new Long(date.getTime() / 1000));

map.put("signature_dict", signature_dict);

//根据openid查询用户id,以此决定更新还是新增用户信息

WxUsers wxUsers = wxUsersMapper.selectIdByOpenid(snsUser.getOpenid());

if(wxUsers == null){

wxUsers = new WxUsers();

}

wxUsers.setNickName(snsUser.getNickname());

wxUsers.setSex(snsUser.getSex());

wxUsers.setImg(snsUser.getHeadimgurl());

wxUsers.setOpenid(snsUser.getOpenid());

map.put("nickName",wxUsers.getNickName());

map.put("img",wxUsers.getImg());

if (wxUsers.getWxUsersId() == null) {

wxUsersMapper.insert(wxUsers);

map.put("wxUsersId",wxUsers.getWxUsersId());

} else {

map.put("wxUsersId",wxUsers.getWxUsersId());

wxUsersMapper.updateByPrimaryKey(wxUsers);

}

return map;

}

到这里已经授权成功啦,短短几行代码实现了微信文档里麻烦的步骤

如果我的方法解决了大家的问题,希望大家可以点赞支持!希望对大家有所帮助!

转载请注明出处即可

分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:3875789
帖子:775174
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP