微信授权,接口需要调整为wx.getUserProfile
但是如果需要嵌套wx.login的话,需要考虑code和iv参数过期的问题。
所以使用Promise.all优雅地解决这个问题
直接上代码:
// 微信授权 getProfile 方式
function wxProfileLogin({
success,
fail
}) {
// login
const loginFunc = new Promise((resolve, reject) => {
wx.login({
success: res => { resolve(res) },
fail: err => {
if (typeof fail === 'function') fail("登录失败-wx.login")
reject(err)
}
})
})
// gerProfile
const userProfileFunc = new Promise((resolve, reject) => {
wx.getUserProfile({
lang: 'zh_CN',
desc: '用于完善用户资料',
success: res => { resolve(res) },
fail: err => {
if (typeof fail === 'function') fail("登录失败-wx.getUserProfile")
reject(err)
}
})
})
// 必须先login再getProfile,否则解析出来的code和iv过期
Promise.all([loginFunc, userProfileFunc]).then(([loginRes, userRes]) => {
const code = loginRes.code;
logicLogin({
code: code,
userInfo: userRes,
success: success,
fail: fail
})
}).catch(error => {
console.log('登录失败-' + JSON.stringify(error))
})
}
/**
* 业务逻辑登录
*/
function logicLogin({ code, userInfo, success, fail }) {
console.log('【loginService】开始登录业务服务器');
const app = getApp();
//发起登录请求
wx.request({
url: XXXXXXXXXXX,
header: {
'content-type': 'application/json',
'x-wx-code': code,
'x-wx-encrypted-data': userInfo.encryptedData,
'x-wx-iv': userInfo.iv,
'SYSTEM': wx.getSystemInfoSync().platform,
},
success: (resp) => {
console.log('[logic-Login]', resp);
const httpStatusCode = resp.statusCode;
if (httpStatusCode == 0 || httpStatusCode == 200) { // http请求成功
const data = resp.data;
if (data && data.errcode === 0) {
console.log("【loginService】", data);
**你的逻辑代码**
} else {
console.log('【loginService】用户信息不完善,登录失败!');
if (typeof fail === 'function') fail();
}
} else {
if (typeof fail === 'function') fail();
}
},
fail: () => {
if (typeof fail === 'function') fail();
}
})
}
---End---