【微信】根据appid, secret, code获取用户openid(Java版)

【微信】根据appid, secret, code获取用户openid

网页授权流程分为四步:
1、引导用户进入授权页面同意授权,获取code
2、通过code换取网页授权access_token(与基础支持中的access_token不同)
3、如果需要,开发者可以刷新网页授权access_token,避免过期
4、通过网页授权access_token和openid获取用户基本信息(支持UnionID机制)

微信官方文档: https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140842


public class WxOpenIdUtils {
    public static String login(String code, String appId, String secretKey) {
        // 创建Httpclient对象
        CloseableHttpClient httpclient = HttpClients.createDefault();
        String result = "";
        CloseableHttpResponse response;
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + appId + "&secret=" + secretKey + "&js_code=" + code + "&grant_type=authorization_code";
        try {
            // 创建uri
            URIBuilder builder = new URIBuilder(url);
            URI uri = builder.build();

            // 创建GET请求
            HttpGet httpGet = new HttpGet(uri);

            // 执行请求
            response = httpclient.execute(httpGet);
            // 判断返回状态是否为200
            if (response.getStatusLine().getStatusCode() == 200) {
                result = EntityUtils.toString(response.getEntity(), "UTF-8");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 解析json
        return ((JSONObject) JSONObject.parse(result)).get("openid") + "";

    }

}
posted @ 2021-06-24 14:36  ddgo's  阅读(737)  评论(0编辑  收藏  举报
.