Files
miniwx/app.js
T
ws 055549f198 refactor: 重构微信小程序从云开发迁移至后端API
将云数据库操作改为调用后端API接口
提取登录失败处理逻辑到单独方法
添加环境配置和API请求工具类
移除云开发相关配置
2026-04-21 17:30:53 +08:00

72 lines
1.7 KiB
JavaScript

// app.js
const { BASE_URL, API } = require('./utils/config')
App({
onLaunch() {
// 自动静默登录: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.handleLoginFail()
}
},
fail: (err) => {
console.error('wx.login 调用失败', err)
this.handleLoginFail()
}
})
},
loginWithCode(code) {
wx.request({
url: BASE_URL + API.LOGIN,
method: 'GET',
data: { code },
success: (res) => {
const result = res.data
if (result && result.code === 0 && result.data) {
const userInfo = {
openid: result.data.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.handleLoginFail()
}
},
fail: (err) => {
console.error('请求后端登录接口失败', err)
this.handleLoginFail()
}
})
},
handleLoginFail() {
this.globalData.isLoggedIn = false
this.globalData.loginFailed = true
if (this.loginReadyCallback) {
this.loginReadyCallback(null)
}
},
globalData: {
userInfo: null,
isLoggedIn: false,
loginFailed: false
}
})