Java對接微信登錄

今天我們來對接微信開放平台的網站應用登錄

首先上文檔鏈接:https://developers.weixin.qq.com/doc/oplatform/Website_App/WeChat_Login/Wechat_Login.html


1. 第三方發起微信授權登錄請求,微信用戶允許授權第三方應用後,微信會拉起應用或重定向到第三方網站,並且帶上授權臨時票據code參數; 2. 通過code參數加上AppID和AppSecret等,通過API換取access_token; 3. 通過access_token進行介面調用,獲取用戶基本數據資源或幫助用戶實現基本操作。
 
文檔上說的也很明白
 
首先我們需要註冊一個開放平台的帳號
image但是吧很不爽的是需要企業認證花300RMB進行資質認證。
  
imageok,我們先來創建一個網站應用
image就是這樣進行填寫就行了
  
填寫完,狀態為通過就可以開始微信登錄的開發了。
image
  
然後我們需要知道三個資訊imageimage
  
ok,配置資訊完成了
  
讓我們繼續來看微信開放平台的文檔
  
image第一步:請求code

這邊請求需要帶上相應的參數

 

 

 redirect_uri是回調地址uri剛才配置的授權回調域填上並加上介面 or html,這個可以根據自己的業務來,這裡我是填上介面

 

這個urlEnCode處理,網上有很多在線工具:https://tool.chinaz.com/tools/urlencode.aspx

 

然後根據微信開發文檔填寫對應的資訊

 

https://open.weixin.qq.com/connect/qrconnect?

appid=xxxxxxxxx&redirect_uri=https%3a%2f%2fwww.baidu.com%2frequestWechatLogin&response_type=code&scope=snsapi_login&state=STATE#wechat_redirect

上面資訊是我隨便填寫的,開發時請根據自己的資訊填寫

 

ok,完成後打開此鏈接就會進入到該頁面,就可以開始登錄了。

 

 

 

 

 

使用手機端微信掃描,

 

注意:每次每個用戶授權後都會得到一個一次性的code,這個code只能使用一次 ,下次再授權登錄會重新生成code的!!!

 

 

https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code

鏈接參數根據微信開放平台配置對應填寫

 

 

 

 

 

 




因為我這邊redirect_uri填寫的是一個介面,就需要寫一個介面,我就直接上程式碼了,這裡有封裝的類和枚舉,我就不展示了大家可以修改!!!

 

 1 /**   2      * 請求 code web微信登錄   3      *   4      * @param code 請求登錄唯一 code   5      * @return 通用返回對象   6      */   7     @ApiOperation("請求 code 微信登錄")   8     @ApiImplicitParam(name = "code", value = "請求登錄唯一code", dataType = "String", paramType = "query")   9     @GetMapping("/requestWeChatLogin")  10     public ApiResult requestWeChatLogin(@RequestParam("code") String code) {  11         // 斷言為空則拋出異常  12         Assert.notNull(code, "未授權成功");  13         String appId = "xxxxxxxxx";  14         String secret = "xxxxxxxxxxxxxxxxxx";  15         String strUri = StrUtil.format("https://api.weixin.qq.com/sns/oauth2/access_token?appid={}&secret={}&code={}&grant_type=authorization_code", appId, secret, code);  16         // 使用 Hutool開發工具包,執行請求介面,根據code獲取相關資訊  17         HttpResponse response = HttpRequest.get(strUri).execute();  18         // 轉成JSON對象  19         JSONObject jsonObject = JSONUtil.parseObj(response.body());  20         // 判斷JSON對象中 unionid 是否存在  21         if (jsonObject.isNull("unionid")) {  22             // 不存在返回結果,code無效  23             return new ApiResult(CommonEnum.CODE_INVALID);  24         }  25         // 獲取 unionId  26         String unionId = jsonObject.get("unionid").toString();  27         // 獲取 openId  28         String openId = jsonObject.get("openid").toString();  29         // 獲取 accessToken  30         String accessToken= jsonObject.get("access_token").toString();  31         return new ApiResult(CommonEnum.SUCCESS);  32     } 

 

這樣一頓操作後,就可以根據code獲取到掃碼授權用戶的一些資訊,

比如可以根據 access_token&openid 來獲取用戶個人資訊

該保存資料庫可以保存,有別的操作自行編寫!!!  

Tags: