准备工具:微信开发者工具。
前台编译:
onLoad: function () {
var that = this;
// // 登录
wx.login({
success: res => {
// 发送 res.code 到后台换取 openId, sessionKey, unionId
if (res.code) {
//发起网络请求
wx.request({
url: 'http://******/WXServlet', (注1)
data: {
code: res.code
},
success: res => {
app.globalData.openid = res.data.openid;
console.log(res)
}
})
} else {
console.log('登录失败!' + res.errMsg)
}
}
})
}
注1:“http://localhost:8080/ZYJ_WXTest/WXServlet”时,微信小程序开发工具会报错。如果有服务器的小伙伴设置为你服务器的请求地址(ip地址是不可以的,需要域名地址),本地测试的小伙伴需要内网穿透,博主用的花生壳穿透的,6块钱申请,会免费送你一个域名。
后台代码:
@WebServlet("/WXServlet")
public class WXServlet extends HttpServlet{
/**
*
*/
private static final long serialVersionUID = 1L;
/*申请小程序给的APPID 和 APPSECRET*
private static final String APPID = "wxcc*****1ed7";
private static final String SECRET = "c7c64*******c1617294f";
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//设置请求编码
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
/* 设置响应头允许ajax跨域访问 */
response.setHeader("Access-Control-Allow-Origin", "*");
/* 星号表示所有的异域请求都可以接受, */
response.setHeader("Access-Control-Allow-Methods", "GET,POST");
//获取code
String code =request.getParameter("code"));
System.out.println("code="+code);
String url = "https://api.weixin.qq.com/sns/jscode2session?appid="+APPID+
"&secret="+SECRET+"&js_code="+ code +"&grant_type=authorization_code";
RestTemplate restTemplate = new RestTemplate();
//进行网络请求,访问url接口
ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.GET, null, String.class);
//根据返回值进行后续操作
if(responseEntity != null && responseEntity.getStatusCode() == HttpStatus.OK)
{
String sessionData = responseEntity.getBody();
Gson gson = new Gson();
//解析从微信服务器获得的openid和session_key;
JSONObject jsonResult = JSONObject.parseObject(sessionData.toString());
//这样就取到 openId和 session_key了//获取用户的唯一标识
String openId=jsonResult.getString("openid");
String key = jsonResult.getString("session_key");
System.out.println(jsonResult);
//下面就可以写自己的业务代码了
//最后要返回一个自定义的登录状态,用来做后续数据传输的验证
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}