https://developers.weixin.qq.com/community/develop/doc/0004e229464d78c1d557ed5e359404
https://blog.csdn.net/weixin_43055905/article/details/82222668
项目代码 //通过code生成token code不可反复使用,只能使用一次
token有缓存时间 到时间重新获取
onLoad: function () {
this.getCode();
},
getCode: function () {
let that = this;
let getovertime = wx.getStorageSync("overtime");//拿到过期时间
let nowtime = Date.parse(new Date()); //现在时间
nowtime = nowtime/1000;
if (getovertime < nowtime){ //过期
console.log('过期了')
wx.login({
success: function (res) {
app.globalData.code = res.code;//cede储存到全局
wx.removeStorageSync('token')
wx.setStorageSync('token', 'thisistoken')
let overtime = nowtime + 3600;// 设置过期时间2小时
wx.setStorageSync("overtime", overtime);
}
})
that.index();
}else{
that.index();
}
},
index(){
console.log('this is index')
},
getCode(){
let token = wx.getStorageSync('token');
if(token){
console.log("token存在. 进行校验.");
this.Getindex();
}else{
console.log("token不存在,正在重新拿token..");
wx.login({
success: function (res) {
console.log(res.code) //code
//发送code
BaseApi.save_update_openid({
code: res.code
}).then((res) => {
console.log(res);
if (res.data.status == 1) {
let datas = res.data.data;
wx.setStorageSync('open_id', datas.open_id)
app.globalData.open_id = datas.open_id //设置全局
}
}, (err) => {
})
}
})
}
}
const app = getApp();
//页面一加载获取code
getCode: function () {
let that = this;
wx.login({
success: function (res) {
console.log(res.code) //code
app.globalData.code = res.code;//cede储存到全局
//发送code
BaseApi.save_update_openid({
code: res.code
}).then((res) => {
console.log(res);
if (res.data.status == 1) {
let datas = res.data.data;
wx.setStorageSync('open_id', datas.open_id)
app.globalData.open_id = datas.open_id //设置全局
}
}, (err) => {
})
}
})
},
App({
globalData: {
openid:'',
'appid': "wx93d4137aeaafa1a4",
'secret': "fb96f74d42872b0ed67312eccd4bf868",
},
})
//user.js
const app = getApp();
Page({
/**
* 页面的初始数据
*/
data: {
openid: '',
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
this.getOpenid();
}
})