前端代码:
小程序登录时获取code
wx.login({
success: res => {
// 发送 res.code 到后台换取 openId, sessionKey, unionId
//that.data.url 你的服务器地址
wx.request({
url: that.data.url + '/mini_Weixin_getOpenId.action',
data:{"code":res.code},
method:'GET',
header: {
'content-type': 'application/json'
},
success: function (res) {
openId = res.data;
}
})
}
})
后端代码:
controller类:
public String getOpenId(String code){
String url = " https://api.weixin.qq.com/sns/jscode2session?appid="+小程序appid+"&secret="+小程序appsecret+"&js_code="+code+"&grant_type=authorization_code";
String rst = doGet(url, "GBK");
System.out.println("rst==="+rst);
logger.info("rst==="+rst);
try {
String tmp = "\"openid\":\"";
rst = rst.substring(rst.indexOf(tmp)+tmp.length());
rst = rst.substring(0, rst.indexOf("\""));
} catch (Exception e) {
e.printStackTrace();
rst = "";
}
return rst;
}
util类
/**
* http get 提交
* @param url
* @param charset
* @return
*/
public static String doGet(String url, String charset) {
try {
URL httpURL = new URL(url);
HttpURLConnection http = (HttpURLConnection) httpURL
.openConnection();
http.setRequestProperty("Content-type", "text/html");
BufferedReader br = new BufferedReader(new InputStreamReader(http
.getInputStream(), charset));
StringBuilder sb = new StringBuilder();
String temp = null;
while ((temp = br.readLine()) != null) {
sb.append(temp);
sb.append("\n");
}
br.close();
return sb.toString();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
完。。。