微信授權登入


官網地址:https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/Wechat_webpage_authorization.html

官網提供的四個步驟

  1. 第一步:用戶同意授權,獲取code
  2. 第二步:通過code換取網頁授權access_token
  3. 第三步:刷新access_token(如果需要)
  4. 第四步:拉取用戶信息(需scope為 snsapi_userinfo)
  5. 附:檢驗授權憑證(access_token)是否有效

一、獲取code

  • 所需要的參數

image

  • 授權效果

image

  • 錯誤碼的返回

image

二、獲取access_token

第一步會獲得一個微信返回的code,拿着這個CODE 還有APPID還有公鑰往微信發送請求

// 1.調用getHTMLAccessToken
	JSONObject htmlAccessToken = WeChatUtil.getHTMLAccessToken(code);

	// 2.獲取用戶授權的微信地址
    public static  final String GET_HTML_ACCESS_TOKEN = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";


    /**
     * 3.根據code獲取access_token
     * @param code
     * @return access_token,open_id
     */

    public static JSONObject getHTMLAccessToken(String code) {

        String replace =GET_HTML_ACCESS_TOKEN.replace("APPID", WeChatResources.APPID).replace("SECRET", WeChatResources.APPSECRET).replace("CODE", code);
        log.info("請求url:{}",replace);
        JSONObject jsonObject = HttpUtil.doGet(replace);
        return jsonObject;
    }

    /**
     * 4.發送請求的doGET方法
     */
	    public static JSONObject doGet(String url) {
        HttpClient httpClient = HttpClientBuilder.create().build();
        HttpGet get = new HttpGet(url);
        JSONObject jsonObject = null;

        try {
            HttpResponse response = httpClient.execute(get);
            HttpEntity entity = response.getEntity();
            if (null != entity) {
                String result = EntityUtils.toString(entity);
                jsonObject = JSONObject.fromObject(result);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return jsonObject;
    }


//  5.方法響應成功后獲取access_token和openid
Object access_token = htmlAccessToken.get("access_token");
Object openid = htmlAccessToken.get("openid");
  • 參數說明

image

  • 返回參數說明

image

三、刷新access_token

image

  • 返回參數說明

image

四、拉取用戶信息

	//1.根據access_token,open_id獲取用戶信息  從而完成微信的授權登入
    JSONObject userInfo = WeChatUtil.getUserInfo(access_token, openid);


    //2.獲取用戶信息 openid
    public static  final String GET_USER_INFO = "https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN";

	 /**
     * 3.根據access_token,open_id獲取用戶信息
     * @return
     */
    public static JSONObject getUserInfo(Object access_token,Object open_id){

        String replace = GET_USER_INFO.replace("ACCESS_TOKEN", access_token.toString()).replace("OPENID", open_id.toString());
        JSONObject jsonObject = HttpUtil.doGet(replace);
        return jsonObject;
    }



  • 參數說明

image

  • 返回參數說明

image

  • 檢驗授權憑證(access_token)是否有效

image


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM