第三方平臺系列文章,今天終于又開始更新了,今天繼續學習微信(wechat)授權第三方登錄
一、準備作業
1、申請微信公眾測驗號
由于我們是個人開發者,我們需要去注冊申請一個微信公眾平臺的測驗號
https://mp.weixin.qq.com/debug/cgi-bin/sandbox?t=sandbox/login

我們使用微信掃碼登錄后,我們可以拿到 appID 和 appsecret

2、關注公眾測驗號

3、配置回呼域名
在“網頁服務”中找到“網頁賬號”,修改“網頁授權獲取用戶基本資訊”介面的回呼域名


注意:這里說的是,配置網頁授權回呼頁面 域名,跟我們平常對接的第三方介面不一樣,不用填寫完整的回呼地址,只是回呼域名,回呼地址在回呼域名之下
- 例如:
回呼地址:http://www.baidu.com/wechat/back
那么這里:baidu.com
新手一般在這里容易弄混,配置完成,點擊“確認”即可
二、開始開發
1、獲取應用資訊
我們將獲取到的 appID 和 appsecret 寫在組態檔中,我這里是 SpringBoot 專案,我就放在 application.yml 檔案中

2、引入 maven 依賴
<!-- 網路請求 -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.6</version>
</dependency>
<!-- alibaba的fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.51</version>
</dependency>
這里我們需要用到網路請求,和 JSON 物件的轉換,所以我引入了 httpclient 和 fastjson,其余依賴請自行引入
3、從組態檔中獲取 “wechat” 配置資訊
/**
* 公眾平臺提供的 appid 和 appsecret
*/
@Value("${wechat.oauth.appid}")
public String APPID;
@Value("${wechat.oauth.appsecret}")
public String APPKEY;
@Value("${wechat.oauth.callback}")
public String URL;
4、重定向到授權頁面
/**
* 請求授權頁面
*/
@RequestMapping("/auth")
public String token(HttpSession session) throws Exception {
// 用于第三方應用防止CSRF攻擊
String uuid = UUID.randomUUID().toString().replaceAll("-", "");
session.setAttribute("state", uuid);
// Step1:獲取Authorization Code
String url = "https://open.weixin.qq.com/connect/oauth2/authorize?" +
"appid=" + APPID +
"&redirect_uri=" + URLEncoder.encode(URL) +
"&response_type=code" +
"&scope=snsapi_userinfo" +
"&state=" + uuid +
"#wechat_redirect";
return PasswordUtils.redirectTo(url);
}
- Step1 引數解釋如下:
| 引數 | 是否必須 | 說明 |
|---|---|---|
| appid | 是 | 公眾號的唯一標識 |
| redirect_uri | 是 | 授權后重定向的回呼鏈接地址, 請使用 urlEncode 對鏈接進行處理 |
| response_type | 是 | 回傳型別,請填寫code |
| scope | 是 | 應用授權作用域,snsapi_base (不彈出授權頁面,直接跳轉,只能獲取用戶openid),snsapi_userinfo (彈出授權頁面,可通過openid拿到昵稱、性別、所在地,并且, 即使在未關注的情況下,只要用戶授權,也能獲取其資訊 ) |
| state | 否 | 重定向后會帶上state引數,開發者可以填寫a-zA-Z0-9的引數值,最多128位元組 |
| #wechat_redirect | 是 | 無論直接打開還是做頁面302重定向時候,必須帶此引數 |

這時,我們訪問,便會出現授權頁面
5、授權回呼
/**
* 授權回呼
*/
@GetMapping(value = "/callback")
public void callback(HttpServletRequest request) throws Exception {
HttpSession session = request.getSession();
// 得到Authorization Code
String code = request.getParameter("code");
// 我們放在地址中的狀態碼
String state = request.getParameter("state");
String uuid = (String) session.getAttribute("state");
// 驗證資訊我們發送的狀態碼
if (null != uuid) {
// 狀態碼不正確,直接回傳登錄頁面
if (!uuid.equals(state)) {
return PasswordUtils.redirectTo("/login");
}
}
// Step2:通過Authorization Code獲取Access Token
String url = "https://api.weixin.qq.com/sns/oauth2/access_token?" +
"appid=" + APPID +
"&secret=" + APPKEY +
"&code=" + code +
"&grant_type=authorization_code";
JSONObject resJson = HttpRequestUtils.httpRequestGet(url);
if (null == resJson) {
return PasswordUtils.redirectTo("/login");
}
String accessToken = resJson.getString("access_token");
String openId = resJson.getString("openid");
if (StringUtils.isBlank(accessToken) || StringUtils.isBlank(openId)) {
return PasswordUtils.redirectTo("/login");
}
url = "https://api.weixin.qq.com/sns/userinfo?" +
"access_token=" + accessToken +
"&openid=" + openId +
"&lang=zh_CN";
// Step3: 獲取微信用戶資訊
resJson = HttpRequestUtils.httpRequestGet(url);
/**
* TODO 這時就該寫自己的業務邏輯了
*/
}
- Step2 引數解釋如下:
| 引數 | 是否必須 | 說明 |
|---|---|---|
| appid | 是 | 公眾號的唯一標識 |
| secret | 是 | 公眾號的appsecret |
| code | 是 | 填寫第一步獲取的code引數 |
| grant_type | 是 | 填寫為authorization_code |
- Step3 引數解釋如下:
| 引數 | 是否必須 | 說明 |
|---|---|---|
| access_token | 是 | 網頁授權介面呼叫憑證,注意:此access_token與基礎支持的access_token不同 |
| openid | 是 | 用戶的唯一標識 |
| lang | 是 | 回傳國家地區語言版本,zh_CN 簡體,zh_TW 繁體,en 英語 |
6、網路請求方法
Step 2 和 Step 3 均為 GET 請求方式
/**
* GET 請求
*/
public static JSONObject httpRequestGet(String url) throws IOException {
CloseableHttpClient client = HttpClients.createDefault();
HttpGet httpGet = new HttpGet(url);
HttpResponse response = client.execute(httpGet);
HttpEntity entity = response.getEntity();
if (entity != null) {
String result = EntityUtils.toString(entity, "UTF-8");
return JSONObject.parseObject(result);
}
httpGet.releaseConnection();
return null;
}
三、檔案資料
關于微信授權登錄的檔案地址如下:
https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/Wechat_webpage_authorization.html
四、總結
該授權認證程序符合 OAuth2 認證基本流程,對于應用而言,其流程由獲取Authorization Code和通過Authorization Code獲取Access Token這2步組成,如圖所示:

如您在閱讀中發現不足,歡迎留言!!!
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/196739.html
標籤:java
