小程序登录流程整理
流程图
![流程图.jpg][https://photoserver-1254285921.cos.ap-beijing.myqcloud.com/xcx-login.png]
代码示例
function wxLogin() {
// 调用wx.login
wx.login({
success: (res) => {
// 获取到code
const CODE = res.code
wx.showToast({
title: '数据加载中',
icon: 'loading',
})
// 使用code和后端换取openid,sessionKey
request(
'后端提供的接口',
'POST',
{
code: CODE,
},
{
'content-type': 'application/json',
},
)
.then((res) => {
wx.hideToast()
if (res.data.InfoState === 0) {
getUserInfo()
.then
// 成功后的处理
()
.catch
// 失败后的处理
()
}
})
.catch((result) => {
// 请求失败重新处理
wx.showModal({
title: '提示',
content: '请求失败',
confirmText: '重新请求',
success(res) {
if (res.confirm) {
request(
'后端提供的接口',
'POST',
{
code: CODE,
},
{
'content-type': 'application/json',
},
)
}
else if (res.cancel) {
console.log('用户点击取消')
}
},
})
})
},
})
}
// 判断用户是否授权
function getUserInfo() {
return new Promise((resolve, reject) => {
wx.getUserInfo({
success(res) {
resolve(res)
},
fail(res) {
// eslint-disable-next-line prefer-promise-reject-errors
reject('我还没有授权')
},
})
})
}
// 封装请求
function request(url, method, data, header) {
return new Promise((resolve, reject) => {
wx.request({
url,
data,
header,
method,
timeout: 0,
success: (result) => {
resolve(result)
},
fail: (res) => {
reject(res)
},
})
})
}
更新判断登录信息失效
// 验证登录是否过期
function checksession() {
wx.checkSession({
success(res) {
console.log('登录未过期')
},
fail(res) {
console.log('登录过期')
wx.showModal({
title: '提示',
content: '你的登录信息过期了,请重新登录',
})
// 再次调用wxLogin()
wxLogin().then((res) => {
// 登录成功存储用户信息
getUserInfo()
})
},
})
}
// 获取用户的信息
function getUserInfo() {
wx.getUserInfo({
success(res) {
console.log(res.userInfo)
getApp().globalData.city = res.userInfo.city
getApp().globalData.country = res.userInfo.country
getApp().globalData.nickName = res.userInfo.nickName
getApp().globalData.province = res.userInfo.province
},
})
}
Comments