微信公众号code换取openId

  微信网页授权的时候,不管是静默授权还是显示的用户点击授权,我们都能够拿到用户的code,详见官方文档

  拿到用户的code之后我们就可以根据我们的已有的appid和sercet拿到openId。

  

public class WeChatUserInfoTest {

    public static String getOpenId(String code, String appId, String appSecret) {
        Map<String, String> params = new HashMap<>();
        params.put("appid", appId);
        params.put("secret", appSecret);
        params.put("code", code);
        params.put("grant_type", "authorization_code");
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token";
        String response = HttpClientUtil.doGet(url, params);
        JSONObject object = JSONObject.parseObject(response);

        String openId = object.getString("openid");
        return openId;
    }
    public static void main(String[] args) {
        String appId = "";//对应的appId
        String appSecret = "";//对应的appSecret
        String code = "";//前端获取到的用户code
        String openId = getOpenId(appId, appSecret, code);
        System.out.println(openId);
    }
}

猜你喜欢

转载自blog.csdn.net/qq_26400953/article/details/84282557