小程序token有效期_微信小程序 token 过期时间后重新获取

本文介绍了微信小程序中token的管理,包括验证、获取及过期处理。通过封装的Token类,实现当本地token无效时从服务器重新获取,并在App启动时自动验证token的有效性。
摘要由CSDN通过智能技术生成

首先先封装个公用的jsclass Config{

constructor() {

}

}

Config.restUrl = 'https://wx.knowdao.com';

export { Config };123456789

再从另一个封装的共用的调token的js里面传入这个模块import { Config } from 'config.js';

class Token {

constructor() {

console.log(this)

this.verifyUrl = Config.restUrl + '/api/validate/token';

this.tokenUrl = Config.restUrl + '/api/login/get_openid';

}

verify() {

var token = wx.getStorageSync('token');

console.log(token)

if(!token) {

this.getTokenFromServer(token);

}else{

this._verifyFromServer(token);

}

}

// 携带令牌去服务器校验令牌

_verifyFromServer(token) {

console.log(11212)

var that = this;

const account = wx.getStorageSync("account")

// console.log(token)

// console.log(wx.getStorageSync("token"))

// console.log(account)

const tokenn = wx.getStorageSync("token")

wx.request({

url: that.verifyUrl,

method: 'POST',

data: {

token: tokenn,

account:account

},

success: function (res) {

console.log(res)

return false

var valid = res.data.isValid;

if (!valid) {

that.getTokenFromServer();

}

}

})

}

// 从服务器获取token

getTokenFromServer(callback) {

var that = this;

wx.login({

success: function(res) {

let code = res.code

wx.getUserInfo({

lang: "zh_CN",

success: res => {

let userInfo = res.userInfo

wx.request({

url: that.tokenUrl,

method: 'POST',

data: {

code: code,

nickname: userInfo.nickName,

gender: userInfo.gender,

avatarUrl: userInfo.avatarUrl,

city: userInfo.city

},

header: {

"content-type": "application/x-www-form-urlencoded",

'content-type': 'application/json'

},

success: function (res) {

console.log(res)

wx.setStorageSync('token', res.data.data.token);

wx.setStorageSync('account', res.data.data.account);

wx.setStorageSync('userid', res.data.data.user_id);

}

})

}

})

}

})

}

}

export { Token };123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990

最后在app.js中调用import { Token } from 'utils/token-model.js';

var scence = 0;

App({

onLaunch: function () {

var token = new Token();

token.verify();

// token.changlink("wss://wx.knowdao.com/system");

},

onShow: function () {

},

onHide: function () {

this.globalData.scence = 1

wx.setStorageSync('scence', this.globalData.scence)

},

globalData: {

account: '',

stroge: 0,

openid: 0,

userInfo: null,

times: null,

urls: 'https://wx.knowdao.com',

urlst: 'http://test.knowdao.com',

token: ''

}

})

作者:前端阿龙

链接:https://blog.csdn.net/weixin_42790916/article/details/82806337

来源:CSDN

著作权归作者所有,转载请联系作者获得授权,切勿私自转载。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值