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

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