H5微信網頁授權java后端SpringBoot實現


轉載請注明出處即可,感謝!本文地址:https://www.cnblogs.com/qupengblog/p/14105369.html
本文使用weixin4j工具包,實現SpringBoot中微信網頁授權功能,並獲取用戶信息。

使用weixin4j工具包1.0.0版本,官網:http://www.weixin4j.org/
微信官方文檔:> https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/Wechat_webpage_authorization.html

從微信文檔中我們可以發現有以下幾個步驟:

在這里我整理了一個最簡便的實現方式,請大家參考

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

<!-- 微信工具包 -->
<dependency>
	<groupId>org.weixin4j.spring.boot</groupId>
	<artifactId>weixin4j-spring-boot-starter</artifactId>
	<version>1.0.0</version>
</dependency>
<!-- 微信工具包 -->
<dependency>
	<groupId>com.github.liyiorg</groupId>
	<artifactId>weixin-popular</artifactId>
	<version>2.8.5</version>
</dependency>

在 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<String, Object> login(Map<String, Object> param) throws WeixinException {
    SnsUser snsUser = weixinTemplate.sns().getSnsUserByCode((String) param.get("code")); //通過code獲取access_token信息
    String subscribe = weixinTemplate.user().info(snsUser.getOpenid()).getSubscribe();
    Map<String, Object> 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<String, Object> 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;
}

到這里已經授權成功啦,短短幾行代碼實現了微信文檔里麻煩的步驟
如果我的方法解決了大家的問題,希望大家可以點贊支持!希望對大家有所幫助!
轉載請注明出處即可


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM