Files
JayuCloud/JC-Salon-WeChat/app.js
T

117 lines
3.2 KiB
JavaScript

const auth = require('./utils/auth')
const authApi = require('./api/auth')
const { BRAND_CONFIG } = require('./utils/config')
const profileCache = require('./utils/profile-cache')
App({
globalData: {
appName: BRAND_CONFIG.appName,
shopName: BRAND_CONFIG.defaultShopName,
userInfo: null,
planningNeedRefresh: false,
wechatLoginState: null
},
onLaunch() {
this.bootstrapSession()
},
getWechatCode() {
return new Promise((resolve, reject) => {
wx.login({
success: result => result.code ? resolve(result.code) : reject(new Error('未获取到微信登录凭证')),
fail: reject
})
})
},
async bootstrapWechatLogin() {
if (this._wechatBootstrapPromise) return this._wechatBootstrapPromise
this._wechatBootstrapPromise = this.runWechatBootstrap()
try {
return await this._wechatBootstrapPromise
} finally {
this._wechatBootstrapPromise = null
}
},
async runWechatBootstrap() {
try {
const preference = auth.getLoginPreference()
if (!preference || !preference.rememberMe) {
const status = await authApi.wechatStatus(await this.getWechatCode())
this.publishWechatLoginState(status)
auth.clearSession()
this.globalData.userInfo = null
this.goLogin()
return
}
const result = await authApi.wechatQuickLogin({
wxCode: await this.getWechatCode(),
preferredShopId: preference.preferredShopId,
agreementAccepted: true,
agreementVersions: preference.agreementVersions || {},
clientType: 'WECHAT_MINI'
})
this.publishWechatLoginState(result)
if (result.status === 'SUCCESS' && result.accessToken) {
this.setSession(result)
wx.reLaunch({ url: '/pages/planning/index' })
return
}
auth.clearSession()
this.globalData.userInfo = null
this.goLogin()
} catch (error) {
auth.clearSession()
this.globalData.userInfo = null
this.publishWechatLoginState({
status: 'ERROR',
message: error.message || '自动登录失败,请点击重试'
})
this.goLogin()
}
},
goLogin() {
const pages = getCurrentPages()
const current = pages.length ? pages[pages.length - 1].route : ''
if (current !== 'pages/login/index') wx.reLaunch({ url: '/pages/login/index' })
},
publishWechatLoginState(state) {
this.globalData.wechatLoginState = state
const pages = getCurrentPages()
const current = pages.length ? pages[pages.length - 1] : null
if (current && current.route === 'pages/login/index' && typeof current.setData === 'function') {
current.setData({ loginState: state })
}
},
bootstrapSession() {
const session = auth.getSession()
this.globalData.userInfo = session.userInfo || null
if (session.shopName) {
this.globalData.shopName = session.shopName
}
},
setSession(session) {
auth.setSession(session)
this.bootstrapSession()
},
clearSession() {
auth.clearSession()
profileCache.invalidate()
this.globalData.userInfo = null
},
logoutDevice() {
auth.clearDeviceLoginState()
profileCache.invalidate()
this.globalData.userInfo = null
this.globalData.wechatLoginState = null
}
})