功能:新增微信小程序一键登录
This commit is contained in:
@@ -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',
|
||||
|
||||
+123
-2
@@ -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() {
|
||||
|
||||
@@ -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 '输入账号和密码即可登录;若账号绑定了多家门店,登录前需要先选择本次门店。'
|
||||
}
|
||||
})
|
||||
|
||||
@@ -4,21 +4,21 @@
|
||||
<view class="page-content auth-content">
|
||||
<view class="page-hero auth-hero">
|
||||
<text class="hero-kicker">YUMI NAIL</text>
|
||||
<text class="hero-title">{{activeTab === 'login' ? '登录后继续预约与收藏' : '注册账号,开始你的美甲旅程'}}</text>
|
||||
<text class="hero-desc">支持账号密码或手机验证码,绑定门店后,下单和查看记录都会更顺手。</text>
|
||||
<text class="hero-title">{{activeTab === 'login' ? '登录后继续预约、收藏与下单' : '注册账号,开启你的美甲旅程'}}</text>
|
||||
<text class="hero-desc">支持微信手机号一键登录,也保留账号密码与短信验证码登录方式。完成门店绑定后,订单、购物车与收藏会跟着账号同步。</text>
|
||||
|
||||
<view class="auth-benefits">
|
||||
<view class="auth-benefit">
|
||||
<text class="auth-benefit-title">收藏同步</text>
|
||||
<text class="auth-benefit-desc">喜欢的作品随时可回看</text>
|
||||
<text class="auth-benefit-title">微信直达</text>
|
||||
<text class="auth-benefit-desc">授权手机号后,可自动识别账号并快速登录</text>
|
||||
</view>
|
||||
<view class="auth-benefit">
|
||||
<text class="auth-benefit-title">预约顺手</text>
|
||||
<text class="auth-benefit-desc">登录后直接补全预约信息</text>
|
||||
<text class="auth-benefit-title">门店同步</text>
|
||||
<text class="auth-benefit-desc">支持选择本次登录门店,后续会优先记住</text>
|
||||
</view>
|
||||
<view class="auth-benefit">
|
||||
<text class="auth-benefit-title">门店绑定</text>
|
||||
<text class="auth-benefit-desc">注册时即可关联常用门店</text>
|
||||
<text class="auth-benefit-title">记录留存</text>
|
||||
<text class="auth-benefit-desc">订单、购物车与收藏统一跟账号同步</text>
|
||||
</view>
|
||||
</view>
|
||||
</view>
|
||||
@@ -29,14 +29,51 @@
|
||||
<view class="tab-item {{activeTab === 'register' ? 'active' : ''}}" data-tab="register" bindtap="handleTabChange">注册</view>
|
||||
</view>
|
||||
|
||||
<view wx:if="{{activeTab === 'login'}}" class="toggle-row">
|
||||
<view class="toggle-item {{loginType === 'password' ? 'active' : ''}}" data-type="password" bindtap="handleLoginTypeChange">账号密码登录</view>
|
||||
<view class="toggle-item {{loginType === 'phone' ? 'active' : ''}}" data-type="phone" bindtap="handleLoginTypeChange">验证码登录</view>
|
||||
</view>
|
||||
<block wx:if="{{activeTab === 'login'}}">
|
||||
<view class="wechat-login-panel">
|
||||
<text class="wechat-login-title">微信手机号一键登录</text>
|
||||
<text class="wechat-login-desc">适合已绑定微信的老用户,也支持首次授权后自动注册并绑定门店。</text>
|
||||
|
||||
<view class="auth-helper">
|
||||
{{activeTab === 'login' ? (loginType === 'password' ? '输入账号和密码即可登录。' : '手机号登录时会发送短信验证码。') : '注册前会实时检查账号和手机号是否已被占用。'}}
|
||||
</view>
|
||||
<button
|
||||
wx:if="{{wechatMiniSupported}}"
|
||||
class="primary-btn wechat-login-btn"
|
||||
open-type="getPhoneNumber"
|
||||
bindgetphonenumber="handleWechatMiniPhoneLogin"
|
||||
loading="{{wechatMiniLoading}}"
|
||||
disabled="{{wechatMiniLoading || loading}}"
|
||||
>
|
||||
{{wechatMiniLoading ? '正在获取微信手机号...' : '微信手机号一键登录'}}
|
||||
</button>
|
||||
|
||||
<button
|
||||
wx:else
|
||||
class="secondary-btn wechat-login-btn wechat-login-btn-disabled"
|
||||
bindtap="handleWechatMiniUnavailableTap"
|
||||
>
|
||||
微信手机号一键登录
|
||||
</button>
|
||||
|
||||
<text class="wechat-login-hint">{{wechatMiniSupported ? '若该微信已绑定且只有一家可用门店,将直接登录;首次授权时会先让你选择门店。' : wechatMiniDisabledReason}}</text>
|
||||
</view>
|
||||
|
||||
<view wx:if="{{miniShopTicket && !showMiniShopSelector}}" class="hint-card mini-login-resume">
|
||||
<text class="mini-login-resume-text">微信身份已识别完成,还差一步门店确认即可登录。</text>
|
||||
<view class="ghost-btn mini-login-resume-btn" bindtap="handleResumeMiniShopSelector">继续选择门店</view>
|
||||
</view>
|
||||
|
||||
<view class="login-divider">
|
||||
<view class="divider-line"></view>
|
||||
<text class="login-divider-text">传统登录方式</text>
|
||||
<view class="divider-line"></view>
|
||||
</view>
|
||||
|
||||
<view class="toggle-row">
|
||||
<view class="toggle-item {{loginType === 'password' ? 'active' : ''}}" data-type="password" bindtap="handleLoginTypeChange">账号密码登录</view>
|
||||
<view class="toggle-item {{loginType === 'phone' ? 'active' : ''}}" data-type="phone" bindtap="handleLoginTypeChange">验证码登录</view>
|
||||
</view>
|
||||
</block>
|
||||
|
||||
<view class="auth-helper">{{authHelperText}}</view>
|
||||
|
||||
<block wx:if="{{activeTab === 'register'}}">
|
||||
<view class="field-block">
|
||||
@@ -106,7 +143,7 @@
|
||||
|
||||
<view wx:if="{{showResetPanel}}" class="page-card reset-card">
|
||||
<view class="section-title">重置密码</view>
|
||||
<view class="section-subtitle">使用手机验证码设置新的登录密码。</view>
|
||||
<view class="section-subtitle">使用手机号验证码设置新的登录密码。</view>
|
||||
|
||||
<view class="field-block">
|
||||
<text class="field-label">手机号</text>
|
||||
@@ -129,4 +166,26 @@
|
||||
<view class="primary-btn submit-btn" bindtap="handleResetPassword">确认重置密码</view>
|
||||
</view>
|
||||
</view>
|
||||
|
||||
<view wx:if="{{showMiniShopSelector}}" class="mini-shop-mask" catchtouchmove="noop">
|
||||
<view class="page-card mini-shop-modal">
|
||||
<text class="mini-shop-kicker">{{miniShopNewUser ? '首次微信登录' : '确认本次登录门店'}}</text>
|
||||
<text class="mini-shop-title">{{miniShopNewUser ? '先选一家门店,我们会自动注册并登录' : '该账号绑定了多家门店,请先选择本次登录门店'}}</text>
|
||||
<text class="mini-shop-desc">{{miniShopMessage || '选择后将继续完成登录。'}}</text>
|
||||
|
||||
<view class="field-block mini-shop-field">
|
||||
<text class="field-label">登录门店</text>
|
||||
<picker mode="selector" range="{{miniShops}}" range-key="shopName" value="{{miniShopIndex}}" bindchange="handleMiniShopChange">
|
||||
<view class="field-picker">{{miniShopDisplayName || '请选择门店'}}</view>
|
||||
</picker>
|
||||
</view>
|
||||
|
||||
<view wx:if="{{miniShopNewUser}}" class="hint-card mini-shop-note">首次通过微信手机号登录时,会自动创建账号、绑定手机号,并将当前门店作为本次登录门店。</view>
|
||||
|
||||
<view class="mini-shop-actions">
|
||||
<view class="secondary-btn mini-shop-action" bindtap="handleCloseMiniShopSelector">稍后再选</view>
|
||||
<view class="primary-btn mini-shop-action" bindtap="handleConfirmMiniShopLogin">{{miniShopSubmitting ? '确认中...' : '确认登录'}}</view>
|
||||
</view>
|
||||
</view>
|
||||
</view>
|
||||
</view>
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -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')
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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/',
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
@@ -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/**",
|
||||
|
||||
+20
@@ -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;
|
||||
}
|
||||
@@ -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<WechatMiniLoginResultVO> wechatMiniAutoLogin(@Valid @RequestBody WechatMiniAutoLoginRequestDTO requestDTO) {
|
||||
return Result.success(wechatMiniAuthService.autoLogin(requestDTO));
|
||||
}
|
||||
|
||||
@PostMapping("/wechat-mini/phone-login")
|
||||
public Result<WechatMiniLoginResultVO> wechatMiniPhoneLogin(@Valid @RequestBody WechatMiniPhoneLoginRequestDTO requestDTO) {
|
||||
return Result.success(wechatMiniAuthService.phoneLogin(requestDTO));
|
||||
}
|
||||
|
||||
@PostMapping("/wechat-mini/confirm-login")
|
||||
public Result<WechatMiniLoginResultVO> confirmWechatMiniLogin(@Valid @RequestBody WechatMiniConfirmLoginRequestDTO requestDTO) {
|
||||
return Result.success(wechatMiniAuthService.confirmLogin(requestDTO));
|
||||
}
|
||||
|
||||
@PostMapping("/switch-shop")
|
||||
public Result<LoginResponseVO> switchShop(HttpServletRequest request, @RequestBody SwitchShopRequestDTO switchShopRequestDTO) {
|
||||
Long userId = (Long) request.getAttribute("userId");
|
||||
|
||||
+17
@@ -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;
|
||||
}
|
||||
+19
@@ -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;
|
||||
}
|
||||
+20
@@ -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;
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
+10
@@ -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<WechatMiniBindingDO> {
|
||||
}
|
||||
@@ -39,6 +39,10 @@ public interface UserService extends IService<UserDO> {
|
||||
|
||||
LoginResponseVO phoneLogin(PhoneLoginRequestDTO phoneLoginRequestDTO);
|
||||
|
||||
LoginResponseVO loginByVerifiedPhone(String phone, Long shopId);
|
||||
|
||||
LoginResponseVO loginByUserId(Long userId, Long shopId);
|
||||
|
||||
LoginResponseVO adminLogin(LoginRequestDTO loginRequestDTO);
|
||||
|
||||
LoginShopSelectionVO getLoginShopSelectionByAccount(String account);
|
||||
|
||||
+20
@@ -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);
|
||||
}
|
||||
+16
@@ -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) {
|
||||
}
|
||||
}
|
||||
+42
@@ -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<UserMapper, UserDO> implements
|
||||
private final UserShopBindingSupport userShopBindingSupport;
|
||||
private final StringRedisTemplate redisTemplate;
|
||||
private final TimeOrderedSnowflakeIdGenerator snowflakeIdGenerator;
|
||||
private final WechatMiniBindingMapper wechatMiniBindingMapper;
|
||||
|
||||
private static Map<String, PermissionSeed> buildDefaultPermissionSeeds() {
|
||||
Map<String, PermissionSeed> seeds = new HashMap<>();
|
||||
@@ -427,6 +430,13 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
|
||||
|
||||
clearLoginFailureCount(userDO.getAccount());
|
||||
userShopBindingSupport.deleteBindingsByUserId(id);
|
||||
wechatMiniBindingMapper.update(
|
||||
null,
|
||||
new LambdaUpdateWrapper<WechatMiniBindingDO>()
|
||||
.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<UserMapper, UserDO> 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"; // 加密后的特殊标识
|
||||
|
||||
|
||||
+378
@@ -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<ShopSimpleVO> 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<WechatMiniBindingDO>()
|
||||
.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<ShopSimpleVO> 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<UserDO>()
|
||||
.eq(UserDO::getPhone, phone)
|
||||
.eq(UserDO::getIsDelete, 0)
|
||||
.last("limit 1")
|
||||
);
|
||||
}
|
||||
|
||||
private WechatMiniBindingDO findBindingByOpenId(String openId) {
|
||||
return wechatMiniBindingMapper.selectOne(
|
||||
new LambdaQueryWrapper<WechatMiniBindingDO>()
|
||||
.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<WechatMiniBindingDO>()
|
||||
.eq(WechatMiniBindingDO::getAppId, wechatMiniClientService.getConfiguredAppId())
|
||||
.eq(WechatMiniBindingDO::getOpenId, openId)
|
||||
.last("limit 1")
|
||||
);
|
||||
}
|
||||
|
||||
private WechatMiniBindingDO findAnyBindingByUserId(Long userId) {
|
||||
return wechatMiniBindingMapper.selectOne(
|
||||
new LambdaQueryWrapper<WechatMiniBindingDO>()
|
||||
.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<WechatMiniBindingDO>()
|
||||
.eq(WechatMiniBindingDO::getId, bindingId)
|
||||
.set(WechatMiniBindingDO::getStatus, 0)
|
||||
.set(WechatMiniBindingDO::getUpdateTime, LocalDateTime.now())
|
||||
);
|
||||
}
|
||||
|
||||
private Long resolvePreferredOrOnlyShop(List<ShopSimpleVO> 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<ShopSimpleVO> 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
+173
@@ -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<String, Object> 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<String, Object> 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<String, Object> phoneInfo = objectMapper.convertValue(
|
||||
response.get("phone_info"),
|
||||
new TypeReference<Map<String, Object>>() {
|
||||
}
|
||||
);
|
||||
String phoneNumber = asText(phoneInfo.get("phoneNumber"));
|
||||
if (!StringUtils.hasText(phoneNumber)) {
|
||||
phoneNumber = asText(phoneInfo.get("purePhoneNumber"));
|
||||
}
|
||||
if (!StringUtils.hasText(phoneNumber)) {
|
||||
throw new RuntimeException("获取微信手机号失败:未返回手机号");
|
||||
}
|
||||
return phoneNumber;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getConfiguredAppId() {
|
||||
requireConfiguredCredentials();
|
||||
return properties.getAppId();
|
||||
}
|
||||
|
||||
private String getAccessToken() {
|
||||
requireConfiguredCredentials();
|
||||
String cacheKey = ACCESS_TOKEN_CACHE_KEY_PREFIX + properties.getAppId();
|
||||
String cachedToken = redisTemplate.opsForValue().get(cacheKey);
|
||||
if (StringUtils.hasText(cachedToken)) {
|
||||
return cachedToken;
|
||||
}
|
||||
|
||||
Map<String, Object> response = readJsonResponse(
|
||||
restTemplate.getForObject(
|
||||
UriComponentsBuilder.fromHttpUrl(ACCESS_TOKEN_URL)
|
||||
.queryParam("grant_type", "client_credential")
|
||||
.queryParam("appid", properties.getAppId())
|
||||
.queryParam("secret", properties.getAppSecret())
|
||||
.build(true)
|
||||
.toUri(),
|
||||
Map.class
|
||||
)
|
||||
);
|
||||
assertWechatResponseOk(response, "获取微信 access_token 失败");
|
||||
|
||||
String accessToken = asText(response.get("access_token"));
|
||||
if (!StringUtils.hasText(accessToken)) {
|
||||
throw new RuntimeException("获取微信 access_token 失败:未返回 access_token");
|
||||
}
|
||||
|
||||
long expiresIn = parseLong(response.get("expires_in"), 7200L);
|
||||
long safeBuffer = Math.max(0L, Objects.requireNonNullElse(properties.getAccessTokenBufferSeconds(), 60));
|
||||
long ttlSeconds = Math.max(60L, expiresIn - safeBuffer);
|
||||
redisTemplate.opsForValue().set(cacheKey, accessToken, Duration.ofSeconds(ttlSeconds));
|
||||
return accessToken;
|
||||
}
|
||||
|
||||
private void requireConfiguredCredentials() {
|
||||
if (!StringUtils.hasText(properties.getAppId()) || !StringUtils.hasText(properties.getAppSecret())) {
|
||||
throw new RuntimeException("微信小程序登录未配置 appId/appSecret");
|
||||
}
|
||||
}
|
||||
|
||||
private Map<String, Object> readJsonResponse(Object response) {
|
||||
if (response == null) {
|
||||
throw new RuntimeException("微信服务未返回数据");
|
||||
}
|
||||
return objectMapper.convertValue(response, new TypeReference<Map<String, Object>>() {
|
||||
});
|
||||
}
|
||||
|
||||
private void assertWechatResponseOk(Map<String, Object> response, String defaultMessage) {
|
||||
long errCode = parseLong(response.get("errcode"), 0L);
|
||||
if (errCode == 0L) {
|
||||
return;
|
||||
}
|
||||
String errMsg = asText(response.get("errmsg"));
|
||||
throw new RuntimeException(defaultMessage + ":" + (StringUtils.hasText(errMsg) ? errMsg : ("错误码 " + errCode)));
|
||||
}
|
||||
|
||||
private long parseLong(Object value, long defaultValue) {
|
||||
if (value == null) {
|
||||
return defaultValue;
|
||||
}
|
||||
if (value instanceof Number number) {
|
||||
return number.longValue();
|
||||
}
|
||||
if (value instanceof String text && StringUtils.hasText(text)) {
|
||||
try {
|
||||
return Long.parseLong(text);
|
||||
} catch (NumberFormatException ignored) {
|
||||
return defaultValue;
|
||||
}
|
||||
}
|
||||
return defaultValue;
|
||||
}
|
||||
|
||||
private String asText(Object value) {
|
||||
return value == null ? "" : String.valueOf(value).trim();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
package com.xiaowang.yuminailcore.vo;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 微信小程序登录结果。
|
||||
*/
|
||||
@Data
|
||||
public class WechatMiniLoginResultVO {
|
||||
|
||||
public static final String STATUS_SUCCESS = "SUCCESS";
|
||||
public static final String STATUS_SELECT_SHOP = "SELECT_SHOP";
|
||||
public static final String STATUS_NEED_MANUAL_LOGIN = "NEED_MANUAL_LOGIN";
|
||||
|
||||
private String status;
|
||||
private String message;
|
||||
private String ticket;
|
||||
private Boolean newUser;
|
||||
private List<ShopSimpleVO> shops;
|
||||
private String accessToken;
|
||||
private String refreshToken;
|
||||
private LoginResponseVO.UserInfo userInfo;
|
||||
private Boolean needSetPassword;
|
||||
|
||||
public static WechatMiniLoginResultVO success(String message, LoginResponseVO loginResponse, boolean newUser) {
|
||||
WechatMiniLoginResultVO resultVO = new WechatMiniLoginResultVO();
|
||||
resultVO.setStatus(STATUS_SUCCESS);
|
||||
resultVO.setMessage(message);
|
||||
resultVO.setNewUser(newUser);
|
||||
resultVO.setAccessToken(loginResponse.getAccessToken());
|
||||
resultVO.setRefreshToken(loginResponse.getRefreshToken());
|
||||
resultVO.setUserInfo(loginResponse.getUserInfo());
|
||||
resultVO.setNeedSetPassword(loginResponse.isNeedSetPassword());
|
||||
return resultVO;
|
||||
}
|
||||
|
||||
public static WechatMiniLoginResultVO selectShop(
|
||||
String message,
|
||||
String ticket,
|
||||
boolean newUser,
|
||||
List<ShopSimpleVO> shops
|
||||
) {
|
||||
WechatMiniLoginResultVO resultVO = new WechatMiniLoginResultVO();
|
||||
resultVO.setStatus(STATUS_SELECT_SHOP);
|
||||
resultVO.setMessage(message);
|
||||
resultVO.setTicket(ticket);
|
||||
resultVO.setNewUser(newUser);
|
||||
resultVO.setShops(shops);
|
||||
return resultVO;
|
||||
}
|
||||
|
||||
public static WechatMiniLoginResultVO needManualLogin(String message) {
|
||||
WechatMiniLoginResultVO resultVO = new WechatMiniLoginResultVO();
|
||||
resultVO.setStatus(STATUS_NEED_MANUAL_LOGIN);
|
||||
resultVO.setMessage(message);
|
||||
resultVO.setNewUser(false);
|
||||
return resultVO;
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,13 @@
|
||||
# YumiNail 前后端接口文档
|
||||
# YumiNail 前后端接口文档
|
||||
|
||||
## 一、项目模块结构
|
||||
|
||||
| 模块 | 路径 | 说明 |
|
||||
|------|------|------|
|
||||
| Frontend | `Frontend/` | Vue3前端项目 |
|
||||
| YumiNail-Frontend | `YumiNail-Frontend/` | YumiNail 主业务 Vue3 前端项目 |
|
||||
| YumiNail-Calendar-Frontend | `YumiNail-Calendar-Frontend/` | 美甲师日历表独立前端项目 |
|
||||
| YumiNail-Calendar-Gateway | `YumiNail-Calendar-Gateway/` | 美甲师日历表独立网关 |
|
||||
| YumiNail-Calendar-Core | `YumiNail-Calendar-Core/` | 美甲师日历表独立后端服务 |
|
||||
| YumiNail-Gateway | `YumiNail-Gateway/` | Spring Cloud Gateway网关 |
|
||||
| YumiNail-Core | `YumiNail-Core/` | 核心业务服务 |
|
||||
| MessageHub | `MessageHub/` | 消息推送服务 |
|
||||
@@ -52,6 +55,9 @@ baseURL: `http://wcy111.top:8088/api`
|
||||
|-------------|----------------|----------|------|------|
|
||||
| `/api/user/login` | UserController | `/user/login` | POST | 用户登录 |
|
||||
| `/api/user/phone-login` | UserController | `/user/phone-login` | POST | 手机号登录 |
|
||||
| `/api/user/wechat-mini/auto-login` | UserController | `/user/wechat-mini/auto-login` | POST | 小程序冷启动自动登录 |
|
||||
| `/api/user/wechat-mini/phone-login` | UserController | `/user/wechat-mini/phone-login` | POST | 小程序微信手机号一键登录 |
|
||||
| `/api/user/wechat-mini/confirm-login` | UserController | `/user/wechat-mini/confirm-login` | POST | 小程序补选门店后确认登录 |
|
||||
| `/api/user/register` | UserController | `/user/register` | POST | 用户注册 |
|
||||
| `/api/user/refresh-token` | UserController | `/user/refresh-token` | POST | 刷新Token |
|
||||
| `/api/user/logout` | UserController | `/user/logout` | POST | 用户登出 |
|
||||
@@ -67,6 +73,11 @@ baseURL: `http://wcy111.top:8088/api`
|
||||
| `/api/user/bind-phone` | UserController | `/user/bind-phone` | POST | 绑定手机号 |
|
||||
| `/api/user/phone` | UserController | `/user/phone` | PUT | 修改手机号 |
|
||||
| `/api/user/get/account/{account}` | UserController | `/user/get/account/{account}` | GET | 根据账号查询用户 |
|
||||
| `/api/user/check/account/{account}` | UserController | `/user/check/account/{account}` | GET | 检查注册账号是否可用 |
|
||||
| `/api/user/check/phone/{phone}` | UserController | `/user/check/phone/{phone}` | GET | 检查手机号是否可用 |
|
||||
| `/api/user/check/login-account/{account}` | UserController | `/user/check/login-account/{account}` | GET | 检查登录账号是否存在并返回昵称提示 |
|
||||
| `/api/user/check/login-shops/account/{account}` | UserController | `/user/check/login-shops/account/{account}` | GET | 按账号预加载可登录门店 |
|
||||
| `/api/user/check/login-shops/phone/{phone}` | UserController | `/user/check/login-shops/phone/{phone}` | GET | 按手机号预加载可登录门店 |
|
||||
| `/api/user/list/type/{type}` | UserController | `/user/list/type/{type}` | GET | 根据类型查询用户 |
|
||||
| `/api/user/send-verification-code` | UserController | `/user/send-verification-code` | POST | 发送验证码 |
|
||||
| `/api/user/deactivate` | UserController | `/user/deactivate` | DELETE | 注销账号 |
|
||||
@@ -293,9 +304,12 @@ yuminail:
|
||||
# 用户端白名单
|
||||
- /user/login
|
||||
- /user/register
|
||||
- /user/check/**
|
||||
- /user/refresh-token
|
||||
- /user/send-verification-code
|
||||
- /user/phone-login
|
||||
- /user/wechat-mini/**
|
||||
- /user/reset-password-by-phone
|
||||
- /user/get/account/**
|
||||
- /shop/list/simple
|
||||
- /health/**
|
||||
@@ -309,6 +323,22 @@ yuminail:
|
||||
- 白名单配置**不需要**带 `/api` 前缀
|
||||
- 网关在处理请求时会自动去掉 `/api` 前缀后再进行白名单匹配
|
||||
- 所有不在白名单中的接口都需要携带有效的Token
|
||||
- 小程序微信登录链路 `/user/wechat-mini/**` 需要同步加入 Gateway 本地配置、Gateway 代码默认白名单、Core 拦截器白名单、小程序请求层白名单,以及 Nacos `YumiNail-Dev` 对应 whitelist 配置
|
||||
|
||||
### 5.3 小程序微信登录配置
|
||||
|
||||
以下配置通过 Nacos `YumiNail-Dev` 命名空间维护:
|
||||
|
||||
```yaml
|
||||
yuminail:
|
||||
wechat:
|
||||
mini:
|
||||
app-id: wx1234567890abcdef
|
||||
app-secret: your-mini-program-secret
|
||||
code2session-url: https://api.weixin.qq.com/sns/jscode2session
|
||||
phone-number-url: https://api.weixin.qq.com/wxa/business/getuserphonenumber
|
||||
access-token-buffer-seconds: 60
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
@@ -412,3 +442,4 @@ public Result<Long> createProduct(@RequestBody ProductDTO productDTO) {
|
||||
3. **Token校验由网关统一处理**
|
||||
4. **权限校验由后端Controller通过注解处理**
|
||||
5. **后端Controller路径保持不变**
|
||||
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
CREATE TABLE IF NOT EXISTS t_wechat_mini_binding
|
||||
(
|
||||
id BIGINT UNSIGNED NOT NULL COMMENT '微信小程序绑定主键ID(雪花ID)',
|
||||
user_id BIGINT UNSIGNED NOT NULL COMMENT '关联用户ID',
|
||||
app_id VARCHAR(64) NOT NULL COMMENT '微信小程序appId',
|
||||
openid VARCHAR(100) NOT NULL COMMENT '微信小程序openid',
|
||||
unionid VARCHAR(100) NULL COMMENT '微信开放平台unionid',
|
||||
status TINYINT UNSIGNED DEFAULT 1 NULL COMMENT '状态:1-有效,0-失效',
|
||||
create_time DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL COMMENT '创建时间',
|
||||
update_time DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
|
||||
PRIMARY KEY (id)
|
||||
) COMMENT = '微信小程序账号绑定表';
|
||||
|
||||
DROP PROCEDURE IF EXISTS sp_add_index_if_not_exists;
|
||||
DELIMITER $$
|
||||
CREATE PROCEDURE sp_add_index_if_not_exists(
|
||||
IN p_table_name VARCHAR(64),
|
||||
IN p_index_name VARCHAR(64),
|
||||
IN p_index_sql TEXT
|
||||
)
|
||||
BEGIN
|
||||
IF NOT EXISTS (
|
||||
SELECT 1
|
||||
FROM information_schema.statistics
|
||||
WHERE table_schema = DATABASE()
|
||||
AND table_name = p_table_name
|
||||
AND index_name = p_index_name
|
||||
) THEN
|
||||
SET @index_sql = p_index_sql;
|
||||
PREPARE stmt FROM @index_sql;
|
||||
EXECUTE stmt;
|
||||
DEALLOCATE PREPARE stmt;
|
||||
END IF;
|
||||
END$$
|
||||
DELIMITER ;
|
||||
|
||||
CALL sp_add_index_if_not_exists(
|
||||
't_wechat_mini_binding',
|
||||
'idx_wechat_mini_unionid',
|
||||
'CREATE INDEX idx_wechat_mini_unionid ON t_wechat_mini_binding (unionid)'
|
||||
);
|
||||
|
||||
CALL sp_add_index_if_not_exists(
|
||||
't_wechat_mini_binding',
|
||||
'uk_wechat_mini_app_openid',
|
||||
'ALTER TABLE t_wechat_mini_binding ADD CONSTRAINT uk_wechat_mini_app_openid UNIQUE (app_id, openid)'
|
||||
);
|
||||
|
||||
CALL sp_add_index_if_not_exists(
|
||||
't_wechat_mini_binding',
|
||||
'uk_wechat_mini_app_user',
|
||||
'ALTER TABLE t_wechat_mini_binding ADD CONSTRAINT uk_wechat_mini_app_user UNIQUE (app_id, user_id)'
|
||||
);
|
||||
|
||||
DROP PROCEDURE IF EXISTS sp_add_index_if_not_exists;
|
||||
@@ -193,6 +193,29 @@ create index idx_user_id
|
||||
on t_login_identity (user_id)
|
||||
comment '按用户查询登录标识的索引';
|
||||
|
||||
-- auto-generated definition
|
||||
create table t_wechat_mini_binding
|
||||
(
|
||||
id bigint unsigned auto_increment comment '微信小程序绑定主键ID(雪花ID)'
|
||||
primary key,
|
||||
user_id bigint unsigned not null comment '关联用户ID',
|
||||
app_id varchar(64) not null comment '微信小程序appId',
|
||||
openid varchar(100) not null comment '微信小程序openid',
|
||||
unionid varchar(100) null comment '微信开放平台unionid',
|
||||
status tinyint unsigned default 1 null comment '状态:1-有效,0-失效',
|
||||
create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间',
|
||||
update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间',
|
||||
constraint uk_wechat_mini_app_openid
|
||||
unique (app_id, openid),
|
||||
constraint uk_wechat_mini_app_user
|
||||
unique (app_id, user_id)
|
||||
)
|
||||
comment '微信小程序账号绑定表';
|
||||
|
||||
create index idx_wechat_mini_unionid
|
||||
on t_wechat_mini_binding (unionid)
|
||||
comment '按unionid查询的索引';
|
||||
|
||||
-- auto-generated definition
|
||||
create table t_nail_artist_info
|
||||
(
|
||||
@@ -1327,6 +1350,7 @@ CALL sp_drop_auto_increment_on_id_if_exists('t_coupon');
|
||||
CALL sp_drop_auto_increment_on_id_if_exists('t_coupon_tag');
|
||||
CALL sp_drop_auto_increment_on_id_if_exists('t_effect_diagram');
|
||||
CALL sp_drop_auto_increment_on_id_if_exists('t_login_identity');
|
||||
CALL sp_drop_auto_increment_on_id_if_exists('t_wechat_mini_binding');
|
||||
CALL sp_drop_auto_increment_on_id_if_exists('t_nail_artist_info');
|
||||
CALL sp_drop_auto_increment_on_id_if_exists('t_object_storage_file');
|
||||
CALL sp_drop_auto_increment_on_id_if_exists('t_order');
|
||||
|
||||
+1
@@ -37,6 +37,7 @@ public class AuthGlobalFilter implements GlobalFilter, Ordered {
|
||||
"/api/user/refresh-token",
|
||||
"/api/user/send-verification-code",
|
||||
"/api/user/phone-login",
|
||||
"/api/user/wechat-mini/**",
|
||||
"/api/user/reset-password-by-phone",
|
||||
"/api/product/get/**",
|
||||
"/api/product/list/**",
|
||||
|
||||
@@ -121,6 +121,7 @@ yuminail:
|
||||
- /api/user/refresh-token
|
||||
- /api/user/send-verification-code
|
||||
- /api/user/phone-login
|
||||
- /api/user/wechat-mini/**
|
||||
- /api/user/reset-password-by-phone
|
||||
- /api/shop/list/simple
|
||||
- /api/health/**
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
# 项目架构分析
|
||||
# 项目架构分析
|
||||
|
||||
## 1. 项目结构
|
||||
|
||||
### 1.1 目录结构
|
||||
|
||||
```
|
||||
├── Frontend/ # 前端项目
|
||||
├── YumiNail-Frontend/ # YumiNail 主业务前端项目
|
||||
│ ├── src/
|
||||
│ │ ├── api/ # API请求封装
|
||||
│ │ ├── router/ # 路由配置
|
||||
@@ -21,6 +21,9 @@
|
||||
│ ├── controller/ # 控制器
|
||||
│ ├── service/ # 业务逻辑
|
||||
│ └── utils/ # 工具类
|
||||
├── YumiNail-Calendar-Frontend/ # 美甲师日历表独立前端项目
|
||||
├── YumiNail-Calendar-Gateway/ # 美甲师日历表独立网关
|
||||
├── YumiNail-Calendar-Core/ # 美甲师日历表独立后端
|
||||
└── MessageHub/ # 消息推送服务
|
||||
```
|
||||
|
||||
@@ -45,6 +48,12 @@
|
||||
- 对于管理员路由,会检查adminAccessToken
|
||||
- 对于需要权限的页面,会检查用户是否拥有对应权限
|
||||
|
||||
4. **小程序自动登录**:
|
||||
- `WeChatProgram/app.js` 会在本地没有有效 session 时自动执行 `wx.login -> /api/user/wechat-mini/auto-login`
|
||||
- 若返回 `SUCCESS`,会直接写入 accessToken、refreshToken 和当前用户门店信息
|
||||
- 若返回 `SELECT_SHOP`,会把一次性 ticket 缓存在小程序全局态,等进入登录页后再弹出独立门店选择层
|
||||
- `WeChatProgram/utils/navigation.js` 的 `ensureLogin` 会等待这段启动期自动登录 promise 结束,再决定是否跳转登录页,避免先跳页后又自动登录成功的闪烁
|
||||
|
||||
### 2.2 后端处理流程
|
||||
|
||||
1. **网关过滤**:
|
||||
@@ -56,6 +65,8 @@
|
||||
- AuthInterceptor会进一步验证token的有效性
|
||||
- 验证token是否过期、是否为accessToken类型
|
||||
- 从token中提取用户信息并设置到请求属性中
|
||||
- 微信小程序登录由 `WechatMiniAuthService` 统一编排:先调用微信 `jscode2session` / 手机号接口,再决定是自动登录、补选门店还是回退到传统登录
|
||||
- `SELECT_SHOP` 场景会把一次性 ticket 存入 Redis,TTL 为 5 分钟;用户在登录页确认门店后再调用 `/api/user/wechat-mini/confirm-login` 完成收口
|
||||
- 后台账号密码登录会强制校验 `shopId`,防止仅靠前端“选店铺”表单限制被绕过
|
||||
- 当系统内尚无店铺时,仅平台管理员可跳过 `shopId` 进入后台;此时运行时权限会被收紧到 `shop:view` 与 `shop:create`
|
||||
- 订单创建时还会校验购物车归属、同店铺/同美甲师约束、预约时间有效性、门店营业时间以及美甲师已有预约冲突
|
||||
@@ -70,7 +81,7 @@
|
||||
|
||||
### 3.1 前端白名单
|
||||
|
||||
在`Frontend/src/api/index.ts`中定义:
|
||||
在`YumiNail-Frontend/src/api/index.ts`中定义:
|
||||
|
||||
```typescript
|
||||
const isWhitelistedPath = (url: string) => {
|
||||
@@ -80,12 +91,15 @@ const isWhitelistedPath = (url: string) => {
|
||||
url?.includes('/user/refresh-token') ||
|
||||
url?.includes('/user/send-verification-code') ||
|
||||
url?.includes('/user/phone-login') ||
|
||||
url?.includes('/user/wechat-mini/') ||
|
||||
url?.includes('/shop/list/simple') ||
|
||||
url?.includes('/admin/auth/login') ||
|
||||
url?.includes('/admin/auth/refresh')
|
||||
}
|
||||
```
|
||||
|
||||
小程序端对应的 `WeChatProgram/utils/request.js` 也需要把 `/user/wechat-mini/` 视为免鉴权白名单,否则冷启动自动登录会被误判为 401。
|
||||
|
||||
### 3.2 网关白名单
|
||||
|
||||
在`YumiNail-Gateway/src/main/resources/application.yaml`中通过配置集中维护:
|
||||
@@ -100,6 +114,7 @@ yuminail:
|
||||
- /api/user/refresh-token
|
||||
- /api/user/send-verification-code
|
||||
- /api/user/phone-login
|
||||
- /api/user/wechat-mini/**
|
||||
- /api/user/reset-password-by-phone
|
||||
- /api/shop/list/simple
|
||||
- /api/health/**
|
||||
@@ -121,6 +136,7 @@ registry.addInterceptor(authInterceptor)
|
||||
"/user/refresh-token",
|
||||
"/user/send-verification-code",
|
||||
"/user/phone-login",
|
||||
"/user/wechat-mini/**",
|
||||
"/user/reset-password-by-phone",
|
||||
"/shop/list/simple",
|
||||
"/admin/auth/login",
|
||||
@@ -133,6 +149,8 @@ registry.addInterceptor(authInterceptor)
|
||||
### 3.4 白名单补充说明
|
||||
|
||||
- 账号检测链路 `GET /api/user/check/account/{account}`、`GET /api/user/check/phone/{phone}`、`GET /api/user/check/login-account/{account}` 必须同时在前端、网关、本地 Core 拦截器以及 Nacos `YumiNail-Dev` 白名单中保持一致。
|
||||
- 微信小程序登录链路 `POST /api/user/wechat-mini/auto-login`、`POST /api/user/wechat-mini/phone-login`、`POST /api/user/wechat-mini/confirm-login` 也必须同时在小程序请求层、Gateway 本地默认白名单、Gateway 配置白名单、Core 拦截器白名单与 Nacos `YumiNail-Dev` whitelist 中保持一致。
|
||||
- 微信开放平台配置通过 Nacos `YumiNail-Dev` 下的 `yuminail.wechat.mini.*` 维护,至少包括 `app-id`、`app-secret`、`code2session-url`、`phone-number-url` 和 `access-token-buffer-seconds`。
|
||||
- 白名单只开放登录、注册、验证码、刷新 token、店铺简表、健康检查与账号检测接口;其余用户资产、订单、购物车、后台管理接口仍必须携带 token。
|
||||
|
||||
## 4. 权限控制体系
|
||||
@@ -641,3 +659,4 @@ registry.addInterceptor(authInterceptor)
|
||||
该项目采用了现代化的前后端分离架构,具有完善的认证和授权机制,以及良好的安全设计。通过多层白名单保护和双Token认证,确保了系统的安全性。同时,清晰的代码组织和合理的服务拆分,为系统的可维护性和扩展性奠定了基础。
|
||||
|
||||
在未来的发展中,可以通过集中管理白名单、增强权限管理、加强安全性和完善监控日志等方面进一步提升系统的可靠性和安全性。
|
||||
|
||||
|
||||
@@ -0,0 +1,125 @@
|
||||
# 小程序微信手机号一键登录接入
|
||||
|
||||
## 本轮目标
|
||||
|
||||
- 接通 `WeChatProgram` 的微信手机号一键登录能力
|
||||
- 支持微信身份绑定、冷启动自动登录、补选门店后确认登录
|
||||
- 保留现有账号密码登录与短信验证码登录作为兜底
|
||||
- 新增独立微信绑定表,并同步增量 SQL 与初始化 SQL
|
||||
- 补齐 Gateway / Core / 小程序请求层 / 文档中的白名单同步点
|
||||
|
||||
## 代码变更
|
||||
|
||||
### 后端
|
||||
|
||||
- 新增微信小程序绑定实体、Mapper、DTO、VO:
|
||||
- `YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/entity/WechatMiniBindingDO.java`
|
||||
- `YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/mapper/WechatMiniBindingMapper.java`
|
||||
- `YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/WechatMiniAutoLoginRequestDTO.java`
|
||||
- `YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/WechatMiniPhoneLoginRequestDTO.java`
|
||||
- `YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/dto/WechatMiniConfirmLoginRequestDTO.java`
|
||||
- `YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/vo/WechatMiniLoginResultVO.java`
|
||||
- 新增微信开放接口客户端与登录编排服务:
|
||||
- `WechatMiniClientService` / `WechatMiniClientServiceImpl`
|
||||
- `WechatMiniAuthService` / `WechatMiniAuthServiceImpl`
|
||||
- 新增公共接口:
|
||||
- `POST /api/user/wechat-mini/auto-login`
|
||||
- `POST /api/user/wechat-mini/phone-login`
|
||||
- `POST /api/user/wechat-mini/confirm-login`
|
||||
- `UserService` / `UserServiceImpl` 增补:
|
||||
- `loginByVerifiedPhone(String phone, Long shopId)`
|
||||
- `loginByUserId(Long userId, Long shopId)`
|
||||
- 删除用户时会同步将 `t_wechat_mini_binding.status` 置为 `0`,避免旧绑定污染重新注册
|
||||
- 微信补选门店 ticket 使用 Redis 存储,TTL 固定为 5 分钟
|
||||
- ticket 改为 `wxmini_` + 雪花 ID,避免新逻辑继续引入 UUID
|
||||
|
||||
### 小程序
|
||||
|
||||
- `WeChatProgram/app.js`
|
||||
- 启动时在本地无 session 时自动尝试 `wx.login -> /api/user/wechat-mini/auto-login`
|
||||
- 新增待完成微信登录上下文缓存与冷启动等待状态
|
||||
- 登录成功后自动记住 `preferredMiniLoginShopId`
|
||||
- `WeChatProgram/utils/navigation.js`
|
||||
- `ensureLogin` 会等待启动期微信自动登录结束,再决定是否跳转登录页
|
||||
- `WeChatProgram/utils/auth.js`
|
||||
- 新增 `preferredMiniLoginShopId` 的读写方法
|
||||
- `WeChatProgram/api/auth.js`
|
||||
- 新增三条微信小程序登录接口调用
|
||||
- `WeChatProgram/pages/auth/index.*`
|
||||
- 登录页新增“微信手机号一键登录”主入口
|
||||
- 新增独立门店选择弹层,不复用注册表单
|
||||
- 支持继续完成上一次 `SELECT_SHOP` 的登录流程
|
||||
- DevTools / 不支持环境下按钮置为不可用提示,传统登录仍可使用
|
||||
|
||||
## SQL 变更
|
||||
|
||||
### 初始化 SQL
|
||||
|
||||
- 已同步写入:
|
||||
- `YumiNail-Core/src/main/resources/files/YumiNail.sql`
|
||||
- 新增表:
|
||||
- `t_wechat_mini_binding`
|
||||
- 约束:
|
||||
- `uk_wechat_mini_app_openid (app_id, openid)`
|
||||
- `uk_wechat_mini_app_user (app_id, user_id)`
|
||||
- `idx_wechat_mini_unionid (unionid)`
|
||||
|
||||
### 增量 SQL
|
||||
|
||||
- 文件:
|
||||
- `YumiNail-Core/src/main/resources/files/2026-04-02_wechat_mini_binding_patch.sql`
|
||||
|
||||
### 推荐执行顺序
|
||||
|
||||
1. `YumiNail-Core/src/main/resources/files/YumiNail.sql`
|
||||
2. 如果目标库是历史库,再执行 `YumiNail-Core/src/main/resources/files/2026-04-02_wechat_mini_binding_patch.sql`
|
||||
|
||||
说明:
|
||||
|
||||
- 空库首次部署时,直接执行最新 `YumiNail.sql` 即可
|
||||
- 已部署过旧版本的库,需要补执行本次增量 SQL
|
||||
|
||||
## 白名单同步点
|
||||
|
||||
以下位置都已同步加入微信小程序登录白名单:
|
||||
|
||||
- `YumiNail-Gateway/src/main/java/com/xiaowang/yumitailgateway/filter/AuthGlobalFilter.java`
|
||||
- `YumiNail-Gateway/src/main/resources/application.yaml`
|
||||
- `YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/config/WebMvcConfig.java`
|
||||
- `WeChatProgram/utils/request.js`
|
||||
- `YumiNail-Core/src/main/resources/API.md`
|
||||
- `docs/architecture/项目架构分析.md`
|
||||
|
||||
仍需你在 Nacos `YumiNail-Dev` 命名空间中同步确认 whitelist 包含:
|
||||
|
||||
- `/api/user/wechat-mini/**`
|
||||
- `/api/user/check/**`
|
||||
|
||||
## Nacos 新配置项
|
||||
|
||||
通过 `YumiNail-Dev` 命名空间维护:
|
||||
|
||||
```yaml
|
||||
yuminail:
|
||||
wechat:
|
||||
mini:
|
||||
app-id: wx1234567890abcdef
|
||||
app-secret: your-mini-program-secret
|
||||
code2session-url: https://api.weixin.qq.com/sns/jscode2session
|
||||
phone-number-url: https://api.weixin.qq.com/wxa/business/getuserphonenumber
|
||||
access-token-buffer-seconds: 60
|
||||
```
|
||||
|
||||
## 验证情况
|
||||
|
||||
- `YumiNail-Core` 已执行 `mvn -q -DskipTests compile`,通过
|
||||
- 小程序关键脚本已执行语法检查,以下文件通过:
|
||||
- `WeChatProgram/app.js`
|
||||
- `WeChatProgram/utils/navigation.js`
|
||||
- `WeChatProgram/pages/auth/index.js`
|
||||
|
||||
## 说明
|
||||
|
||||
- 本轮只接入用户端小程序微信登录,不改后台管理员登录
|
||||
- 若微信 `openid` 已绑定用户与手机号命中用户不一致,服务端会直接拒绝,避免错误合并账号
|
||||
- 若用户被停用,微信自动登录和微信手机号一键登录都会返回“账号已停用”
|
||||
Reference in New Issue
Block a user