微信小程序通过CODE换取session_key和openid

微信小程序的用户信息获取需要请求微信的服务器,通过小程序提供的API在小程序端获取CODE,然后将CODE传入到我们自己的服务器,用我们的服务器来换取session_key和openid。

小程序端比较简单,从教程的API部分把代码拷贝到小程序里就好了,这里将提供一个javaweb服务器端换取session_key和openid的代码示例



@Value("${weixin.app_id}") // spring配置文件配置了appID
    private String appId;
    
    @Value("${weixin.app_secret}") // spring配置文件配置了secret
    private String secret;
    
    @RequestMapping("/openId")
    @ResponseBody
    public Map<String, Object> openId(String code){ // 小程序端获取的CODE
        Map<String, Object> result = new HashMap<>();
        result.put("code", 0);
        try {
            boolean check = (StringUtils.isEmpty(code)) ? true : false;
            if (check) {
                throw new Exception("参数异常");
            }
            StringBuilder urlPath = new StringBuilder("https://api.weixin.qq.com/sns/jscode2session"); // 微信提供的API,这里最好也放在配置文件
            urlPath.append(String.format("?appid=%s", appId));
            urlPath.append(String.format("&secret=%s", secret));
            urlPath.append(String.format("&js_code=%s", code));
            urlPath.append(String.format("&grant_type=%s", "authorization_code")); // 固定值
            String data = HttpUtils.sendHttpRequestPOST(urlPath.toString(), "utf-8", "POST"); // java的网络请求,这里是我自己封装的一个工具包,返回字符串
            System.out.println("请求结果:" + data);
            String openId = new JSONObject(data).getString("openid");
            System.out.println("获得openId: " + openId);
            result.put("openId", openId);
        } catch (Exception e) {
            result.put("code", 1);
            result.put("remark", e.getMessage());
            e.printStackTrace();
        }
        return result;
    }



请求以上这个控制器将返回openId,注意data中还有session_key也可以从这里取出来使用,至于JSON的处理方式,根据自己项目中的jar包更改代码即可。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值