const app = getApp();
Page({
data: {
// 登陆按钮现实隐藏
loginBtn: false,
// 全局是否登陆
loginShow: false,
// 用户信息
userInfo: {}
},
async onLoad() {
const _res = await app._checkLogin();
this.setData({
loginBtn: _res,
loginShow: _res,
userInfo: app.globalData.userInfo
});
},
// 登陆
async _login() {
const _res = await app._getUserInfo();
_res &&
this.setData({
userInfo: app.globalData.userInfo,
loginBtn: false
}),
this.onLoad();
},
// 关闭登陆弹窗
onClose(e) {
this.setData({
loginBtn: e.type == "click" ? !this.data.loginBtn : false
});
}
});
App({
onLaunch: function () {
// 全局变量
this.globalData = {
openId: wx.getStorageSync('openId'),
userInfo: wx.getStorageSync('userInfo')
};
if (!wx.cloud) {
console.error('请使用 2.2.3 或以上的基础库以使用云能力');
} else {
wx.cloud.init({
// env 参数说明:
// env 参数决定接下来小程序发起的云开发调用(wx.cloud.xxx)会默认请求到哪个云环境的资源
// 此处请填入环境 ID, 环境 ID 可打开云控制台查看
// 如不填则使用默认环境(第一个创建的环境)
// env: 'my-env-id',
traceUser: true,
});
}
// 微信小程序获取版本更新
const updateManager = wx.getUpdateManager()
updateManager.onCheckForUpdate(function (res) {
// 请求完新版本信息的回调
})
updateManager.onUpdateReady(function () {
wx.showModal({
title: '小韩提示',
content: '新版来袭,速来体验!',
success: function (res) {
if (res.confirm) {
updateManager.applyUpdate()
}
}
})
})
updateManager.onUpdateFailed(function () {
// 新版本下载失败
});
// 获取OpedId
this._getOpenId()
},
// 获取用户OpenId
_getOpenId() {
((this.globalData.openId || '') == '') && wx.cloud.callFunction({
name: 'login'
}).then(res => {
this.globalData.openId = res.result.openid;
wx.setStorageSync('openId', res.result.openid)
}).catch(res => {
console.error(res)
});
},
// 判断是否登陆
async _checkLogin() {
const _this = this
return new Promise((resolve) => {
wx.checkSession({
success: function (_res) {
const _userInfo = wx.getStorageSync('userInfo');
resolve((_userInfo || '') === '')
},
fail: async function (_res) {
await wx.login({})
resolve(true)
}
})
})
},
// 获取用户信息并存储
async _getUserInfo() {
return new Promise((resolve) => {
wx.getUserProfile({
desc: 'get用户信息',
success: async res => {
res.userInfo.openid = this.globalData.openId
this.globalData.userInfo = res.userInfo
wx.setStorageSync('userInfo', res.userInfo)
resolve(true)
},
fail: () => {
resolve(false)
}
});
})
},
});
});