404730238b
提交
91 lines
2.3 KiB
JavaScript
91 lines
2.3 KiB
JavaScript
// app.js
|
|
App({
|
|
onLaunch() {
|
|
if (!wx.cloud) {
|
|
console.error('请使用 2.2.3 或以上的基础库以使用云能力')
|
|
} else {
|
|
wx.cloud.init({
|
|
traceUser: true
|
|
})
|
|
}
|
|
|
|
|
|
|
|
// 自动静默登录:wx.login 获取 code,再请求后端接口换取 openid
|
|
this.silentLogin()
|
|
},
|
|
|
|
silentLogin() {
|
|
wx.login({
|
|
success: (loginRes) => {
|
|
if (loginRes.code) {
|
|
this.loginWithCode(loginRes.code)
|
|
} else {
|
|
console.error('wx.login 失败', loginRes.errMsg)
|
|
this.globalData.isLoggedIn = false
|
|
this.globalData.loginFailed = true
|
|
if (this.loginReadyCallback) {
|
|
this.loginReadyCallback(null)
|
|
}
|
|
}
|
|
},
|
|
fail: (err) => {
|
|
console.error('wx.login 调用失败', err)
|
|
this.globalData.isLoggedIn = false
|
|
this.globalData.loginFailed = true
|
|
if (this.loginReadyCallback) {
|
|
this.loginReadyCallback(null)
|
|
}
|
|
}
|
|
})
|
|
},
|
|
|
|
loginWithCode(code) {
|
|
wx.request({
|
|
url: 'https://xcx.yun.588580.xyz/api/wx-mini/login',
|
|
method: 'GET',
|
|
data: { code },
|
|
success: (res) => {
|
|
const result = res.data
|
|
if (result && result.code === 0 && result.data) {
|
|
const openid = result.data.openid
|
|
const userInfo = {
|
|
openid,
|
|
sessionKey: result.data.session_key,
|
|
unionid: result.data.unionid || ''
|
|
}
|
|
|
|
this.globalData.userInfo = userInfo
|
|
this.globalData.isLoggedIn = true
|
|
wx.setStorageSync('userInfo', userInfo)
|
|
|
|
if (this.loginReadyCallback) {
|
|
this.loginReadyCallback(userInfo)
|
|
}
|
|
} else {
|
|
console.error('后端登录失败', result)
|
|
this.globalData.isLoggedIn = false
|
|
this.globalData.loginFailed = true
|
|
if (this.loginReadyCallback) {
|
|
this.loginReadyCallback(null)
|
|
}
|
|
}
|
|
},
|
|
fail: (err) => {
|
|
console.error('请求后端登录接口失败', err)
|
|
this.globalData.isLoggedIn = false
|
|
this.globalData.loginFailed = true
|
|
if (this.loginReadyCallback) {
|
|
this.loginReadyCallback(null)
|
|
}
|
|
}
|
|
})
|
|
},
|
|
|
|
globalData: {
|
|
userInfo: null,
|
|
isLoggedIn: false,
|
|
loginFailed: false
|
|
}
|
|
})
|