onLoad: function() {
wx.login({
success: res => {
this.data.code = res.code
console.log(res.code)
}
})
},
//点击获取用户手机号
getPhoneNumber: function(e) {
if (e.detail.errMsg !== “getPhoneNumber:ok”) {
return;
}
//拿到加密数据
var iv = e.detail.iv;
console.log(e.detail.iv)
var encryptedData = e.detail.encryptedData;
this.setData({
iv: iv,
encryptedData: encryptedData
})
//检查登录
wx.checkSession({
success: (res) => {
//session_key 未过期,并且在本生命周期一直有效
//传code
wx.request({
url: base.path.www + ‘/api/sysUser/authorizedLogin’,
data: {
// ‘encrypteData’: this.data.encryptedData,
// ‘iv’: this.data.iv,
‘code’: this.data.code,
},
method: ‘POST’, // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
header: {
‘content-type’: ‘application/x-www-form-urlencoded’
}, // 设置请求的 header
success: res => {
console.log(res)
let sKey = res.data.data.sKey;
wx.setStorageSync(‘sKey’, sKey);
//把用户标识放入globalData里
base.globalData.sessionId = sKey;
//请求电话号码接口
wx.request({
url: base.path.www + ‘/api/sysUser/getUserPhone’,
data: {
‘encrypteData’: this.data.encryptedData,
‘iv’: this.data.iv,
‘sKey’: sKey,
},
method: ‘POST’, // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
header: {
‘content-type’: ‘application/json’,
‘Cookie’: ‘JSESSIONID=’ + base.globalData.sessionId
}, // 设置请求的 header
success: res => {
console.log(res)
let userInfo = res.data.data.userInfo;
wx.setStorageSync(‘USER_INFO’, userInfo);
//把用户数据保存在user里供自动登录时用
var openid = userInfo.user.userWechat;
var phone = userInfo.phoneNumber;
var randKey = userInfo.user.randKey;
base.user.openid = openid;
base.user.phone = phone;
base.user.randKey = randKey;
console.log(base.user)
base.saveUser();
//转为登录状态
base.isLogin = true;
//给弹框信息传过去
base.globalData.isPopup = 1;
//跳转到首页
// wx.navigateTo({
// url: ‘/pages/index/index’,
// })
wx.navigateBack({
delta: 6
})
}
})
},
fail: function(err) {
console.log(err);
}
})
},
fail() {
// session_key 已经失效,需要重新执行登录流程
//重新登录
wx.login({
success: res => {
this.data.code = res.code
}
})
}
})
},
已解决,这是问题解决后的代码。需提前调用wx.login获取code,在点击获取手机号的时候在用checksession检查过期情况即可