java實現微信公衆號網頁受權,獲取用戶基本信息

1.網頁受權回調域名

在微信公衆號請求用戶網頁受權以前,須要先到公衆平臺官網中,修改受權回調域名,請注意,這裏填寫的是域名(是一個字符串),而不是URL,所以請勿加 http:// 等協議頭
圖片描述前端

2.網頁受權的兩種scope的區別

1)以snsapi_base爲scope發起的網頁受權,是用來獲取進入頁面的用戶的openid的,而且是靜默受權並自動跳轉到回調頁的。用戶感知的就是直接進入了回調頁(每每是業務頁面)ios

2)以snsapi_userinfo爲scope發起的網頁受權,是用來獲取用戶的基本信息的。但這種受權須要用戶手動贊成,而且因爲用戶贊成過,因此無須關注,就可在受權後獲取該用戶的基本信息。json

3.網頁受權流程分爲四步

1)引導用戶進入受權頁面贊成受權,獲取codeaxios

//前端發請請求
created() {
  this.axios.get('/wx/get_code').then((res) => {
    if (res.code == 0) {
      window.location.href = res.data;
    }
  }).catch((error) => {
    console.log(error)
  });
}

/**
 * 1.用戶贊成受權,獲取code
 */
@RequestMapping(value = "/get_code", method = RequestMethod.GET)
public String getWxCode() throws UnsupportedEncodingException {
    return "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + Constants.APPID + "&redirect_uri="
            + URLEncoder.encode("http://192.168.0.152:8080/get_auth_access_token", "UTF-8") + "&response_type=code&scope="
            + Constants.GRANTSCOPE + "&state=STATE#wechat_redirect";
}

scope等於snsapi_userinfo時的受權頁面
圖片描述api

2)經過code換取網頁受權access_token(與基礎支持中的access_token不一樣)微信

/**
 * 2.經過code換取網頁受權access_token
 */
@RequestMapping(value = "/get_auth_access_token", method = RequestMethod.GET)
public void getAuthAccessToken(HttpServletRequest request, HttpServletResponse response, String code) throws IOException {
    String urlToken = "https://api.weixin.qq.com/sns/oauth2/access_token";
    String accessTokenObj = HttpClientUtil.sendGet(urlToken, "appid=" + Constants.APPID + "&secret="
            + Constants.APPSECRET + "&code=" + code + "&grant_type=authorization_code");
    JSONObject jsonToken = JSONObject.fromObject(accessTokenObj);

    String openId = null;
    String accessToken = null;
    if (StringUtils.isNotBlank(String.valueOf(jsonToken))) {
        openId = jsonToken.getString("openid");
        accessToken = jsonToken.getString("access_token");
    }

    logger.info("openid={},access_token={}", openId, accessToken);
    }
}

3)若是須要,開發者能夠刷新網頁受權access_token,避免過時
因爲access_token擁有較短的有效期,當access_token超時後,可使用refresh_token進行刷新,refresh_token有效期爲30天,當refresh_token失效以後,須要用戶從新受權。微信開發

4)經過網頁受權access_token和openid獲取用戶基本信息(支持UnionID機制)app

/**
 * 2.經過code換取網頁受權access_token
 */
@RequestMapping(value = "/get_auth_access_token", method = RequestMethod.GET)
public void getAuthAccessToken(HttpServletRequest request, HttpServletResponse response, String code) throws IOException {
    String urlToken = "https://api.weixin.qq.com/sns/oauth2/access_token";
    String accessTokenObj = HttpClientUtil.sendGet(urlToken, "appid=" + Constants.APPID + "&secret="
            + Constants.APPSECRET + "&code=" + code + "&grant_type=authorization_code");
    JSONObject jsonToken = JSONObject.fromObject(accessTokenObj);

    String openId = null;
    String accessToken = null;
    if (StringUtils.isNotBlank(String.valueOf(jsonToken))) {
        openId = jsonToken.getString("openid");
        accessToken = jsonToken.getString("access_token");
    }

    logger.info("openid={},access_token={}", openId, accessToken);
    //3.拉取用戶信息(需scope爲 snsapi_userinfo)
    String urlInfo = "https://api.weixin.qq.com/sns/userinfo";
    String infoObj = HttpClientUtil.sendGet(urlInfo, "access_token=" + accessToken + "&openid=" + openId + "&lang=zh_CN");
    JSONObject jsonUserInfo = JSONObject.fromObject(infoObj);
    if (StringUtils.isNotBlank(String.valueOf(jsonUserInfo))) {
        String nickName = jsonUserInfo.getString("nickname");
        String headImgUrl = jsonUserInfo.getString("headimgurl");
        String sex = jsonUserInfo.getString("sex");
        response.sendRedirect("http://lyx1314520ll.w3.luyouxia.net/auth?nickName=" + nickName + "&headImgUrl=" + headImgUrl + "&sex=" + sex);
    }
}

unionid 只有在用戶將公衆號綁定到微信開放平臺賬號後,纔會出現該字段。測試

公衆號經過微信網頁受權機制後,重定向頁面
圖片描述網站

4.網頁受權遇到的問題

1)redirect_uri參數錯誤
測試微信公衆號回調地址支持域名和ip,正式公衆號回調地址只支持域名,不要加https://,http://這些前綴,如:www.baidu.com。
edirect_uri能夠是你網站下的任何頁面(不侷限於受權回調域配置的域名),可是必定要在前面加上http://,而且使用urlencode編碼。

2)該連接沒法訪問,code:-1
code做爲換取access_token的票據,每次用戶受權帶上的code將不同,code只能使用一次,5分鐘未被使用自動過時,從新獲取就好

想要了解更多內容能夠閱讀微信開發者文檔,裏面詳情的講解了這些內容https://mp.weixin.qq.com/wiki...

相關文章
相關標籤/搜索