//注意:
//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;
}