微信小程序登录状态校验及token校验实现
首先全局util工具js中写两个校验方法:
// 判断当前时间token是否已过期
const isTokenExpired = () => {
let curTime = new Date();
//上一次登录的时间
let loginTime = wx.getStorageSync('login_time');
// token过期时间
let expiresTime = wx.getStorageSync('expires_in');
// 若无这两个值,直接返回过期状态
if (!loginTime || !expiresTime) {
return true
}
// 判断当前时间是否大于即将过期时间
if (curTime - loginTime > expiresTime * 1000) {
return true
}
return false;
}
// 检查接口返回中token是否过期
const checkTokenExpired = (resp) => {
//服务器返回的token过期code为1004
if (resp.data.code == 1004) {
// 清理本地缓存中的token与token过期时间
wx.removeStorageSync('auth_token')
wx.removeStorageSync('expires_in')
wx.removeStorageSync('login_time')
wx.showToast({
title: '登录状态已失效,请重新登陆',
icon: 'none',
duration: 3000
})
// 跳转到登录页,要求用户重新登录
wx.navigateTo({
url: '/pages/login/login',
})
}
}
module.exports = {
isTokenExpired,
checkTokenExpired
}
其中,isTokenExpired方法用在app.js中,体现于生命周期onLaunch中:
// app.js
const util = require('./utils/util')
// 版本更新监测
const updateManager = wx.getUpdateManager()
updateManager.onCheckForUpdate(function (res) {
// 请求完新版本信息的回调
console.log(res.hasUpdate)
})
updateManager.onUpdateReady(function () {
wx.showModal({
title: '更新提示',
content: '新版本已经准备好,是否重启应用?',
success(res) {
if (res.confirm) {
// 新的版本已经下载好,调用 applyUpdate 应用新版本并重启
updateManager.applyUpdate()
}
}
})
})
updateManager.onUpdateFailed(function () {
// 新版本下载失败
})
App({
apiInfo: {
host: 'https://xxx.com'
},
onLaunch() {
// 展示本地存储能力
const logs = wx.getStorageSync('logs') || []
logs.unshift(Date.now())
wx.setStorageSync('logs', logs)
// 启动后判断token是否过期,若过期则跳转登录页,否则跳转到主页
const auth_token = wx.getStorageSync('auth_token') || '';
if (auth_token) {
const isExpired = util.isTokenExpired();
// token已过期
if (isExpired) {
// 清理本地缓存中的token与token过期时间
wx.removeStorageSync('auth_token')
wx.removeStorageSync('expires_in')
wx.removeStorageSync('login_time')
}
}
// 登录
wx.login({
success: res => {
// 发送 res.code 到后台换取 openId, sessionKey, unionId
}
})
},
globalData: {
userInfo: null
}
})
ps:apiInfo的配置是全局接口域名配置
checkTokenExpired方法则用于接口请求后,举个栗子:
(获取一个详情接口)
请求之前先在js文件上方引入app和util:
const app = getApp();
const util = require('../../utils/util.js');
发起请求的方法:
// 获取游戏详情信息
getGameInfo: function () {
wx.showLoading({
title: '游戏详情获取中',
mask: true
})
const that = this;
const auth_token = wx.getStorageSync('auth_token') || '';
wx.request({
url: app.apiInfo.host + '/vip/game/detail',
method: 'GET',
data: {
game_id: this.data.gameId
},
header: {
'content-type': 'application/json',
'AuthToken': auth_token
},
success(res) {
util.checkTokenExpired(res);
if (res?.data?.code === 0) {
const {
gameInfo,
isBind,
privilege,
isLogin
} = res?.data?.data || {};
that.setData({
isLogin: isLogin,
isBind: isBind,
actionList: privilege || [],
bannerInfo: gameInfo || [],
gameBanner: gameInfo?.banner || [],
gameDesc: gameInfo?.desc || '',
gameName: gameInfo?.name || '',
})
wx.hideLoading()
} else {
wx.hideLoading()
wx.showToast({
title: res?.data?.msg || '游戏详情获取失败',
icon: 'none',
duration: 3000
})
}
}
})
},
success回调中,可以看到首先使用util.checkTokenExpired(res)进行了token状态的校验,校验通过后会继续向下执行,否则会退出登录状态,并返回到登录页。

浙公网安备 33010602011771号