本文使用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層方法如下(核心):
@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;
}
到這里已經授權成功啦,短短幾行代碼實作了微信檔案里麻煩的步驟
如果我的方法解決了大家的問題,希望大家可以點贊支持!希望對大家有所幫助!
轉載請注明出處即可
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/231736.html
標籤:Java
