话不多说,直接开车
1.微信公众平台获取凭证
获取appid和appSecret 目前凭证不在页面显示,需要手动获取后记住。
2.小程序端登录后发送请求
这是app.js 主要部分为wx.login那里
//app.js
App({
onLaunch: function () {
// 展示本地存储能力
var logs = wx.getStorageSync('logs') || []
logs.unshift(Date.now())
wx.setStorageSync('logs', logs)
// 登录
wx.login({
success: res => {
console.log(res.code)
wx.request({
url: 'http://localhost:8080/user/login?pw='+res.code,
method:'GET',
header: {
//'content-type': 'application/x-www-form-urlencoded' // 默认是json
},
success: function (res) {
console.log(res);
},
fail: function (res) {
console.log(".....fail.....");
}
})
// 发送 res.code 到后台换取 openId, sessionKey, unionId
}
})
// 获取用户信息
wx.getSetting({
success: res => {
if (res.authSetting['scope.userInfo']) {
// 已经授权,可以直接调用 getUserInfo 获取头像昵称,不会弹框
wx.getUserInfo({
success: res => {
// 可以将 res 发送给后台解码出 unionId
this.globalData.userInfo = res.userInfo
// 由于 getUserInfo 是网络请求,可能会在 Page.onLoad 之后才返回
// 所以此处加入 callback 以防止这种情况
if (this.userInfoReadyCallback) {
this.userInfoReadyCallback(res)
}
}
})
}
}
})
},
globalData: {
menuIdx:0,
userInfo: null
}
})
其中若使接口能够调通,需在开发这工具中做如下设置
3.后台代码
@GetMapping("/getOpenid")
public String getOpenId(String code){
//微信那边的接口,grant_type=authorization_code是固定的
String url="https://api.weixin.qq.com/sns/jscode2session?appid="+APPID+
"&secret="+SECRET+"&js_code="+ code +"&grant_type=authorization_code";
//发送请求给微信后端
try{
String e = Jsoup.connect(url).get().body().text();
System.out.println(e.toString());
}catch (Exception e){
e.printStackTrace();
}
return "";
}
发送请求我用的Jsoup,版本1.13.1 自己去maven库找包