一、前提條件
1.申請微信公眾號測驗號申請一個微信公眾號測驗號,測驗號申請:https://mp.weixin.qq.com/debug/cgi-bin/sandbox?t=sandbox/login

2.掃碼登陸注冊,注冊成功后就會生成微信公號的appID和appsecret

3.需要設定網頁授權(體驗介面權限表 —》 網頁服務 —》網頁帳號 —》 網頁授權獲取用戶基本資訊

4.點擊修改,填寫域名,切記一定不能加上http://協議,

注:沒有域名的話可以用內網穿透動態決議一個域名:https://natapp.cn/register
注冊登錄成功后可以看到下圖,選擇免費隧道進行購買

購買免費的隧道之后,點擊我的隧道就會看下圖1,同時在本地新建一個natapp目錄,并且下載客戶端到natapp目錄下,將壓縮包解壓,同時在需要在新建一個config.ini檔案,這樣我們就拿到了我們的域名(步驟5)

下載客戶端

config.ini檔案內容:

#將本檔案放置于natapp同級目錄 程式將讀取 [default] 段
#在命令列引數模式如 natapp -authtoken=xxx 等相同引數將會覆寫掉此配置
#命令列引數 -config= 可以指定任意config.ini檔案
[default]
authtoken=xxxxxxxxxx #對應一條隧道的authtoken
clienttoken= #對應客戶端的clienttoken,將會忽略authtoken,若無請留空,
log=none #log 日志檔案,可指定本地檔案, none=不做記錄,stdout=直接螢屏輸出 ,默認為none
loglevel=ERROR #日志等級 DEBUG, INFO, WARNING, ERROR 默認為 DEBUG
http_proxy= #代理設定 如 http://10.123.10.10:3128 非代理上網用戶請務必留空
5.配置域名


6.下載微信開發者工具:https://developers.weixin.qq.com/miniprogram/dev/devtools/download.html
二:實作邏輯
網頁授權流程分為四步:參考官方:https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/Wechat_webpage_authorization.html
1.引導用戶進入授權頁面同意授權,獲取code
public void getCode(HttpServletResponse response) throws Exception{
String appId = "wxbac840ef8aba6443";
// 官方地址
String urlFir = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=";
// 微信申請的域名(提前準備)
String domain = "http://rhvp5f.natappfree.cc";
// 自定義跳轉方法
String redirectMethod = "/v1/weChat/callback";
String encoderUrl = getURLEncoderString(domain + redirectMethod);
String url = urlFir + appId + "&redirect_uri=" + encoderUrl + "&response_type=code&scope=snsapi_base" + "&state=123" + "#wechat_redirect";
response.sendRedirect(url);
}
public static String getURLEncoderString(String str) {
String result = "";
if (null == str) {
return "";
}
try {
result = java.net.URLEncoder.encode(str, "GBK");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return result;
}
2.通過 code 換取網頁授權access_token(與基礎支持中的access_token不同)
public void callback(@RequestParam String code, @RequestParam String state) {
String appId = "wxbac840ef8aba6443";
String appIdSecret = "dbf4aadaae8dab4e699ff5259c0c0ad8";
log.info("獲取code:{}",code);
String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="
+ appId + "&secret=" + appIdSecret + "&code=" + code + "&grant_type=authorization_code";
Map<String, Object> paramMap = null;
String res = HttpUtil.get(url, paramMap);
String openid = JSONObject.parseObject(res).getString("openid");
//只有在用戶將公眾號系結到微信開放平臺帳號后,才會出現該欄位,
String unionid = JSONObject.parseObject(res).getString("unionid");
log.info("根據code查詢得到openId:{}",openid);
log.info("unionid:{}",unionid);
}
注:網頁授權的作用域為snsapi_base,則本步驟中獲取到網頁授權access_token的同時,也獲取到了openid,snsapi_base式的網頁授權流程即到此為止,本次文章也是到本步驟結束,
3.如果需要,開發者可以重繪網頁授權access_token,避免過期
4.通過網頁授權access_token和 openid 獲取用戶基本資訊(支持 UnionID 機制)
三:測驗

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/540429.html
標籤:Java
上一篇:彩虹女神躍長空,Go語言進階之Go語言高性能Web框架Iris專案實戰-JWT和中間件(Middleware)的使用EP07
