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

时间:2023-03-08 19:10:32
微信小程序通过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包更改代码即可。