WeChatウィジェットtokenの有効期限が過ぎたら再取得します.
3182 ワード
まず公用のjsをカプセル化します.
class Config{
constructor() {
}
}
Config.restUrl = 'https://wx.knowdao.com';
export { Config };
もう一つのパッケージの共用の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 };
最後にap.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: ''
}
})