功能:新增微信小程序一键登录

This commit is contained in:
xiaowang
2026-04-02 13:20:28 +08:00
parent 8ac7deffca
commit 4f5ef4fedd
32 changed files with 1899 additions and 65 deletions
+371 -25
View File
@@ -1,6 +1,7 @@
const authApi = require('../../api/auth')
const shopApi = require('../../api/shop')
const userApi = require('../../api/user')
const authStore = require('../../utils/auth')
const navigation = require('../../utils/navigation')
const { runWithLoading } = require('../../utils/loading')
@@ -11,6 +12,7 @@ Page({
redirect: '',
activeTab: 'login',
loginType: 'password',
authHelperText: '',
loading: false,
shops: [],
registerShopIndex: -1,
@@ -29,6 +31,17 @@ Page({
countdown: 0,
forgotCountdown: 0,
showResetPanel: false,
wechatMiniSupported: false,
wechatMiniDisabledReason: '',
wechatMiniLoading: false,
showMiniShopSelector: false,
miniShopMessage: '',
miniShopTicket: '',
miniShops: [],
miniShopIndex: -1,
miniShopDisplayName: '',
miniShopNewUser: false,
miniShopSubmitting: false,
form: {
account: '',
password: '',
@@ -48,9 +61,83 @@ Page({
onLoad(options) {
this.setData({
redirect: options && options.redirect ? options.redirect : ''
redirect: options && options.redirect ? options.redirect : '',
authHelperText: this.buildAuthHelperText('login', 'password')
})
this.detectWechatMiniCapability()
this.loadShopOptions()
this.consumePendingWechatMiniLogin()
this.waitForPendingWechatMiniAutoLogin()
},
onShow() {
this.consumePendingWechatMiniLogin()
},
noop() {},
detectWechatMiniCapability() {
let supported = false
let disabledReason = ''
try {
supported = wx.canIUse('button.open-type.getPhoneNumber')
const systemInfo = wx.getSystemInfoSync()
if (systemInfo && systemInfo.platform === 'devtools') {
supported = false
disabledReason = '开发者工具暂不支持微信手机号一键登录,请使用真机调试或传统登录。'
}
} catch (error) {
supported = false
}
if (!supported && !disabledReason) {
disabledReason = '当前微信环境暂不支持手机号一键登录,请使用账号密码或验证码登录。'
}
this.setData({
wechatMiniSupported: supported,
wechatMiniDisabledReason: disabledReason
})
},
waitForPendingWechatMiniAutoLogin() {
const app = getApp()
if (
!app
|| typeof app.isWechatMiniAutoLoginPending !== 'function'
|| typeof app.waitForWechatMiniAutoLogin !== 'function'
|| !app.isWechatMiniAutoLoginPending()
) {
return
}
Promise.resolve(app.waitForWechatMiniAutoLogin())
.catch(() => false)
.then(async () => {
if (authStore.isLoggedIn()) {
try {
await navigation.redirectAfterLogin(this.data.redirect)
} catch (redirectError) {
console.error('自动登录后跳转失败,已回退到首页', redirectError)
await navigation.switchTab('/pages/home/index')
}
return
}
this.consumePendingWechatMiniLogin()
})
},
consumePendingWechatMiniLogin() {
const app = getApp()
if (!app || typeof app.consumePendingWechatMiniLogin !== 'function') {
return
}
const pending = app.consumePendingWechatMiniLogin()
if (pending && pending.status === 'SELECT_SHOP') {
this.openMiniShopSelector(pending)
}
},
async loadShopOptions() {
@@ -71,6 +158,7 @@ Page({
const tab = event.currentTarget.dataset.tab
this.setData({
activeTab: tab,
authHelperText: this.buildAuthHelperText(tab, this.data.loginType),
showResetPanel: false,
loginAccountStatusText: '',
loginAccountStatusType: '',
@@ -85,6 +173,7 @@ Page({
const type = event.currentTarget.dataset.type
this.setData({
loginType: type,
authHelperText: this.buildAuthHelperText(this.data.activeTab, type),
loginShops: [],
loginShopIndex: -1,
loginShopDisplayName: '',
@@ -104,9 +193,44 @@ Page({
handleInputChange(event) {
const field = event.currentTarget.dataset.field
this.setData({
[`form.${field}`]: event.detail.value
})
const value = event.detail.value
const patch = {
[`form.${field}`]: value
}
if (field === 'account') {
if (this.data.activeTab === 'login') {
patch.loginAccountStatusText = ''
patch.loginAccountStatusType = ''
if (!String(value || '').trim()) {
patch.loginShops = []
patch.loginShopIndex = -1
patch.loginShopDisplayName = ''
patch.allowLoginShopless = false
patch.loginShopMessage = ''
patch['form.shopId'] = ''
}
} else {
patch.registerAccountStatusText = ''
patch.registerAccountStatusType = ''
}
}
if (field === 'phone') {
if (this.data.activeTab === 'register') {
patch.registerPhoneStatusText = ''
patch.registerPhoneStatusType = ''
} else if (this.data.loginType === 'phone' && !String(value || '').trim()) {
patch.loginShops = []
patch.loginShopIndex = -1
patch.loginShopDisplayName = ''
patch.allowLoginShopless = false
patch.loginShopMessage = ''
patch['form.shopId'] = ''
}
}
this.setData(patch)
},
handleResetInputChange(event) {
@@ -136,6 +260,34 @@ Page({
})
},
handleMiniShopChange(event) {
const index = Number(event.detail.value)
const shop = this.data.miniShops[index]
this.setData({
miniShopIndex: index,
miniShopDisplayName: shop ? shop.shopName || '' : ''
})
},
handleCloseMiniShopSelector() {
if (this.data.miniShopSubmitting) {
return
}
this.setData({
showMiniShopSelector: false
})
},
handleResumeMiniShopSelector() {
if (!this.data.miniShopTicket || !this.data.miniShops.length) {
return
}
this.setData({
activeTab: 'login',
showMiniShopSelector: true
})
},
async handleAccountBlur() {
const account = this.data.form.account.trim()
if (!account) {
@@ -224,7 +376,7 @@ Page({
} catch (error) {
this.applyLoginShopSelection({
allowShoplessLogin: true,
message: '当前环境暂未开启门店预选,可直接登录',
message: '当前暂无法预加载可登录门店,可直接尝试登录。',
shops: []
})
}
@@ -237,7 +389,7 @@ Page({
} catch (error) {
this.applyLoginShopSelection({
allowShoplessLogin: true,
message: '当前环境暂未开启门店预选,可直接登录',
message: '当前暂无法预加载可登录门店,可直接尝试登录。',
shops: []
})
}
@@ -320,9 +472,7 @@ Page({
}
try {
await runWithLoading(() => userApi.sendVerificationCode({
phone
}))
await runWithLoading(() => userApi.sendVerificationCode({ phone }))
wx.showToast({
title: '验证码已发送',
icon: 'none'
@@ -351,9 +501,7 @@ Page({
}
try {
await runWithLoading(() => authApi.sendVerificationCode({
phone
}))
await runWithLoading(() => authApi.sendVerificationCode({ phone }))
wx.showToast({
title: '验证码已发送',
icon: 'none'
@@ -448,19 +596,7 @@ Page({
})
})
getApp().setUserSession(payload)
wx.showToast({
title: '登录成功',
icon: 'none'
})
try {
await navigation.redirectAfterLogin(this.data.redirect)
} catch (redirectError) {
console.error('登录后跳转失败,已回退到首页:', redirectError)
await navigation.switchTab('/pages/home/index')
}
await this.finishLogin(payload, '登录成功')
return
}
@@ -486,6 +622,7 @@ Page({
this.setData({
activeTab: 'login',
loginType: 'password',
authHelperText: this.buildAuthHelperText('login', 'password'),
'form.password': '',
'form.confirmPassword': '',
'form.verificationCode': ''
@@ -558,5 +695,214 @@ Page({
loading: false
})
}
},
handleWechatMiniUnavailableTap() {
wx.showToast({
title: this.data.wechatMiniDisabledReason || '当前环境暂不支持一键登录',
icon: 'none'
})
},
async handleWechatMiniPhoneLogin(event) {
if (!this.data.wechatMiniSupported || this.data.wechatMiniLoading) {
this.handleWechatMiniUnavailableTap()
return
}
const detail = event.detail || {}
if (!detail.code) {
wx.showToast({
title: this.resolveWechatAuthorizeError(detail),
icon: 'none'
})
return
}
this.setData({
wechatMiniLoading: true
})
try {
const wxCode = await this.requestWechatMiniCode()
const result = await runWithLoading(() => authApi.wechatMiniPhoneLogin({
wxCode,
phoneCode: detail.code,
preferredShopId: authStore.getPreferredMiniLoginShopId() || undefined
}))
await this.handleWechatMiniResult(result)
} catch (error) {
wx.showToast({
title: error.message || '微信手机号一键登录失败',
icon: 'none'
})
} finally {
this.setData({
wechatMiniLoading: false
})
}
},
async handleConfirmMiniShopLogin() {
const shop = this.data.miniShops[this.data.miniShopIndex]
if (!this.data.miniShopTicket) {
wx.showToast({
title: '登录票据已失效,请重新发起微信登录',
icon: 'none'
})
return
}
if (!shop || !shop.id) {
wx.showToast({
title: '请选择门店',
icon: 'none'
})
return
}
this.setData({
miniShopSubmitting: true
})
try {
const result = await runWithLoading(() => authApi.confirmWechatMiniLogin({
ticket: this.data.miniShopTicket,
shopId: shop.id
}))
if (!result || result.status !== 'SUCCESS') {
throw new Error((result && result.message) || '确认登录失败')
}
this.clearMiniShopSelector()
await this.finishLogin(result, result.newUser ? '注册并登录成功' : '登录成功')
} catch (error) {
wx.showToast({
title: error.message || '确认登录失败',
icon: 'none'
})
} finally {
this.setData({
miniShopSubmitting: false
})
}
},
resolveWechatAuthorizeError(detail) {
const errMsg = String((detail && detail.errMsg) || '')
if (errMsg.includes('user deny') || errMsg.includes('user cancel')) {
return '你已取消手机号授权,可继续使用账号密码或验证码登录。'
}
if (errMsg.includes('no permission')) {
return '当前小程序未开通手机号授权能力,请联系管理员检查微信配置。'
}
return '未获取到微信手机号授权,请稍后重试。'
},
requestWechatMiniCode() {
const app = getApp()
if (app && typeof app.requestWechatMiniCode === 'function') {
return app.requestWechatMiniCode()
}
return new Promise((resolve, reject) => {
wx.login({
success: res => {
if (res && res.code) {
resolve(res.code)
return
}
reject(new Error('获取微信登录凭证失败'))
},
fail: () => reject(new Error('获取微信登录凭证失败'))
})
})
},
async handleWechatMiniResult(result) {
if (!result) {
throw new Error('微信登录未返回结果')
}
if (result.status === 'SUCCESS') {
await this.finishLogin(result, result.newUser ? '注册并登录成功' : '登录成功')
return
}
if (result.status === 'SELECT_SHOP') {
this.openMiniShopSelector(result)
return
}
wx.showToast({
title: result.message || '请先使用传统方式登录',
icon: 'none'
})
},
openMiniShopSelector(result) {
const shops = Array.isArray(result && result.shops) ? result.shops : []
if (!shops.length) {
wx.showToast({
title: result && result.message ? result.message : '暂无可选门店,请稍后重试',
icon: 'none'
})
return
}
const defaultIndex = shops.length ? 0 : -1
const defaultShop = defaultIndex >= 0 ? shops[defaultIndex] : null
this.setData({
activeTab: 'login',
authHelperText: this.buildAuthHelperText('login', this.data.loginType),
showMiniShopSelector: true,
miniShopMessage: (result && result.message) || '',
miniShopTicket: (result && result.ticket) || '',
miniShops: shops,
miniShopIndex: defaultIndex,
miniShopDisplayName: defaultShop ? defaultShop.shopName || '' : '',
miniShopNewUser: Boolean(result && result.newUser)
})
},
clearMiniShopSelector() {
this.setData({
showMiniShopSelector: false,
miniShopMessage: '',
miniShopTicket: '',
miniShops: [],
miniShopIndex: -1,
miniShopDisplayName: '',
miniShopNewUser: false,
miniShopSubmitting: false
})
},
async finishLogin(payload, successMessage) {
getApp().setUserSession(payload)
this.clearMiniShopSelector()
this.setData({
loading: false,
wechatMiniLoading: false
})
wx.showToast({
title: successMessage || '登录成功',
icon: 'none'
})
try {
await navigation.redirectAfterLogin(this.data.redirect)
} catch (redirectError) {
console.error('登录后跳转失败,已回退到首页', redirectError)
await navigation.switchTab('/pages/home/index')
}
},
buildAuthHelperText(activeTab, loginType) {
if (activeTab === 'register') {
return '注册前会实时检查账号与手机号是否可用,并要求先绑定一家具备可用状态的门店。'
}
if (loginType === 'phone') {
return '使用手机号验证码登录时,首次登录且账号不存在会要求先选择门店后自动注册。'
}
return '输入账号和密码即可登录;若账号绑定了多家门店,登录前需要先选择本次门店。'
}
})