背景:
最近公司有新项目要启动,之前项目在登录的流程中需要用户授权手机号,不符合小程序运营规范,故决定此次进行梳理整改一下登录的相关流程。
分析:
根据官方的示例(https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/login.html),针对C端业务token的管理,输出该流程图,如下所示:
代码实现:
app.js
// 登录
login() {
return new Promise((resolve, reject) => {
const userInfo = wx.getStorageSync('userinfo')
if (userInfo) {
resolve(userInfo)
} else {
wx.login({
success: (res) =>{
console.log(res)
// 获取业务token,及个人信息接口
setTimeout(() => {
const res = {
token: "iahsoiyiuaiu798=23492ib2hbjds823sdkajhgkas=",
userInfo: {
mobile: '18755131234',
nickName: 'xxx',
imgUrl: 'https:/xxxx'
}
}
wx.setStorageSync('userinfo', res)
resolve(res)
}, 0)
}
})
}
})
xxx页面.js:
const app = getApp()
Page({
data: {
isBandMobile: false // 是否绑定手机号
},
onLoad() {
// 登录
app.login().then(res => {
console.log(res)
const { userInfo: { mobile } } = res
this.setData({
isBandMobile: Boolean(mobile)
})
})
},
// 绑定手机号
getPhoneNumber (e) {
console.log(e.detail.code)
},
// 业务
todo() {
// todo
},
})
request.js:
let isRefreshing = true;
let subscribers = [];
function onAccessTokenFetched() {
subscribers.forEach((callback) => {
callback();
})
subscribers = [];
}
function addSubscriber(callback) {
subscribers.push(callback)
}
export class Http {
constructor() {}
request({ url, data = {}, method, header, callback = ''} = {}) {
let _this = this;
return new Promise((resolve, reject) => {
wx.request({
url,
data,
method,
header: { Authorization: 'Bearer ' + wx.getStorageSync('userinfo').token },
callback,
fail(res) {
reject(res)
},
complete: res => {
if (callback) return callback(res.data);
let statusCode = res.statusCode;
if (statusCode == 404) {
console.log('接口不存在')
} else if (statusCode == 401) {
// 将需要重新执行的接口缓存到一个队列中
addSubscriber(() => {
_this.request({ url, data, method, header, callback: resolve })
})
if (isRefreshing) {
refreshToken(url, data).then(() => {
// 依次去执行缓存的接口
onAccessTokenFetched();
isRefreshing = true;
})
}
isRefreshing = false;
} else if (statusCode == 200) {
resolve(res.data)
} else if (statusCode.startsWith('5')) {
wx.showModal({ content: '服务器报错,请重试!', showCancel: false });
}
}
})
})
}
}
// 获取token
const refreshToken = () => {
return new Promise((resolve, reject) => {
wx.login({
success: (res) =>{
console.log(res)
// 获取业务token,及个人信息接口
setTimeout(() => {
const res = {
token: "iahsoiyiuaiu798=23492ib2hbjds823sdkajhgkas=",
userInfo: {
mobile: '18755131234',
nickName: 'xxx',
imgUrl: 'https:/xxxx'
}
}
wx.setStorageSync('userinfo', res)
resolve(res)
}, 0)
}
})
})
}
代码片段:https://developers.weixin.qq.com/s/d2uFwHm17mBg
总结:
此流程中主要将获取用户手机号,从登录流程中剥离出去,使得登录流程更加解耦,以用户openid作为唯一标识,将授权手机号后置,当具体某业务中需要用户手机号时,再去获取。根据自己的业务需要,在“个人中心”页面也可以提供修改绑定手机号的入口即可。关于头像和昵称的话,也在个人中心去获取即可。