feat: 微信小程序登录改造(手机号授权 + API前缀改为/mp-api + 隐私协议检查)

This commit is contained in:
jacobxu666
2026-06-14 21:54:08 +08:00
parent 6ee484d8a3
commit 3af5f2850d
6 changed files with 60 additions and 29 deletions
+36 -7
View File
@@ -8,7 +8,10 @@
<view class="login-area">
<!-- #ifdef MP-WEIXIN -->
<button class="btn-wx-login" @click="handleWxLogin" :disabled="loading">
<button class="btn-wx-login"
open-type="getPhoneNumber"
@getphonenumber="handleGetPhoneNumber"
:disabled="loading">
{{ loading ? '登录中...' : '微信一键登录' }}
</button>
<!-- #endif -->
@@ -59,17 +62,43 @@ const form = reactive({
password: ''
})
/** 微信一键登录 */
async function handleWxLogin() {
/** 微信手机号授权回调 → 登录 */
async function handleGetPhoneNumber(e: any) {
// 用户拒绝授权手机号
if (e.detail.errMsg !== 'getPhoneNumber:ok') {
showToast('需要手机号授权才能登录')
return
}
loading.value = true
try {
await userStore.wxLogin()
const phoneCode = e.detail.code
if (!phoneCode) {
showToast('手机号获取失败,请重试')
return
}
// 获取微信登录 code(与 phoneCode 是完全不同的凭证)
const loginRes: any = await new Promise((resolve, reject) => {
uni.login({ provider: 'weixin', success: resolve, fail: reject })
})
// 防御性检查:loginCode 不能为空
if (!loginRes || !loginRes.code) {
showToast('微信登录失败,请重试')
return
}
await userStore.wxLogin({
loginCode: loginRes.code, // wx.login() 返回的 code
phoneCode: phoneCode // getPhoneNumber 返回的 code
})
showToast('登录成功', 'success')
setTimeout(() => {
uni.switchTab({ url: '/packages/user/pages/index/index' })
uni.switchTab({ url: '/pages/index/index' })
}, 1000)
} catch (err: any) {
console.error('微信登录失败:', err)
showToast(err.message || '登录失败')
} finally {
loading.value = false
@@ -87,7 +116,7 @@ async function handleFallbackLogin() {
await userStore.login({ username: form.username, password: form.password })
showToast('登录成功', 'success')
setTimeout(() => {
uni.switchTab({ url: '/packages/user/pages/index/index' })
uni.switchTab({ url: '/pages/index/index' })
}, 1000)
} catch (err: any) {
console.error('登录失败:', err)