diff --git a/WeChatProgram/api/auth.js b/WeChatProgram/api/auth.js
index 1f798d24..6426784b 100644
--- a/WeChatProgram/api/auth.js
+++ b/WeChatProgram/api/auth.js
@@ -25,6 +25,30 @@ module.exports = {
})
},
+ wechatMiniAutoLogin(data) {
+ return request({
+ url: '/user/wechat-mini/auto-login',
+ method: 'POST',
+ data
+ })
+ },
+
+ wechatMiniPhoneLogin(data) {
+ return request({
+ url: '/user/wechat-mini/phone-login',
+ method: 'POST',
+ data
+ })
+ },
+
+ confirmWechatMiniLogin(data) {
+ return request({
+ url: '/user/wechat-mini/confirm-login',
+ method: 'POST',
+ data
+ })
+ },
+
register(data) {
return request({
url: '/user/register',
diff --git a/WeChatProgram/app.js b/WeChatProgram/app.js
index deed6222..f9213977 100644
--- a/WeChatProgram/app.js
+++ b/WeChatProgram/app.js
@@ -1,16 +1,22 @@
-const auth = require('./utils/auth')
+const authApi = require('./api/auth')
const cartApi = require('./api/cart')
+const auth = require('./utils/auth')
App({
globalData: {
userInfo: null,
isLoggedIn: false,
cartCount: 0,
- pendingProductFilter: null
+ pendingProductFilter: null,
+ pendingWechatMiniLogin: null,
+ wechatMiniAutoLoginState: 'idle'
},
onLaunch() {
this.bootstrapSession()
+ if (!auth.isLoggedIn()) {
+ this.tryWechatMiniAutoLogin()
+ }
},
bootstrapSession() {
@@ -19,6 +25,10 @@ App({
this.globalData.userInfo = userInfo
this.globalData.isLoggedIn = isLoggedIn
+ if (userInfo && userInfo.shopId) {
+ auth.setPreferredMiniLoginShopId(userInfo.shopId)
+ }
+
if (isLoggedIn) {
this.updateCartBadge()
return
@@ -27,10 +37,117 @@ App({
this.clearCartBadge()
},
+ async tryWechatMiniAutoLogin() {
+ if (auth.isLoggedIn()) {
+ return true
+ }
+
+ if (this._wechatMiniAutoLoginPromise) {
+ return this._wechatMiniAutoLoginPromise
+ }
+
+ if (typeof wx === 'undefined' || typeof wx.login !== 'function') {
+ return false
+ }
+
+ this.globalData.wechatMiniAutoLoginState = 'pending'
+ this._wechatMiniAutoLoginPromise = this.requestWechatMiniCode()
+ .then(code => authApi.wechatMiniAutoLogin({
+ wxCode: code,
+ preferredShopId: auth.getPreferredMiniLoginShopId() || undefined
+ }))
+ .then(result => this.handleWechatMiniLoginResult(result, { silent: true }))
+ .catch(() => false)
+ .finally(() => {
+ this._wechatMiniAutoLoginPromise = null
+ if (this.globalData.wechatMiniAutoLoginState === 'pending') {
+ this.globalData.wechatMiniAutoLoginState = 'idle'
+ }
+ })
+
+ return this._wechatMiniAutoLoginPromise
+ },
+
+ handleWechatMiniLoginResult(result, options) {
+ const config = options || {}
+ const status = result && result.status ? result.status : ''
+
+ if (status === 'SUCCESS') {
+ this.setUserSession(result)
+ this.clearPendingWechatMiniLogin()
+ this.globalData.wechatMiniAutoLoginState = 'idle'
+ return true
+ }
+
+ if (status === 'SELECT_SHOP') {
+ this.setPendingWechatMiniLogin(result)
+ this.globalData.wechatMiniAutoLoginState = 'idle'
+ if (!config.silent && result.message) {
+ wx.showToast({
+ title: result.message,
+ icon: 'none'
+ })
+ }
+ return false
+ }
+
+ this.clearPendingWechatMiniLogin()
+ this.globalData.wechatMiniAutoLoginState = 'idle'
+ if (!config.silent && result && result.message) {
+ wx.showToast({
+ title: result.message,
+ icon: 'none'
+ })
+ }
+ return false
+ },
+
+ requestWechatMiniCode() {
+ return new Promise((resolve, reject) => {
+ wx.login({
+ success: res => {
+ if (res && res.code) {
+ resolve(res.code)
+ return
+ }
+ reject(new Error('获取微信登录凭证失败'))
+ },
+ fail: reject
+ })
+ })
+ },
+
+ isWechatMiniAutoLoginPending() {
+ return this.globalData.wechatMiniAutoLoginState === 'pending'
+ },
+
+ waitForWechatMiniAutoLogin() {
+ return this._wechatMiniAutoLoginPromise || Promise.resolve(auth.isLoggedIn())
+ },
+
+ setPendingWechatMiniLogin(payload) {
+ this.globalData.pendingWechatMiniLogin = payload || null
+ },
+
+ consumePendingWechatMiniLogin() {
+ const pending = this.globalData.pendingWechatMiniLogin
+ this.globalData.pendingWechatMiniLogin = null
+ return pending
+ },
+
+ clearPendingWechatMiniLogin() {
+ this.globalData.pendingWechatMiniLogin = null
+ },
+
setUserSession(payload) {
auth.setSession(payload)
this.globalData.userInfo = auth.getStoredUserInfo()
this.globalData.isLoggedIn = auth.isLoggedIn()
+
+ if (this.globalData.userInfo && this.globalData.userInfo.shopId) {
+ auth.setPreferredMiniLoginShopId(this.globalData.userInfo.shopId)
+ }
+
this.updateCartBadge()
},
@@ -38,6 +155,10 @@ App({
auth.updateStoredUserInfo(userInfo)
this.globalData.userInfo = userInfo
this.globalData.isLoggedIn = auth.isLoggedIn()
+
+ if (userInfo && userInfo.shopId) {
+ auth.setPreferredMiniLoginShopId(userInfo.shopId)
+ }
},
clearUserSession() {
diff --git a/WeChatProgram/pages/auth/index.js b/WeChatProgram/pages/auth/index.js
index 62a163d6..1a2764ba 100644
--- a/WeChatProgram/pages/auth/index.js
+++ b/WeChatProgram/pages/auth/index.js
@@ -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 '输入账号和密码即可登录;若账号绑定了多家门店,登录前需要先选择本次门店。'
}
})
diff --git a/WeChatProgram/pages/auth/index.wxml b/WeChatProgram/pages/auth/index.wxml
index 1c4c0653..cc059d0e 100644
--- a/WeChatProgram/pages/auth/index.wxml
+++ b/WeChatProgram/pages/auth/index.wxml
@@ -4,21 +4,21 @@
YUMI NAIL
- {{activeTab === 'login' ? '登录后继续预约与收藏' : '注册账号,开始你的美甲旅程'}}
- 支持账号密码或手机验证码,绑定门店后,下单和查看记录都会更顺手。
+ {{activeTab === 'login' ? '登录后继续预约、收藏与下单' : '注册账号,开启你的美甲旅程'}}
+ 支持微信手机号一键登录,也保留账号密码与短信验证码登录方式。完成门店绑定后,订单、购物车与收藏会跟着账号同步。
- 收藏同步
- 喜欢的作品随时可回看
+ 微信直达
+ 授权手机号后,可自动识别账号并快速登录
- 预约顺手
- 登录后直接补全预约信息
+ 门店同步
+ 支持选择本次登录门店,后续会优先记住
- 门店绑定
- 注册时即可关联常用门店
+ 记录留存
+ 订单、购物车与收藏统一跟账号同步
@@ -29,14 +29,51 @@
注册
-
- 账号密码登录
- 验证码登录
-
+
+
+ 微信手机号一键登录
+ 适合已绑定微信的老用户,也支持首次授权后自动注册并绑定门店。
-
- {{activeTab === 'login' ? (loginType === 'password' ? '输入账号和密码即可登录。' : '手机号登录时会发送短信验证码。') : '注册前会实时检查账号和手机号是否已被占用。'}}
-
+
+
+
+
+ {{wechatMiniSupported ? '若该微信已绑定且只有一家可用门店,将直接登录;首次授权时会先让你选择门店。' : wechatMiniDisabledReason}}
+
+
+
+ 微信身份已识别完成,还差一步门店确认即可登录。
+ 继续选择门店
+
+
+
+
+ 传统登录方式
+
+
+
+
+ 账号密码登录
+ 验证码登录
+
+
+
+ {{authHelperText}}
@@ -106,7 +143,7 @@
重置密码
- 使用手机验证码设置新的登录密码。
+ 使用手机号验证码设置新的登录密码。
手机号
@@ -129,4 +166,26 @@
确认重置密码
+
+
+
+ {{miniShopNewUser ? '首次微信登录' : '确认本次登录门店'}}
+ {{miniShopNewUser ? '先选一家门店,我们会自动注册并登录' : '该账号绑定了多家门店,请先选择本次登录门店'}}
+ {{miniShopMessage || '选择后将继续完成登录。'}}
+
+
+ 登录门店
+
+ {{miniShopDisplayName || '请选择门店'}}
+
+
+
+ 首次通过微信手机号登录时,会自动创建账号、绑定手机号,并将当前门店作为本次登录门店。
+
+
+ 稍后再选
+ {{miniShopSubmitting ? '确认中...' : '确认登录'}}
+
+
+
diff --git a/WeChatProgram/pages/auth/index.wxss b/WeChatProgram/pages/auth/index.wxss
index 228f0e1a..3135504e 100644
--- a/WeChatProgram/pages/auth/index.wxss
+++ b/WeChatProgram/pages/auth/index.wxss
@@ -93,6 +93,76 @@
color: #c6597d;
}
+.wechat-login-panel {
+ padding: 26rpx 24rpx;
+ border-radius: 30rpx;
+ background: linear-gradient(145deg, #fff9fb 0%, #fff1f5 100%);
+ border: 1rpx solid rgba(244, 214, 224, 0.92);
+}
+
+.wechat-login-title {
+ display: block;
+ font-size: 30rpx;
+ font-weight: 700;
+ color: #2d2430;
+}
+
+.wechat-login-desc {
+ display: block;
+ margin-top: 12rpx;
+ font-size: 24rpx;
+ line-height: 1.7;
+ color: #8d7a84;
+}
+
+.wechat-login-btn {
+ margin-top: 22rpx;
+}
+
+.wechat-login-btn-disabled {
+ color: #99858e;
+ border-color: #f0dde5;
+ background: #fffafb;
+}
+
+.wechat-login-hint {
+ display: block;
+ margin-top: 16rpx;
+ font-size: 22rpx;
+ line-height: 1.7;
+ color: #8d7a84;
+}
+
+.mini-login-resume {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 18rpx;
+ margin-top: 18rpx;
+}
+
+.mini-login-resume-text {
+ flex: 1;
+ min-width: 0;
+}
+
+.mini-login-resume-btn {
+ flex-shrink: 0;
+}
+
+.login-divider {
+ display: flex;
+ align-items: center;
+ gap: 18rpx;
+ margin: 26rpx 0 18rpx;
+}
+
+.login-divider-text {
+ flex-shrink: 0;
+ font-size: 22rpx;
+ color: #99858e;
+}
+
.auth-helper {
margin-bottom: 10rpx;
font-size: 23rpx;
@@ -152,3 +222,63 @@
.submit-btn {
margin-top: 28rpx;
}
+
+.mini-shop-mask {
+ position: fixed;
+ inset: 0;
+ z-index: 60;
+ display: flex;
+ align-items: flex-end;
+ padding: 24rpx;
+ background: rgba(45, 36, 48, 0.34);
+}
+
+.mini-shop-modal {
+ width: 100%;
+ padding: 32rpx 28rpx;
+ border-radius: 36rpx;
+ background: #ffffff;
+}
+
+.mini-shop-kicker {
+ display: block;
+ font-size: 22rpx;
+ font-weight: 700;
+ letter-spacing: 2rpx;
+ color: #c6597d;
+}
+
+.mini-shop-title {
+ display: block;
+ margin-top: 16rpx;
+ font-size: 34rpx;
+ line-height: 1.35;
+ font-weight: 700;
+ color: #2d2430;
+}
+
+.mini-shop-desc {
+ display: block;
+ margin-top: 14rpx;
+ font-size: 24rpx;
+ line-height: 1.75;
+ color: #8d7a84;
+}
+
+.mini-shop-field {
+ margin-top: 26rpx;
+}
+
+.mini-shop-note {
+ margin-top: 20rpx;
+}
+
+.mini-shop-actions {
+ display: flex;
+ gap: 16rpx;
+ margin-top: 28rpx;
+}
+
+.mini-shop-action {
+ flex: 1;
+}
diff --git a/WeChatProgram/utils/auth.js b/WeChatProgram/utils/auth.js
index e0beb476..469ca2d8 100644
--- a/WeChatProgram/utils/auth.js
+++ b/WeChatProgram/utils/auth.js
@@ -16,6 +16,10 @@ function getNeedSetPassword() {
return Boolean(getStorage(STORAGE_KEYS.NEED_SET_PASSWORD, false))
}
+function getPreferredMiniLoginShopId() {
+ return getStorage(STORAGE_KEYS.PREFERRED_MINI_LOGIN_SHOP_ID, '')
+}
+
function isLoggedIn() {
return Boolean(getAccessToken())
}
@@ -64,14 +68,25 @@ function clearSession() {
removeStorage(STORAGE_KEYS.NEED_SET_PASSWORD)
}
+function setPreferredMiniLoginShopId(shopId) {
+ if (shopId === undefined || shopId === null || shopId === '') {
+ removeStorage(STORAGE_KEYS.PREFERRED_MINI_LOGIN_SHOP_ID)
+ return
+ }
+
+ setStorage(STORAGE_KEYS.PREFERRED_MINI_LOGIN_SHOP_ID, String(shopId))
+}
+
module.exports = {
getAccessToken,
getRefreshToken,
getStoredUserInfo,
getNeedSetPassword,
+ getPreferredMiniLoginShopId,
isLoggedIn,
setSession,
updateStoredUserInfo,
setNeedSetPassword,
+ setPreferredMiniLoginShopId,
clearSession
}
diff --git a/WeChatProgram/utils/navigation.js b/WeChatProgram/utils/navigation.js
index 95892f39..36f6c8f5 100644
--- a/WeChatProgram/utils/navigation.js
+++ b/WeChatProgram/utils/navigation.js
@@ -1,6 +1,8 @@
const auth = require('./auth')
const { TAB_PAGES } = require('./config')
+let waitingForAutoLoginNavigation = false
+
function buildUrl(path, params) {
const query = Object.keys(params || {})
.filter(key => params[key] !== undefined && params[key] !== null && params[key] !== '')
@@ -131,27 +133,51 @@ function openAuth(redirect) {
})
}
+function showLoginToast(actionText) {
+ wx.showToast({
+ title: `${actionText || '继续操作'}前请先登录`,
+ icon: 'none'
+ })
+}
+
+function scheduleOpenAuth(actionText) {
+ showLoginToast(actionText)
+ setTimeout(() => {
+ openAuth()
+ }, 120)
+}
+
function ensureLogin(actionText) {
if (auth.isLoggedIn()) {
return true
}
- wx.showToast({
- title: `${actionText || '继续操作'}前请先登录`,
- icon: 'none'
- })
-
- setTimeout(() => {
- openAuth()
- }, 120)
-
- return false
-}
-
-function openProducts(filter) {
const app = getApp()
- app.globalData.pendingProductFilter = filter || {}
- return switchTab('/pages/products/index')
+ const hasAutoLoginHelpers = app
+ && typeof app.isWechatMiniAutoLoginPending === 'function'
+ && typeof app.waitForWechatMiniAutoLogin === 'function'
+
+ if (hasAutoLoginHelpers && app.isWechatMiniAutoLoginPending()) {
+ if (waitingForAutoLoginNavigation) {
+ return false
+ }
+
+ waitingForAutoLoginNavigation = true
+ Promise.resolve(app.waitForWechatMiniAutoLogin())
+ .catch(() => false)
+ .then(() => {
+ if (!auth.isLoggedIn()) {
+ scheduleOpenAuth(actionText)
+ }
+ })
+ .finally(() => {
+ waitingForAutoLoginNavigation = false
+ })
+ return false
+ }
+
+ scheduleOpenAuth(actionText)
+ return false
}
module.exports = {
@@ -164,5 +190,9 @@ module.exports = {
redirectAfterLogin,
openAuth,
ensureLogin,
- openProducts
+ openProducts(filter) {
+ const app = getApp()
+ app.globalData.pendingProductFilter = filter || {}
+ return switchTab('/pages/products/index')
+ }
}
diff --git a/WeChatProgram/utils/request.js b/WeChatProgram/utils/request.js
index 4f464856..d772097c 100644
--- a/WeChatProgram/utils/request.js
+++ b/WeChatProgram/utils/request.js
@@ -23,6 +23,7 @@ function isWhitelistedPath(url) {
'/user/refresh-token',
'/user/send-verification-code',
'/user/phone-login',
+ '/user/wechat-mini/',
'/user/reset-password-by-phone',
'/product/get/',
'/product/list/',
diff --git a/WeChatProgram/utils/storage.js b/WeChatProgram/utils/storage.js
index b963ea3a..599d8757 100644
--- a/WeChatProgram/utils/storage.js
+++ b/WeChatProgram/utils/storage.js
@@ -2,7 +2,8 @@ const STORAGE_KEYS = {
ACCESS_TOKEN: 'accessToken',
REFRESH_TOKEN: 'refreshToken',
USER_INFO: 'userInfo',
- NEED_SET_PASSWORD: 'needSetPassword'
+ NEED_SET_PASSWORD: 'needSetPassword',
+ PREFERRED_MINI_LOGIN_SHOP_ID: 'preferredMiniLoginShopId'
}
function getStorage(key, defaultValue) {
diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/config/HttpClientConfig.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/config/HttpClientConfig.java
new file mode 100644
index 00000000..afe915e8
--- /dev/null
+++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/config/HttpClientConfig.java
@@ -0,0 +1,17 @@
+package com.xiaowang.yuminailcore.config;
+
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.web.client.RestTemplate;
+
+/**
+ * HTTP 客户端配置。
+ */
+@Configuration
+public class HttpClientConfig {
+
+ @Bean
+ public RestTemplate restTemplate() {
+ return new RestTemplate();
+ }
+}
diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/config/WebMvcConfig.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/config/WebMvcConfig.java
index 72b11ddd..81bc9b85 100644
--- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/config/WebMvcConfig.java
+++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/config/WebMvcConfig.java
@@ -22,6 +22,7 @@ public class WebMvcConfig implements WebMvcConfigurer {
"/user/refresh-token",
"/user/send-verification-code",
"/user/phone-login",
+ "/user/wechat-mini/**",
"/user/reset-password-by-phone",
"/product/get/**",
"/product/list/**",
diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/config/WechatMiniProperties.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/config/WechatMiniProperties.java
new file mode 100644
index 00000000..ed63e59d
--- /dev/null
+++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/config/WechatMiniProperties.java
@@ -0,0 +1,20 @@
+package com.xiaowang.yuminailcore.config;
+
+import lombok.Data;
+import org.springframework.boot.context.properties.ConfigurationProperties;
+import org.springframework.context.annotation.Configuration;
+
+/**
+ * 微信小程序登录配置。
+ */
+@Data
+@Configuration
+@ConfigurationProperties(prefix = "yuminail.wechat.mini")
+public class WechatMiniProperties {
+
+ private String appId;
+ private String appSecret;
+ private String code2sessionUrl = "https://api.weixin.qq.com/sns/jscode2session";
+ private String phoneNumberUrl = "https://api.weixin.qq.com/wxa/business/getuserphonenumber";
+ private Integer accessTokenBufferSeconds = 60;
+}
diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/UserController.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/UserController.java
index 54f002c2..88b54396 100644
--- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/UserController.java
+++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/controller/UserController.java
@@ -11,9 +11,11 @@ import com.xiaowang.yuminailcore.vo.ChunkUploadSessionVO;
import com.xiaowang.yuminailcore.vo.LoginShopSelectionVO;
import com.xiaowang.yuminailcore.vo.LoginResponseVO;
import com.xiaowang.yuminailcore.vo.UserVO;
+import com.xiaowang.yuminailcore.vo.WechatMiniLoginResultVO;
import com.xiaowang.yuminailcore.service.MinioService;
import com.xiaowang.yuminailcore.service.UserService;
import com.xiaowang.yuminailcore.service.VerificationCodeService;
+import com.xiaowang.yuminailcore.service.WechatMiniAuthService;
import com.xiaowang.yuminailcore.support.id.TimeOrderedSnowflakeIdGenerator;
import com.xiaowang.yuminailcore.utils.AccountValidationUtils;
import lombok.Data;
@@ -46,6 +48,7 @@ public class UserController {
private final UserMapper userMapper;
private final AdminScopeHelper adminScopeHelper;
private final TimeOrderedSnowflakeIdGenerator snowflakeIdGenerator;
+ private final WechatMiniAuthService wechatMiniAuthService;
/**
* 创建用户
@@ -276,6 +279,21 @@ public class UserController {
return Result.success(loginResponseVO);
}
+ @PostMapping("/wechat-mini/auto-login")
+ public Result wechatMiniAutoLogin(@Valid @RequestBody WechatMiniAutoLoginRequestDTO requestDTO) {
+ return Result.success(wechatMiniAuthService.autoLogin(requestDTO));
+ }
+
+ @PostMapping("/wechat-mini/phone-login")
+ public Result wechatMiniPhoneLogin(@Valid @RequestBody WechatMiniPhoneLoginRequestDTO requestDTO) {
+ return Result.success(wechatMiniAuthService.phoneLogin(requestDTO));
+ }
+
+ @PostMapping("/wechat-mini/confirm-login")
+ public Result confirmWechatMiniLogin(@Valid @RequestBody WechatMiniConfirmLoginRequestDTO requestDTO) {
+ return Result.success(wechatMiniAuthService.confirmLogin(requestDTO));
+ }
+
@PostMapping("/switch-shop")
public Result switchShop(HttpServletRequest request, @RequestBody SwitchShopRequestDTO switchShopRequestDTO) {
Long userId = (Long) request.getAttribute("userId");
diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/WechatMiniAutoLoginRequestDTO.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/WechatMiniAutoLoginRequestDTO.java
new file mode 100644
index 00000000..afdd6869
--- /dev/null
+++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/WechatMiniAutoLoginRequestDTO.java
@@ -0,0 +1,17 @@
+package com.xiaowang.yuminailcore.dto;
+
+import lombok.Data;
+
+import javax.validation.constraints.NotBlank;
+
+/**
+ * 微信小程序自动登录请求。
+ */
+@Data
+public class WechatMiniAutoLoginRequestDTO {
+
+ @NotBlank(message = "微信登录凭证不能为空")
+ private String wxCode;
+
+ private Long preferredShopId;
+}
diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/WechatMiniConfirmLoginRequestDTO.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/WechatMiniConfirmLoginRequestDTO.java
new file mode 100644
index 00000000..52e389f9
--- /dev/null
+++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/WechatMiniConfirmLoginRequestDTO.java
@@ -0,0 +1,19 @@
+package com.xiaowang.yuminailcore.dto;
+
+import lombok.Data;
+
+import javax.validation.constraints.NotBlank;
+import javax.validation.constraints.NotNull;
+
+/**
+ * 微信小程序补选店铺后确认登录请求。
+ */
+@Data
+public class WechatMiniConfirmLoginRequestDTO {
+
+ @NotBlank(message = "登录票据不能为空")
+ private String ticket;
+
+ @NotNull(message = "店铺不能为空")
+ private Long shopId;
+}
diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/WechatMiniPhoneLoginRequestDTO.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/WechatMiniPhoneLoginRequestDTO.java
new file mode 100644
index 00000000..620a8cd0
--- /dev/null
+++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/WechatMiniPhoneLoginRequestDTO.java
@@ -0,0 +1,20 @@
+package com.xiaowang.yuminailcore.dto;
+
+import lombok.Data;
+
+import javax.validation.constraints.NotBlank;
+
+/**
+ * 微信小程序手机号一键登录请求。
+ */
+@Data
+public class WechatMiniPhoneLoginRequestDTO {
+
+ @NotBlank(message = "微信登录凭证不能为空")
+ private String wxCode;
+
+ @NotBlank(message = "手机号授权凭证不能为空")
+ private String phoneCode;
+
+ private Long preferredShopId;
+}
diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/entity/WechatMiniBindingDO.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/entity/WechatMiniBindingDO.java
new file mode 100644
index 00000000..d5e3c62f
--- /dev/null
+++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/entity/WechatMiniBindingDO.java
@@ -0,0 +1,35 @@
+package com.xiaowang.yuminailcore.entity;
+
+import com.baomidou.mybatisplus.annotation.IdType;
+import com.baomidou.mybatisplus.annotation.TableField;
+import com.baomidou.mybatisplus.annotation.TableId;
+import com.baomidou.mybatisplus.annotation.TableName;
+import lombok.Getter;
+import lombok.Setter;
+
+/**
+ * 微信小程序用户绑定关系。
+ */
+@Getter
+@Setter
+@TableName("t_wechat_mini_binding")
+public class WechatMiniBindingDO extends BaseEntity {
+
+ @TableId(type = IdType.ASSIGN_ID)
+ private Long id;
+
+ @TableField("user_id")
+ private Long userId;
+
+ @TableField("app_id")
+ private String appId;
+
+ @TableField("openid")
+ private String openId;
+
+ @TableField("unionid")
+ private String unionId;
+
+ @TableField("status")
+ private Integer status;
+}
diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/mapper/WechatMiniBindingMapper.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/mapper/WechatMiniBindingMapper.java
new file mode 100644
index 00000000..ac5548ef
--- /dev/null
+++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/mapper/WechatMiniBindingMapper.java
@@ -0,0 +1,10 @@
+package com.xiaowang.yuminailcore.mapper;
+
+import com.baomidou.mybatisplus.core.mapper.BaseMapper;
+import com.xiaowang.yuminailcore.entity.WechatMiniBindingDO;
+
+/**
+ * 微信小程序绑定关系 Mapper。
+ */
+public interface WechatMiniBindingMapper extends BaseMapper {
+}
diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/UserService.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/UserService.java
index 09d3ac4f..8a102be5 100644
--- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/UserService.java
+++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/UserService.java
@@ -39,6 +39,10 @@ public interface UserService extends IService {
LoginResponseVO phoneLogin(PhoneLoginRequestDTO phoneLoginRequestDTO);
+ LoginResponseVO loginByVerifiedPhone(String phone, Long shopId);
+
+ LoginResponseVO loginByUserId(Long userId, Long shopId);
+
LoginResponseVO adminLogin(LoginRequestDTO loginRequestDTO);
LoginShopSelectionVO getLoginShopSelectionByAccount(String account);
diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/WechatMiniAuthService.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/WechatMiniAuthService.java
new file mode 100644
index 00000000..ee36afbf
--- /dev/null
+++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/WechatMiniAuthService.java
@@ -0,0 +1,20 @@
+package com.xiaowang.yuminailcore.service;
+
+import com.xiaowang.yuminailcore.dto.WechatMiniAutoLoginRequestDTO;
+import com.xiaowang.yuminailcore.dto.WechatMiniConfirmLoginRequestDTO;
+import com.xiaowang.yuminailcore.dto.WechatMiniPhoneLoginRequestDTO;
+import com.xiaowang.yuminailcore.vo.WechatMiniLoginResultVO;
+
+/**
+ * 微信小程序登录编排服务。
+ */
+public interface WechatMiniAuthService {
+
+ WechatMiniLoginResultVO autoLogin(WechatMiniAutoLoginRequestDTO requestDTO);
+
+ WechatMiniLoginResultVO phoneLogin(WechatMiniPhoneLoginRequestDTO requestDTO);
+
+ WechatMiniLoginResultVO confirmLogin(WechatMiniConfirmLoginRequestDTO requestDTO);
+
+ void invalidateBindingsByUserId(Long userId);
+}
diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/WechatMiniClientService.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/WechatMiniClientService.java
new file mode 100644
index 00000000..95445a37
--- /dev/null
+++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/WechatMiniClientService.java
@@ -0,0 +1,16 @@
+package com.xiaowang.yuminailcore.service;
+
+/**
+ * 微信小程序开放接口客户端。
+ */
+public interface WechatMiniClientService {
+
+ SessionInfo code2Session(String wxCode);
+
+ String getPhoneNumber(String phoneCode);
+
+ String getConfiguredAppId();
+
+ record SessionInfo(String openId, String unionId, String sessionKey) {
+ }
+}
diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/UserServiceImpl.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/UserServiceImpl.java
index cd1bbb30..59294e56 100644
--- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/UserServiceImpl.java
+++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/UserServiceImpl.java
@@ -10,9 +10,11 @@ import com.xiaowang.yuminailcore.dto.NailArtistInfoDTO;
import com.xiaowang.yuminailcore.entity.UserDO;
import com.xiaowang.yuminailcore.entity.UserPermissionDO;
import com.xiaowang.yuminailcore.entity.PermissionDO;
+import com.xiaowang.yuminailcore.entity.WechatMiniBindingDO;
import com.xiaowang.yuminailcore.mapper.UserMapper;
import com.xiaowang.yuminailcore.mapper.UserPermissionMapper;
import com.xiaowang.yuminailcore.mapper.PermissionMapper;
+import com.xiaowang.yuminailcore.mapper.WechatMiniBindingMapper;
import com.xiaowang.yuminailcore.service.NailArtistInfoService;
import com.xiaowang.yuminailcore.service.ShopService;
import com.xiaowang.yuminailcore.service.UserService;
@@ -79,6 +81,7 @@ public class UserServiceImpl extends ServiceImpl implements
private final UserShopBindingSupport userShopBindingSupport;
private final StringRedisTemplate redisTemplate;
private final TimeOrderedSnowflakeIdGenerator snowflakeIdGenerator;
+ private final WechatMiniBindingMapper wechatMiniBindingMapper;
private static Map buildDefaultPermissionSeeds() {
Map seeds = new HashMap<>();
@@ -427,6 +430,13 @@ public class UserServiceImpl extends ServiceImpl implements
clearLoginFailureCount(userDO.getAccount());
userShopBindingSupport.deleteBindingsByUserId(id);
+ wechatMiniBindingMapper.update(
+ null,
+ new LambdaUpdateWrapper()
+ .eq(WechatMiniBindingDO::getUserId, id)
+ .set(WechatMiniBindingDO::getStatus, 0)
+ .set(WechatMiniBindingDO::getUpdateTime, LocalDateTime.now())
+ );
LocalDateTime now = LocalDateTime.now();
return userMapper.update(
null,
@@ -736,6 +746,38 @@ public class UserServiceImpl extends ServiceImpl implements
}
// 未设置密码的特殊标识
+ @Override
+ public LoginResponseVO loginByVerifiedPhone(String phone, Long shopId) {
+ UserDO userDO = userMapper.selectOne(
+ Wrappers.lambdaQuery(UserDO.class)
+ .eq(UserDO::getPhone, phone)
+ .eq(UserDO::getIsDelete, 0)
+ .last("limit 1")
+ );
+
+ if (userDO == null) {
+ if (shopId == null || shopId == 0) {
+ throw new RuntimeException("首次登录需要选择店铺");
+ }
+ userDO = registerByPhone(phone, shopId);
+ } else {
+ assertUserAvailable(userDO);
+ clearLoginFailureCount(userDO.getAccount());
+ }
+
+ Long resolvedShopId = resolveUserLoginShopId(userDO, shopId);
+ return buildLoginResponse(userDO, resolvedShopId, ENCODED_UNSET_PASSWORD.equals(userDO.getPassword()));
+ }
+
+ @Override
+ public LoginResponseVO loginByUserId(Long userId, Long shopId) {
+ UserDO userDO = userMapper.selectById(userId);
+ assertUserAvailable(userDO);
+ clearLoginFailureCount(userDO.getAccount());
+ Long resolvedShopId = resolveUserLoginShopId(userDO, shopId);
+ return buildLoginResponse(userDO, resolvedShopId, ENCODED_UNSET_PASSWORD.equals(userDO.getPassword()));
+ }
+
private static final String UNSET_PASSWORD_MARKER = "__UNSET_PASSWORD__";
private static final String ENCODED_UNSET_PASSWORD = "$2a$10$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW"; // 加密后的特殊标识
diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/WechatMiniAuthServiceImpl.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/WechatMiniAuthServiceImpl.java
new file mode 100644
index 00000000..03e11b23
--- /dev/null
+++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/WechatMiniAuthServiceImpl.java
@@ -0,0 +1,378 @@
+package com.xiaowang.yuminailcore.service.impl;
+
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.xiaowang.yuminailcore.dto.WechatMiniAutoLoginRequestDTO;
+import com.xiaowang.yuminailcore.dto.WechatMiniConfirmLoginRequestDTO;
+import com.xiaowang.yuminailcore.dto.WechatMiniPhoneLoginRequestDTO;
+import com.xiaowang.yuminailcore.entity.UserDO;
+import com.xiaowang.yuminailcore.entity.WechatMiniBindingDO;
+import com.xiaowang.yuminailcore.mapper.UserMapper;
+import com.xiaowang.yuminailcore.mapper.WechatMiniBindingMapper;
+import com.xiaowang.yuminailcore.service.UserService;
+import com.xiaowang.yuminailcore.service.WechatMiniAuthService;
+import com.xiaowang.yuminailcore.service.WechatMiniClientService;
+import com.xiaowang.yuminailcore.support.UserShopBindingSupport;
+import com.xiaowang.yuminailcore.support.id.TimeOrderedSnowflakeIdGenerator;
+import com.xiaowang.yuminailcore.vo.LoginResponseVO;
+import com.xiaowang.yuminailcore.vo.ShopSimpleVO;
+import com.xiaowang.yuminailcore.vo.WechatMiniLoginResultVO;
+import lombok.Data;
+import lombok.RequiredArgsConstructor;
+import org.springframework.data.redis.core.StringRedisTemplate;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+import org.springframework.util.StringUtils;
+
+import java.time.Duration;
+import java.time.LocalDateTime;
+import java.util.List;
+import java.util.Objects;
+
+/**
+ * 微信小程序登录编排服务实现。
+ */
+@Service
+@RequiredArgsConstructor
+public class WechatMiniAuthServiceImpl implements WechatMiniAuthService {
+
+ private static final String PHONE_REGEX = "^1[3-9]\\d{9}$";
+ private static final String TICKET_KEY_PREFIX = "user:wechat-mini:login-ticket:";
+ private static final Duration TICKET_TTL = Duration.ofMinutes(5);
+
+ private final WechatMiniClientService wechatMiniClientService;
+ private final WechatMiniBindingMapper wechatMiniBindingMapper;
+ private final UserMapper userMapper;
+ private final UserService userService;
+ private final UserShopBindingSupport userShopBindingSupport;
+ private final StringRedisTemplate redisTemplate;
+ private final ObjectMapper objectMapper;
+ private final TimeOrderedSnowflakeIdGenerator snowflakeIdGenerator;
+
+ @Override
+ public WechatMiniLoginResultVO autoLogin(WechatMiniAutoLoginRequestDTO requestDTO) {
+ WechatMiniClientService.SessionInfo sessionInfo = wechatMiniClientService.code2Session(requestDTO.getWxCode());
+ WechatMiniBindingDO bindingDO = findBindingByOpenId(sessionInfo.openId());
+ if (bindingDO == null) {
+ return WechatMiniLoginResultVO.needManualLogin("当前微信尚未绑定账号,请使用微信手机号一键登录。");
+ }
+
+ UserDO userDO = getAvailableBoundUser(bindingDO);
+ if (userDO == null) {
+ return WechatMiniLoginResultVO.needManualLogin("当前微信绑定已失效,请重新使用微信手机号一键登录。");
+ }
+
+ return loginOrSelectShop(userDO, normalizeShopId(requestDTO.getPreferredShopId()), sessionInfo, false);
+ }
+
+ @Override
+ public WechatMiniLoginResultVO phoneLogin(WechatMiniPhoneLoginRequestDTO requestDTO) {
+ WechatMiniClientService.SessionInfo sessionInfo = wechatMiniClientService.code2Session(requestDTO.getWxCode());
+ String phone = normalizePhone(wechatMiniClientService.getPhoneNumber(requestDTO.getPhoneCode()));
+ if (!StringUtils.hasText(phone) || !phone.matches(PHONE_REGEX)) {
+ throw new RuntimeException("获取到的微信手机号格式不正确");
+ }
+
+ WechatMiniBindingDO bindingDO = findBindingByOpenId(sessionInfo.openId());
+ if (bindingDO != null) {
+ UserDO boundUser = getAvailableBoundUser(bindingDO);
+ if (boundUser != null) {
+ UserDO phoneUser = findActiveUserByPhone(phone);
+ if (phoneUser != null && !Objects.equals(phoneUser.getId(), boundUser.getId())) {
+ throw new RuntimeException("当前微信已绑定其他账号,无法关联该手机号");
+ }
+ return loginOrSelectShop(boundUser, normalizeShopId(requestDTO.getPreferredShopId()), sessionInfo, false);
+ }
+ }
+
+ UserDO phoneUser = findActiveUserByPhone(phone);
+ if (phoneUser != null) {
+ assertUserAvailable(phoneUser);
+ return loginOrSelectShop(phoneUser, normalizeShopId(requestDTO.getPreferredShopId()), sessionInfo, false);
+ }
+
+ List shops = userShopBindingSupport.listAllActiveShopOptions();
+ if (shops.isEmpty()) {
+ return WechatMiniLoginResultVO.needManualLogin("当前暂无可登录门店,请稍后再试。");
+ }
+ return buildSelectShopResult(
+ "首次使用微信手机号一键登录,请先选择本次登录门店。",
+ shops,
+ new TicketPayload(null, phone, sessionInfo.openId(), sessionInfo.unionId(), true)
+ );
+ }
+
+ @Override
+ @Transactional(rollbackFor = Exception.class)
+ public WechatMiniLoginResultVO confirmLogin(WechatMiniConfirmLoginRequestDTO requestDTO) {
+ Long shopId = normalizeShopId(requestDTO.getShopId());
+ if (shopId == null) {
+ throw new RuntimeException("请选择登录门店");
+ }
+
+ TicketPayload ticketPayload = readTicketPayload(requestDTO.getTicket());
+ LoginResponseVO loginResponse;
+ if (ticketPayload.getUserId() != null) {
+ loginResponse = userService.loginByUserId(ticketPayload.getUserId(), shopId);
+ } else if (StringUtils.hasText(ticketPayload.getPhone())) {
+ loginResponse = userService.loginByVerifiedPhone(ticketPayload.getPhone(), shopId);
+ } else {
+ throw new RuntimeException("登录票据数据不完整,请重新发起微信一键登录");
+ }
+
+ ensureBinding(loginResponse.getUserInfo().getId(), ticketPayload.getOpenId(), ticketPayload.getUnionId());
+ deleteTicketPayload(requestDTO.getTicket());
+ return WechatMiniLoginResultVO.success(
+ Boolean.TRUE.equals(ticketPayload.getNewUser()) ? "注册并登录成功" : "登录成功",
+ loginResponse,
+ Boolean.TRUE.equals(ticketPayload.getNewUser())
+ );
+ }
+
+ @Override
+ public void invalidateBindingsByUserId(Long userId) {
+ if (userId == null) {
+ return;
+ }
+ wechatMiniBindingMapper.update(
+ null,
+ new LambdaUpdateWrapper()
+ .eq(WechatMiniBindingDO::getUserId, userId)
+ .set(WechatMiniBindingDO::getStatus, 0)
+ .set(WechatMiniBindingDO::getUpdateTime, LocalDateTime.now())
+ );
+ }
+
+ private WechatMiniLoginResultVO loginOrSelectShop(
+ UserDO userDO,
+ Long preferredShopId,
+ WechatMiniClientService.SessionInfo sessionInfo,
+ boolean newUser
+ ) {
+ List activeShops = userShopBindingSupport.listActiveShopOptionsByUserId(userDO.getId());
+ if (activeShops.isEmpty()) {
+ return WechatMiniLoginResultVO.needManualLogin("当前账号没有可登录的门店,请联系管理员处理。");
+ }
+
+ Long resolvedShopId = resolvePreferredOrOnlyShop(activeShops, preferredShopId);
+ if (resolvedShopId != null) {
+ LoginResponseVO loginResponse = userService.loginByUserId(userDO.getId(), resolvedShopId);
+ ensureBinding(userDO.getId(), sessionInfo.openId(), sessionInfo.unionId());
+ return WechatMiniLoginResultVO.success("登录成功", loginResponse, newUser);
+ }
+
+ return buildSelectShopResult(
+ "该账号绑定了多家门店,请选择本次登录门店。",
+ activeShops,
+ new TicketPayload(userDO.getId(), null, sessionInfo.openId(), sessionInfo.unionId(), newUser)
+ );
+ }
+
+ private UserDO getAvailableBoundUser(WechatMiniBindingDO bindingDO) {
+ UserDO userDO = userMapper.selectById(bindingDO.getUserId());
+ if (userDO == null || Integer.valueOf(1).equals(userDO.getIsDelete())) {
+ deactivateBinding(bindingDO.getId());
+ return null;
+ }
+ assertUserAvailable(userDO);
+ return userDO;
+ }
+
+ private void assertUserAvailable(UserDO userDO) {
+ if (userDO == null || Integer.valueOf(1).equals(userDO.getIsDelete())) {
+ throw new RuntimeException("账号不存在");
+ }
+ if (userDO.getStatus() != null && !Integer.valueOf(1).equals(userDO.getStatus())) {
+ throw new RuntimeException("账号已停用");
+ }
+ }
+
+ private UserDO findActiveUserByPhone(String phone) {
+ if (!StringUtils.hasText(phone)) {
+ return null;
+ }
+ return userMapper.selectOne(
+ new LambdaQueryWrapper()
+ .eq(UserDO::getPhone, phone)
+ .eq(UserDO::getIsDelete, 0)
+ .last("limit 1")
+ );
+ }
+
+ private WechatMiniBindingDO findBindingByOpenId(String openId) {
+ return wechatMiniBindingMapper.selectOne(
+ new LambdaQueryWrapper()
+ .eq(WechatMiniBindingDO::getAppId, wechatMiniClientService.getConfiguredAppId())
+ .eq(WechatMiniBindingDO::getOpenId, openId)
+ .eq(WechatMiniBindingDO::getStatus, 1)
+ .last("limit 1")
+ );
+ }
+
+ private WechatMiniBindingDO findAnyBindingByOpenId(String openId) {
+ return wechatMiniBindingMapper.selectOne(
+ new LambdaQueryWrapper()
+ .eq(WechatMiniBindingDO::getAppId, wechatMiniClientService.getConfiguredAppId())
+ .eq(WechatMiniBindingDO::getOpenId, openId)
+ .last("limit 1")
+ );
+ }
+
+ private WechatMiniBindingDO findAnyBindingByUserId(Long userId) {
+ return wechatMiniBindingMapper.selectOne(
+ new LambdaQueryWrapper()
+ .eq(WechatMiniBindingDO::getAppId, wechatMiniClientService.getConfiguredAppId())
+ .eq(WechatMiniBindingDO::getUserId, userId)
+ .last("limit 1")
+ );
+ }
+
+ @Transactional(rollbackFor = Exception.class)
+ protected void ensureBinding(Long userId, String openId, String unionId) {
+ if (userId == null || !StringUtils.hasText(openId)) {
+ throw new RuntimeException("微信绑定信息不完整");
+ }
+
+ WechatMiniBindingDO openIdBinding = findAnyBindingByOpenId(openId);
+ WechatMiniBindingDO userBinding = findAnyBindingByUserId(userId);
+
+ if (openIdBinding != null && userBinding != null && !Objects.equals(openIdBinding.getId(), userBinding.getId())) {
+ if (Integer.valueOf(1).equals(openIdBinding.getStatus()) && !Objects.equals(openIdBinding.getUserId(), userId)) {
+ throw new RuntimeException("当前微信已绑定其他账号,无法完成登录");
+ }
+ if (Integer.valueOf(1).equals(userBinding.getStatus()) && !Objects.equals(userBinding.getOpenId(), openId)) {
+ throw new RuntimeException("当前账号已绑定其他微信,请联系管理员处理");
+ }
+ wechatMiniBindingMapper.deleteById(userBinding.getId());
+ userBinding = null;
+ }
+
+ if (openIdBinding != null) {
+ if (Integer.valueOf(1).equals(openIdBinding.getStatus()) && !Objects.equals(openIdBinding.getUserId(), userId)) {
+ throw new RuntimeException("当前微信已绑定其他账号,无法完成登录");
+ }
+ openIdBinding.setUserId(userId);
+ openIdBinding.setUnionId(unionId);
+ openIdBinding.setStatus(1);
+ openIdBinding.setUpdateTime(LocalDateTime.now());
+ wechatMiniBindingMapper.updateById(openIdBinding);
+ return;
+ }
+
+ if (userBinding != null) {
+ if (Integer.valueOf(1).equals(userBinding.getStatus()) && !Objects.equals(userBinding.getOpenId(), openId)) {
+ throw new RuntimeException("当前账号已绑定其他微信,请联系管理员处理");
+ }
+ userBinding.setOpenId(openId);
+ userBinding.setUnionId(unionId);
+ userBinding.setStatus(1);
+ userBinding.setUpdateTime(LocalDateTime.now());
+ wechatMiniBindingMapper.updateById(userBinding);
+ return;
+ }
+
+ WechatMiniBindingDO bindingDO = new WechatMiniBindingDO();
+ bindingDO.setUserId(userId);
+ bindingDO.setAppId(wechatMiniClientService.getConfiguredAppId());
+ bindingDO.setOpenId(openId);
+ bindingDO.setUnionId(unionId);
+ bindingDO.setStatus(1);
+ wechatMiniBindingMapper.insert(bindingDO);
+ }
+
+ private void deactivateBinding(Long bindingId) {
+ if (bindingId == null) {
+ return;
+ }
+ wechatMiniBindingMapper.update(
+ null,
+ new LambdaUpdateWrapper()
+ .eq(WechatMiniBindingDO::getId, bindingId)
+ .set(WechatMiniBindingDO::getStatus, 0)
+ .set(WechatMiniBindingDO::getUpdateTime, LocalDateTime.now())
+ );
+ }
+
+ private Long resolvePreferredOrOnlyShop(List shops, Long preferredShopId) {
+ Long normalizedPreferredShopId = normalizeShopId(preferredShopId);
+ if (normalizedPreferredShopId != null) {
+ boolean matched = shops.stream().anyMatch(shop -> Objects.equals(shop.getId(), normalizedPreferredShopId));
+ if (matched) {
+ return normalizedPreferredShopId;
+ }
+ }
+ if (shops.size() == 1) {
+ return shops.get(0).getId();
+ }
+ return null;
+ }
+
+ private WechatMiniLoginResultVO buildSelectShopResult(
+ String message,
+ List shops,
+ TicketPayload ticketPayload
+ ) {
+ String ticket = storeTicketPayload(ticketPayload);
+ return WechatMiniLoginResultVO.selectShop(message, ticket, Boolean.TRUE.equals(ticketPayload.getNewUser()), shops);
+ }
+
+ private String storeTicketPayload(TicketPayload ticketPayload) {
+ String ticket = "wxmini_" + snowflakeIdGenerator.nextIdString();
+ try {
+ redisTemplate.opsForValue().set(
+ TICKET_KEY_PREFIX + ticket,
+ objectMapper.writeValueAsString(ticketPayload),
+ TICKET_TTL
+ );
+ return ticket;
+ } catch (JsonProcessingException exception) {
+ throw new RuntimeException("生成微信登录票据失败", exception);
+ }
+ }
+
+ private TicketPayload readTicketPayload(String ticket) {
+ String payloadJson = redisTemplate.opsForValue().get(TICKET_KEY_PREFIX + ticket);
+ if (!StringUtils.hasText(payloadJson)) {
+ throw new RuntimeException("登录票据已失效,请重新发起微信一键登录");
+ }
+ try {
+ return objectMapper.readValue(payloadJson, TicketPayload.class);
+ } catch (JsonProcessingException exception) {
+ throw new RuntimeException("解析微信登录票据失败", exception);
+ }
+ }
+
+ private void deleteTicketPayload(String ticket) {
+ redisTemplate.delete(TICKET_KEY_PREFIX + ticket);
+ }
+
+ private Long normalizeShopId(Long shopId) {
+ return shopId != null && shopId > 0 ? shopId : null;
+ }
+
+ private String normalizePhone(String phone) {
+ return phone == null ? "" : phone.trim();
+ }
+
+ @Data
+ private static class TicketPayload {
+ private Long userId;
+ private String phone;
+ private String openId;
+ private String unionId;
+ private Boolean newUser;
+
+ public TicketPayload() {
+ }
+
+ public TicketPayload(Long userId, String phone, String openId, String unionId, Boolean newUser) {
+ this.userId = userId;
+ this.phone = phone;
+ this.openId = openId;
+ this.unionId = unionId;
+ this.newUser = newUser;
+ }
+ }
+}
diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/WechatMiniClientServiceImpl.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/WechatMiniClientServiceImpl.java
new file mode 100644
index 00000000..8a9cd94a
--- /dev/null
+++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/service/impl/WechatMiniClientServiceImpl.java
@@ -0,0 +1,173 @@
+package com.xiaowang.yuminailcore.service.impl;
+
+import com.fasterxml.jackson.core.type.TypeReference;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.xiaowang.yuminailcore.config.WechatMiniProperties;
+import com.xiaowang.yuminailcore.service.WechatMiniClientService;
+import lombok.RequiredArgsConstructor;
+import org.springframework.data.redis.core.StringRedisTemplate;
+import org.springframework.http.HttpEntity;
+import org.springframework.http.HttpHeaders;
+import org.springframework.http.MediaType;
+import org.springframework.stereotype.Service;
+import org.springframework.util.StringUtils;
+import org.springframework.web.client.RestTemplate;
+import org.springframework.web.util.UriComponentsBuilder;
+
+import java.time.Duration;
+import java.util.Map;
+import java.util.Objects;
+
+/**
+ * 微信小程序开放接口客户端实现。
+ */
+@Service
+@RequiredArgsConstructor
+public class WechatMiniClientServiceImpl implements WechatMiniClientService {
+
+ private static final String ACCESS_TOKEN_CACHE_KEY_PREFIX = "wechat:mini:access-token:";
+ private static final String ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token";
+
+ private final RestTemplate restTemplate;
+ private final StringRedisTemplate redisTemplate;
+ private final ObjectMapper objectMapper;
+ private final WechatMiniProperties properties;
+
+ @Override
+ public SessionInfo code2Session(String wxCode) {
+ requireConfiguredCredentials();
+ Map response = readJsonResponse(
+ restTemplate.getForObject(
+ UriComponentsBuilder.fromHttpUrl(properties.getCode2sessionUrl())
+ .queryParam("appid", properties.getAppId())
+ .queryParam("secret", properties.getAppSecret())
+ .queryParam("js_code", wxCode)
+ .queryParam("grant_type", "authorization_code")
+ .build(true)
+ .toUri(),
+ Map.class
+ )
+ );
+ assertWechatResponseOk(response, "获取微信登录身份失败");
+ String openId = asText(response.get("openid"));
+ if (!StringUtils.hasText(openId)) {
+ throw new RuntimeException("获取微信登录身份失败:缺少 openid");
+ }
+ return new SessionInfo(openId, asText(response.get("unionid")), asText(response.get("session_key")));
+ }
+
+ @Override
+ public String getPhoneNumber(String phoneCode) {
+ String accessToken = getAccessToken();
+ HttpHeaders headers = new HttpHeaders();
+ headers.setContentType(MediaType.APPLICATION_JSON);
+
+ Map response = readJsonResponse(
+ restTemplate.postForObject(
+ UriComponentsBuilder.fromHttpUrl(properties.getPhoneNumberUrl())
+ .queryParam("access_token", accessToken)
+ .build(true)
+ .toUri(),
+ new HttpEntity<>(Map.of("code", phoneCode), headers),
+ Map.class
+ )
+ );
+ assertWechatResponseOk(response, "获取微信手机号失败");
+ Map phoneInfo = objectMapper.convertValue(
+ response.get("phone_info"),
+ new TypeReference