功能:新增微信小程序一键登录
This commit is contained in:
@@ -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');
|
||||
|
||||
Reference in New Issue
Block a user