优化小程序手机号与微信授权登录

This commit is contained in:
2026-09-11 15:27:20 +08:00
parent 8d84cb25d4
commit 8c5170cb7e
8 changed files with 121 additions and 29 deletions
@@ -155,25 +155,12 @@ public class WechatMiniAuthServiceImpl implements WechatMiniAuthService {
UserDO phoneUser = findActiveUserByPhone(phone);
if (phoneUser != null) {
/**
* Run business method `assertUserAvailable`.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
* @param phoneUser parameter `phoneUser` supplied by the caller
* @return result consumed by the caller or returned to the frontend
*/
assertUserAvailable(phoneUser);
if (userShopBindingSupport.listActiveShopIdsByUserId(phoneUser.getId()).isEmpty()) {
return WechatMiniLoginResultVO.registrationRequired(userService.phoneLoginByVerifiedPhone(phone));
}
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)
);
return WechatMiniLoginResultVO.registrationRequired(userService.phoneLoginByVerifiedPhone(phone));
}
@Override
@@ -65,6 +65,14 @@ public class WechatMiniLoginResultVO {
*/
private Boolean needSetPassword;
private Boolean registrationRequired;
private String registrationTicket;
private String phone;
private String registrationReason;
private String registrationStatus;
private String registrationRejectReason;
private Long registrationApplicationId;
/**
* Purpose: success supports WechatMiniLoginResultVO.java by holding or executing the success business role.
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
@@ -81,6 +89,20 @@ public class WechatMiniLoginResultVO {
return resultVO;
}
public static WechatMiniLoginResultVO registrationRequired(LoginResponseVO loginResponse) {
WechatMiniLoginResultVO resultVO = new WechatMiniLoginResultVO();
resultVO.setStatus(STATUS_NEED_MANUAL_LOGIN);
resultVO.setMessage("手机号尚未绑定店铺,请先完成身份注册");
resultVO.setRegistrationRequired(true);
resultVO.setRegistrationTicket(loginResponse.getRegistrationTicket());
resultVO.setPhone(loginResponse.getPhone());
resultVO.setRegistrationReason(loginResponse.getRegistrationReason());
resultVO.setRegistrationStatus(loginResponse.getRegistrationStatus());
resultVO.setRegistrationRejectReason(loginResponse.getRegistrationRejectReason());
resultVO.setRegistrationApplicationId(loginResponse.getRegistrationApplicationId());
return resultVO;
}
public static WechatMiniLoginResultVO selectShop(
String message,
String ticket,
@@ -91,8 +91,13 @@ public class WorkbenchRegistrationServiceImpl implements WorkbenchRegistrationSe
} else {
require(existing == null, "该手机号已注册,请直接登录或查看审核状态");
}
require(StringUtils.hasText(request.getPassword()), "密码不能为空");
require(request.getPassword().equals(request.getConfirmPassword()), "两次密码不一致");
boolean passwordProvided = StringUtils.hasText(request.getPassword()) || StringUtils.hasText(request.getConfirmPassword());
if (ticket == null) {
require(passwordProvided, "密码不能为空");
}
if (passwordProvided) {
require(request.getPassword().equals(request.getConfirmPassword()), "两次密码不一致");
}
ShopDO shop = null;
if (WorkbenchRegistrationRole.MANAGER.equals(roleType)) {
@@ -115,7 +120,7 @@ public class WorkbenchRegistrationServiceImpl implements WorkbenchRegistrationSe
user.setShopId(shop.getId());
user.setNickname((WorkbenchRegistrationRole.MANAGER.equals(roleType) ? shop.getShopName() + "店长" : "Salon店员"));
user.setAccount(phone);
user.setPassword(passwordEncoder.encode(request.getPassword()));
user.setPassword(passwordProvided ? passwordEncoder.encode(request.getPassword()) : "$2a$10$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW");
user.setPhone(phone);
user.setContactPhone(phone);
user.setPhoneVerified(1);
@@ -106,6 +106,8 @@ public interface UserService extends IService<UserDO> {
*/
LoginResponseVO phoneLogin(PhoneLoginRequestDTO phoneLoginRequestDTO);
LoginResponseVO phoneLoginByVerifiedPhone(String phone);
/**
* Run the login flow.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
@@ -1074,23 +1074,34 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
throw new RuntimeException("验证码错误或已过期");
}
return phoneLoginByVerifiedPhone(phoneLoginRequestDTO.getPhone(), phoneLoginRequestDTO.getShopId(), Boolean.TRUE.equals(phoneLoginRequestDTO.getRememberMe()));
}
@Override
public LoginResponseVO phoneLoginByVerifiedPhone(String phone) {
return phoneLoginByVerifiedPhone(phone, null, false);
}
private LoginResponseVO phoneLoginByVerifiedPhone(String phone, Long shopId, boolean rememberMe) {
String normalizedPhone = validateUserPhone(phone, null, true);
UserDO userDO = userMapper.selectOne(
Wrappers.lambdaQuery(UserDO.class)
.eq(UserDO::getPhone, phoneLoginRequestDTO.getPhone())
.eq(UserDO::getPhone, normalizedPhone)
.eq(UserDO::getIsDelete, 0)
);
if (userDO == null) {
return buildRegistrationRequiredResponse(phoneLoginRequestDTO.getPhone(), null, "PHONE_NOT_REGISTERED");
return buildRegistrationRequiredResponse(normalizedPhone, null, "PHONE_NOT_REGISTERED");
}
if (userShopBindingSupport.listActiveShopIdsByUserId(userDO.getId()).isEmpty()) {
return buildRegistrationRequiredResponse(phoneLoginRequestDTO.getPhone(), userDO, "NO_SHOP_BINDING");
return buildRegistrationRequiredResponse(normalizedPhone, userDO, "NO_SHOP_BINDING");
}
assertUserAvailable(userDO);
clearLoginFailureCount(userDO.getAccount());
Long resolvedShopId = resolveUserLoginShopId(userDO, phoneLoginRequestDTO.getShopId());
return buildLoginResponse(userDO, resolvedShopId, ENCODED_UNSET_PASSWORD.equals(userDO.getPassword()), Boolean.TRUE.equals(phoneLoginRequestDTO.getRememberMe()));
Long resolvedShopId = resolveUserLoginShopId(userDO, shopId);
return buildLoginResponse(userDO, resolvedShopId, ENCODED_UNSET_PASSWORD.equals(userDO.getPassword()), rememberMe);
}
private LoginResponseVO buildRegistrationRequiredResponse(String phone, UserDO userDO, String reason) {
+18
View File
@@ -99,6 +99,24 @@ module.exports = {
})
},
wechatPhoneLogin(data) {
return request({
url: '/user/wechat-mini/phone-login',
method: 'POST',
params: { __baseUrl: API_DOMAIN },
data
})
},
wechatConfirmLogin(data) {
return request({
url: '/user/wechat-mini/confirm-login',
method: 'POST',
params: { __baseUrl: API_DOMAIN },
data
})
},
getPhoneLoginShops(phone) {
return request({
url: `/user/check/login-shops/phone/${encodeURIComponent(phone)}`,
+48 -1
View File
@@ -101,7 +101,8 @@ Page({
shopSelectVisible: false,
shopSelectMode: '',
shopOptions: [],
switchingShop: false
switchingShop: false,
wechatLoginTicket: ''
},
onLoad() {
@@ -291,6 +292,7 @@ Page({
const query = [
`registrationTicket=${encodeURIComponent(ticket)}`,
`phone=${encodeURIComponent(data.phone || this.data.form.phone || '')}`,
data.wxCode ? `wxCode=${encodeURIComponent(data.wxCode)}` : '',
data.registrationApplicationId ? `applicationId=${encodeURIComponent(data.registrationApplicationId)}` : ''
].filter(Boolean).join('&')
setTimeout(() => wx.navigateTo({ url: `/pages/register/index?${query}` }), 700)
@@ -382,6 +384,8 @@ Page({
try {
if (this.data.shopSelectMode === 'login') {
await this.loginWithSelectedShop(shopId)
} else if (this.data.shopSelectMode === 'wechat') {
await this.loginWithWechatSelectedShop(shopId)
} else {
await this.switchSelectedShop(shopId)
}
@@ -409,6 +413,16 @@ Page({
wx.reLaunch({ url: '/pages/planning/index' })
},
async loginWithWechatSelectedShop(shopId) {
const result = await authApi.wechatConfirmLogin({ ticket: this.data.wechatLoginTicket, shopId, ...this.buildAgreementPayload() })
if (result.status !== 'SUCCESS' || !result.accessToken) {
throw new Error(result.message || '进入店铺失败')
}
getApp().setSession(result)
this.closeShopSelector()
wx.reLaunch({ url: '/pages/planning/index' })
},
startCountdown() {
if (this.data.countdownTimer) {
clearInterval(this.data.countdownTimer)
@@ -531,5 +545,38 @@ Page({
} catch (error) {
wx.showToast({ title: error.message || '微信快捷登录失败', icon: 'none' })
}
},
async wechatPhoneLogin(event) {
if (this.data.loading || !this.ensureAgreementAccepted()) {
return
}
const phoneCode = event && event.detail && event.detail.code
if (!phoneCode) {
wx.showToast({ title: '需要授权手机号后才能登录', icon: 'none' })
return
}
this.setData({ loading: true })
try {
const wxCode = await this.getWechatCode()
const result = await authApi.wechatPhoneLogin({ wxCode, phoneCode, ...this.buildAgreementPayload() })
if (result.registrationRequired) {
this.openRegistrationFlow({ ...result, wxCode })
return
}
if (result.status === 'SELECT_SHOP') {
this.setData({ shopOptions: buildShopOptionsFromSelection(result), shopSelectVisible: true, shopSelectMode: 'wechat', wechatLoginTicket: result.ticket, switchingShop: false })
return
}
if (result.status !== 'SUCCESS' || !result.accessToken) {
throw new Error(result.message || '微信手机号登录暂不可用')
}
getApp().setSession(result)
wx.reLaunch({ url: '/pages/planning/index' })
} catch (error) {
wx.showToast({ title: error.message || '微信手机号登录失败', icon: 'none' })
} finally {
this.setData({ loading: false })
}
}
})
+3 -3
View File
@@ -23,12 +23,12 @@
</view>
<view wx:if="{{loginMode === 'phone'}}" class="field">
<text class="field-label">手机号</text>
<input value="{{form.phone}}" data-field="phone" bindinput="onInput" type="number" placeholder="请输入手机号" />
<input value="{{form.phone}}" data-field="phone" bindinput="onInput" type="text" maxlength="11" placeholder="请输入手机号" />
</view>
<view wx:if="{{loginMode === 'phone'}}" class="field">
<text class="field-label">验证码</text>
<view class="code-row">
<input class="code-input" value="{{form.code}}" data-field="code" bindinput="onInput" type="number" placeholder="请输入验证码" />
<input class="code-input" value="{{form.code}}" data-field="code" bindinput="onInput" type="text" maxlength="6" placeholder="请输入验证码" />
<button class="code-btn {{countdown > 0 ? 'counting' : ''}}" loading="{{codeLoading}}" disabled="{{codeLoading || countdown > 0}}" bindtap="sendLoginCode">
<text wx:if="{{countdown > 0}}">重新获取 {{countdown}}s</text>
<text wx:else>获取验证码</text>
@@ -56,7 +56,7 @@
</view>
</view>
<button class="secondary-btn wechat-btn" bindtap="wechatLogin">微信快捷登录</button>
<button class="secondary-btn wechat-btn" open-type="getPhoneNumber" bindgetphonenumber="wechatPhoneLogin">微信手机号一键登录</button>
<view wx:if="{{shopSelectVisible}}" class="shop-select-mask">
<view class="shop-select-dialog">