网页授权 根据 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;
    }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值