網頁授權 根據 code 獲取請求用戶信息的 accessToken

  

 private static final Logger LOGGER = Logger.getLogger(XXX.class);




 /**
     * 網頁獲取請求用戶信息的access_token
     *
     * @param code
     * @return
     */
    public static Map<String, String> getUserInfoAccessToken(String code,String appId,String appSecret) {
        JsonObject object = null;
        Map<String, String> data = new HashMap<>();
        try {
            String url = String.format("https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code",
                    appId, appSecret, code);
            LOGGER.info("request accessToken from url: {" + url + "}");
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpGet httpGet = new HttpGet(url);
            HttpResponse httpResponse = httpClient.execute(httpGet);
            HttpEntity httpEntity = httpResponse.getEntity();
            String tokens = EntityUtils.toString(httpEntity, "utf-8");
            Gson token_gson = new Gson();
            object = token_gson.fromJson(tokens, JsonObject.class);
            LOGGER.info("request accessToken success. [result={" + object + "}]");

            data.put("openid", object.get("openid").toString().replaceAll("\"", ""));
            data.put("access_token", object.get("access_token").toString().replaceAll("\"", ""));
            JsonElement unionId = object.get("unionid");
            if(null != unionId){
                data.put("unionId", unionId.toString().replaceAll("\"", ""));
            }
        } catch (Exception ex) {
            LOGGER.error("fail to request wechat access token. [error={" + ex + "}]");
        }
        return data;
    }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章