1、問題描述
要在微信公號中新建自定義菜單,然后導航到公司H5中,需要首先獲取用戶微信信息,然后再進行手機號綁定,以前微信公號開發做的不多,記錄下,希望能幫到需要的朋友!
2、解決方案
2.1 官方文檔,寶典
(1)首先最權威的還是微信的官方文檔,這個才是寶典
https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/Wechat_webpage_authorization.html#1
(2)我們用的自定義菜單是屬於微信網頁開發
(3)微信公號有個很重要的概念access_token,這里有區別,需要注意
(4)微信官網獲取用戶信息流程
2.2 微信公號正式環境設置
特別說明下,需要認證服務號才能通過頁面授權獲取用戶信息,如下圖:
(1)獲取用戶信息,開發者ID(AppID)和開發者密碼(AppSecret)是必填的字段。
登錄微信公號后台進行設置(https://mp.weixin.qq.com/)
處於安全考慮,開發者密碼,微信不保存,一旦忘記,需要重置,重置需管理員掃碼和錄入公號密碼。
(2)微信回寫地址設置
這里有個微信回寫地址需要設置,必須是域名。
這樣就設置完畢了。
2.3 微信公號測試環境設置
(1)為了方便測試,微信提供了微信公號的測試環境設置,開發-->開發者工具下面
(2)微信公號會生成測試的appid和密碼
(3)往下面拉,同樣的道理設置回寫域名
2.3 springboot項目調用
簡單就是拼接微信參數+httpclient調用微信接口。
(1)第一步:用戶同意授權,獲取code
@GetMapping("/wxlogin")
public String wxlogin() {
// 第一步:用戶同意授權,獲取code
String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + appid +
"&redirect_uri=" + http +
"&response_type=code" +
"&scope=snsapi_userinfo" +
"&state=STATE#wechat_redirect";
return "redirect:" + url;
}
(2)第二步-第四步:獲取用戶信息(第三步刷新不要)
這里的調用(wxcallback)是設置在微信公號中的回寫地址,就是第一步的獲取code的時候,&redirect_uri= http中,配置文件是這樣的:
@GetMapping("/wxcallback")
public String wxcallback(String code, ModelMap map) throws IOException {
// 第二步:通過code換取網頁授權access_token
String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + appid +
"&secret=" + appsecret +
"&code=" + code +
"&grant_type=authorization_code";
JSONObject jsonObject = HttpClientUtils.doGet(url);
String openid = jsonObject.getString("openid");
String access_Token = jsonObject.getString("access_token");
System.out.println(jsonObject);
// 第四步:拉取用戶信息(需scope為 snsapi_userinfo)
url = "https://api.weixin.qq.com/sns/userinfo?access_token=" + access_Token +
"&openid=" + openid +
"&lang=zh_CN";
JSONObject userInfoJson = HttpClientUtils.doGet(url);
System.out.println("UserInfo:" + userInfoJson);
// 2種情況: 我們是有賬號體系的,微信帳號做來一個關聯,來關聯我們的賬號體系
UserEntity userEntity = userService.getOpenid(openid);
if (userEntity == null) {
userEntity = new UserEntity();
userEntity.setType(0);
userEntity.setOpenid(openid);
userEntity.setNickname((String)userInfoJson.get("nickname"));
userEntity.setImage((String)userInfoJson.get("headimgurl"));
userService.insert(userEntity);
} else {
userEntity.setNickname((String)userInfoJson.get("nickname"));
userEntity.setImage((String)userInfoJson.get("headimgurl"));
userService.update(userEntity);
}
return "redirect:/gohome?openid=" +openid;
}
代碼中增加了用戶關聯的部分,可以不要。
(3)這里有個點要特別說明
微信公號中有個段特別說明,簡單說就是假如是關注了公號,然后從自定義菜單進入,其實是靜默獲取的,不需要用戶授權的,測試了下,確實如此。
(4)首頁測試頁面,也很簡單
2.4 源碼
https://github.com/ruanjianlaowang/wxoauth
更多信息請關注公眾號:「軟件老王」,關注不迷路,軟件老王和他的IT朋友們,分享一些他們的技術見解和生活故事。