rest Template获取openid

//注意:
//1.getForObject的url不能直接拼接
//2.微信返回给你的错误码可能是忽悠你的

    private String getWeChatIdByWeChatCode(String code) {
        RestTemplate restTemplate = new RestTemplate();
        final String appId = "884237c58888ec1e";
        final String secret = "8888e95b88108";
        final String authorizationCode = "authorization_code";
        String url = "https://api.weixin.qq.com/sns/jscode2session" +
                "?appid={appId}&secret={secret}&js_code={code}&grant_type={authorizationCode}";
        Map<String,String> params = new HashMap<>();
        params.put("appId", appId);
        params.put("secret", secret);
        params.put("code",code);
        params.put("authorizationCode", authorizationCode);

        String resultMapStr = restTemplate.getForObject(url, String.class, params);
        HashMap<String, String> hashMap = JSON.parseObject(resultMapStr, HashMap.class);
//微信服务器返回成功与失败格式如下:
//        {"session_key":"RQTCSXszF\/GVhlmHRICQEw==","openid":"oazGY5NjEPE7i-Za-Q6OpoByt5RI"}
//        {"errcode":40029,"errmsg":"invalid code, hints: [ req_id: 5fbdJRNre-l ]"}
        final String openid = hashMap.get("openid");
        if (StringUtils.isEmpty(openid)) {
            System.out.println("openid为空");
            throw new NstException("对不起,openid为空");
        }
        return openid;
    }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值