onLaunch: async function (options) { this.init() var _this = this; let menuButtonObject = wx.getMenuButtonBoundingClientRect(); wx.getSystemInfo({ success: res => { let statusBarHeight = res.statusBarHeight, navTop = menuButtonObject.top, navHeight = statusBarHeight + menuButtonObject.height + (menuButtonObject.top - statusBarHeight) * 2; this.globalData.navHeight = navHeight; this.globalData.navTop = navTop; this.globalData.windowHeight = res.windowHeight; }, fail(err) { console.log(err); } }) const res = await wx.cloud.callFunction({name: 'getServerTime'}); // 使用await等待异步请求结果 console.log('服务器时间:',res.result) const cloudTimeStamp = res.result;// 需要从res中取出result console.log('服务器时间:',cloudTimeStamp) // 获取小程序系统时间戳 const systemTimeStamp = Date.now(); console.log('运行环境系统时间:',systemTimeStamp) // 计算时间戳差值,单位为秒 const diff = Math.abs(cloudTimeStamp - systemTimeStamp) / 1000; console.log('时间差值:',diff) // 如果时间戳差值大于一定值,则认为小程序系统时间被篡改 if (diff > 100) { wx.showToast({ title: '小程序系统时间被篡改,请检查时间设置', icon: 'none', }); return; } },怎么修改这段代码,如果系统时间被篡改就不允许运行小程序
时间: 2023-12-02 09:06:22 浏览: 157
你可以在时间戳差值大于一定值的情况下,将整个小程序退出,代码修改如下:
```javascript
onLaunch: async function (options) {
this.init()
var _this = this;
let menuButtonObject = wx.getMenuButtonBoundingClientRect();
wx.getSystemInfo({
success: res => {
let statusBarHeight = res.statusBarHeight,
navTop = menuButtonObject.top,
navHeight = statusBarHeight + menuButtonObject.height + (menuButtonObject.top - statusBarHeight) * 2;
this.globalData.navHeight = navHeight;
this.globalData.navTop = navTop;
this.globalData.windowHeight = res.windowHeight;
},
fail(err) {
console.log(err);
}
})
const res = await wx.cloud.callFunction({name: 'getServerTime'}); // 使用await等待异步请求结果
console.log('服务器时间:',res.result)
const cloudTimeStamp = res.result;// 需要从res中取出result
console.log('服务器时间:',cloudTimeStamp)
// 获取小程序系统时间戳
const systemTimeStamp = Date.now();
console.log('运行环境系统时间:',systemTimeStamp)
// 计算时间戳差值,单位为秒
const diff = Math.abs(cloudTimeStamp - systemTimeStamp) / 1000;
console.log('时间差值:',diff)
// 如果时间戳差值大于一定值,则认为小程序系统时间被篡改
if (diff > 100) {
wx.showModal({
content: '小程序系统时间被篡改,请检查时间设置',
showCancel: false,
success (res) {
if (res.confirm) {
wx.navigateBack({
delta: 1
})
}
}
})
}
},
```
这里我使用了 `wx.showModal` 方法来提示用户,同时在用户确认后使用 `wx.navigateBack` 方法返回上一页,让用户退出小程序。
阅读全文