1.在 app.js里边写入微信登录时,发送登陆者的 res.code 到后台换取 openId, sessionKey, unionId 代码如下:
// 登录
wx.login({
success: res => {
// 发送 res.code 到后台换取 openId, sessionKey, unionId
console.log(res.code);
wx.request({
url: this.globalData.url.session,
data:{
code:res.code
},
success:res=>{
console.log(res);
console.log(res.header['Set-Cookie']);
wx.setStorage({
key: 'session_id',
data: res.header["Set-Cookie"],
})
}
})
}
})
2.获取用户的信息,若已经授权,可以直接调用 getUserInfo 获取头像昵称,不会弹框,可以将 res 发送给后台解码出 unionId
由于 getUserInfo 是网络请求,可能会在 Page.onLoad 之后才返回,所以此处加入 callback 以防止这种情况,代码如下:
// 获取用户信息
wx.getSetting({
success: res => {
if (res.authSetting['scope.userInfo']) {
// 已经授权,可以直接调用 getUserInfo 获取