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

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

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

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

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

posted @ 2017-08-02 13:48  __lay  阅读(26050)  评论(1编辑  收藏  举报