90 lines
2.5 KiB
JavaScript
90 lines
2.5 KiB
JavaScript
// app.js
|
|
const { BASE_URL, API } = require('./utils/config')
|
|
const { request } = require('./utils/api')
|
|
|
|
App({
|
|
onLaunch() {
|
|
// 优先从本地缓存恢复登录态,避免阻塞页面
|
|
const cached = wx.getStorageSync('userInfo')
|
|
if (cached && cached.openid) {
|
|
this.globalData.userInfo = cached
|
|
this.globalData.isLoggedIn = true
|
|
}
|
|
// 静默登录获取最新 session,不阻塞页面
|
|
this.silentLogin()
|
|
},
|
|
|
|
silentLogin() {
|
|
this._loginPromise = new Promise((resolve) => {
|
|
this._loginResolve = resolve
|
|
wx.login({
|
|
success: (loginRes) => {
|
|
if (loginRes.code) {
|
|
this.loginWithCode(loginRes.code)
|
|
} else {
|
|
console.error('wx.login 失败', loginRes.errMsg)
|
|
this.handleLoginFail()
|
|
}
|
|
},
|
|
fail: (err) => {
|
|
console.error('wx.login 调用失败', err)
|
|
this.handleLoginFail()
|
|
}
|
|
})
|
|
})
|
|
},
|
|
|
|
/**
|
|
* 返回登录完成的 Promise,供页面 await 使用
|
|
* @param {boolean} useCache - 是否在已有缓存时立即 resolve
|
|
* @returns {Promise<object|null>}
|
|
*/
|
|
waitLogin(useCache = false) {
|
|
if (useCache && this.globalData.isLoggedIn) {
|
|
return Promise.resolve(this.globalData.userInfo)
|
|
}
|
|
return this._loginPromise || Promise.resolve(this.globalData.userInfo || null)
|
|
},
|
|
|
|
async loginWithCode(code) {
|
|
try {
|
|
const data = await request({
|
|
url: BASE_URL + API.LOGIN,
|
|
method: 'GET',
|
|
data: { code }
|
|
})
|
|
const userInfo = {
|
|
openid: data.openid,
|
|
sessionKey: data.session_key,
|
|
unionid: data.unionid || ''
|
|
}
|
|
this.globalData.userInfo = userInfo
|
|
this.globalData.isLoggedIn = true
|
|
this.globalData.loginFailed = false
|
|
wx.setStorageSync('userInfo', userInfo)
|
|
if (this._loginResolve) this._loginResolve(userInfo)
|
|
} catch (err) {
|
|
console.error('后端登录失败', err)
|
|
// 如果有缓存登录态,登录失败不立即清除,让页面继续使用缓存
|
|
if (!this.globalData.isLoggedIn) {
|
|
this.handleLoginFail()
|
|
} else {
|
|
this.globalData.loginFailed = true
|
|
if (this._loginResolve) this._loginResolve(this.globalData.userInfo)
|
|
}
|
|
}
|
|
},
|
|
|
|
handleLoginFail() {
|
|
this.globalData.isLoggedIn = false
|
|
this.globalData.loginFailed = true
|
|
if (this._loginResolve) this._loginResolve(null)
|
|
},
|
|
|
|
globalData: {
|
|
userInfo: null,
|
|
isLoggedIn: false,
|
|
loginFailed: false
|
|
}
|
|
})
|