去年暑期做的一个小程序的项目还剩最后一点收尾工作没做完,还差一个在服务端获取用户的openid的接口,因为是第一次写,所以查了点资料。
最后代码如下:
@RequestMapping(value="/wxlogin",method = RequestMethod.GET)
public JSONObject login(String code){
JSONObject jsonObject = new JSONObject();
try{
if(code == null || code.equals("")){
jsonObject.put("errcode","10001");
jsonObject.put("errmsg","数据传输错误,code为空");
return jsonObject;
}
Map<String, String> data = new HashMap<String, String>();
data.put("appid", "此处填写appid");
data.put("secret", "此处填写secret");
data.put("js_code", code);
data.put("grant_type", "authorization_code");
String response = HttpRequest.get("https://api.weixin.qq.com/sns/jscode2session").form(data).body();
jsonObject = JSON.parseObject(response);
System.out.println(jsonObject);
}catch (Exception ex){
jsonObject.put("errcode","10004");
jsonObject.put("errmsg","获取失败,发生未知错误");
}
return jsonObject;
}
我是直接在controller层写的,如果有错误欢迎指正。