diff --git a/JY-Artist-Frontend/src/api/auth.ts b/JY-Artist-Frontend/src/api/auth.ts index 9fe657a0..df4f8990 100644 --- a/JY-Artist-Frontend/src/api/auth.ts +++ b/JY-Artist-Frontend/src/api/auth.ts @@ -12,6 +12,7 @@ import type { IdType } from '@/utils/id' export interface SendVerificationCodeRequest { phone: string sceneCode?: string + clientType?: string } /** diff --git a/JY-Artist-Frontend/src/api/user.ts b/JY-Artist-Frontend/src/api/user.ts index 4c6fc5df..ef164eb0 100644 --- a/JY-Artist-Frontend/src/api/user.ts +++ b/JY-Artist-Frontend/src/api/user.ts @@ -385,7 +385,7 @@ export const userApi = { * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. * @param data: { phone: string; sceneCode?: string } caller-supplied value for `data: { phone: string; sceneCode?: string }` */ - sendVerificationCode: (data: { phone: string; sceneCode?: string }) => { + sendVerificationCode: (data: { phone: string; sceneCode?: string; clientType?: string }) => { return api.post('/user/send-verification-code', data) }, /** diff --git a/JY-Artist-Frontend/src/views/AccountSettingsView.vue b/JY-Artist-Frontend/src/views/AccountSettingsView.vue index a9de8b7c..c5f14f39 100644 --- a/JY-Artist-Frontend/src/views/AccountSettingsView.vue +++ b/JY-Artist-Frontend/src/views/AccountSettingsView.vue @@ -501,7 +501,8 @@ const handleSendVerificationCode = async () => { try { await runWithGlobalLoading(() => userApi.sendVerificationCode({ phone: bindPhoneForm.phone, - sceneCode: 'USER_BIND_PHONE_SMS_CODE' + sceneCode: 'USER_BIND_PHONE_SMS_CODE', + clientType: 'WEB' })) message.success('验证码发送成功') startCountdown() @@ -528,7 +529,8 @@ const handleSendChangePhoneVerificationCode = async () => { try { await runWithGlobalLoading(() => userApi.sendVerificationCode({ phone: changePhoneForm.newPhone, - sceneCode: 'USER_CHANGE_PHONE_SMS_CODE' + sceneCode: 'USER_CHANGE_PHONE_SMS_CODE', + clientType: 'WEB' })) message.success('验证码发送成功') startCountdown() @@ -556,7 +558,8 @@ const handleSendChangePasswordVerificationCode = async () => { try { await runWithGlobalLoading(() => userApi.sendVerificationCode({ phone, - sceneCode: 'USER_CHANGE_PASSWORD_SMS_CODE' + sceneCode: 'USER_CHANGE_PASSWORD_SMS_CODE', + clientType: 'WEB' })) message.success('验证码发送成功') startCountdown() diff --git a/JY-Artist-Frontend/src/views/AuthView.vue b/JY-Artist-Frontend/src/views/AuthView.vue index 57716eac..dbae5ca3 100644 --- a/JY-Artist-Frontend/src/views/AuthView.vue +++ b/JY-Artist-Frontend/src/views/AuthView.vue @@ -1112,7 +1112,8 @@ const handleSendForgotCode = async () => { try { await runWithGlobalLoading(() => authApi.sendVerificationCode({ phone: forgotPasswordForm.phone, - sceneCode: 'USER_RESET_PASSWORD_SMS_CODE' + sceneCode: 'USER_RESET_PASSWORD_SMS_CODE', + clientType: 'WEB' })) message.success('验证码已发送') forgotCountdown.value = 60 @@ -1204,7 +1205,8 @@ const handleSendVerificationCode = async () => { await runWithGlobalLoading(() => userApi.sendVerificationCode({ phone: formData.phone, - sceneCode: activeTab.value === 'register' ? 'USER_REGISTER_SMS_CODE' : 'USER_LOGIN_SMS_CODE' + sceneCode: activeTab.value === 'register' ? 'USER_REGISTER_SMS_CODE' : 'USER_LOGIN_SMS_CODE', + clientType: 'WEB' })) message.success('验证码已发送') countdown.value = 60 diff --git a/JY-Artist-Frontend/src/views/PasswordSettingsView.vue b/JY-Artist-Frontend/src/views/PasswordSettingsView.vue index 82d3c055..b12ee720 100644 --- a/JY-Artist-Frontend/src/views/PasswordSettingsView.vue +++ b/JY-Artist-Frontend/src/views/PasswordSettingsView.vue @@ -239,7 +239,8 @@ const handleSendVerificationCode = async () => { try { await runWithGlobalLoading(() => userApi.sendVerificationCode({ phone: userPhone.value, - sceneCode: 'USER_CHANGE_PASSWORD_SMS_CODE' + sceneCode: 'USER_CHANGE_PASSWORD_SMS_CODE', + clientType: 'WEB' })) message.success('验证码发送成功') startCountdown() diff --git a/JY-Artist-WeChat/pages/auth/index.js b/JY-Artist-WeChat/pages/auth/index.js index a990822e..f74ecc70 100644 --- a/JY-Artist-WeChat/pages/auth/index.js +++ b/JY-Artist-WeChat/pages/auth/index.js @@ -847,7 +847,8 @@ Page({ try { await runWithLoading(() => userApi.sendVerificationCode({ phone, - sceneCode: this.data.activeTab === 'register' ? 'USER_REGISTER_SMS_CODE' : 'USER_LOGIN_SMS_CODE' + sceneCode: this.data.activeTab === 'register' ? 'USER_REGISTER_SMS_CODE' : 'USER_LOGIN_SMS_CODE', + clientType: 'WECHAT_MINI' })) wx.showToast({ title: '验证码已发送', @@ -883,7 +884,8 @@ Page({ try { await runWithLoading(() => authApi.sendVerificationCode({ phone, - sceneCode: 'USER_RESET_PASSWORD_SMS_CODE' + sceneCode: 'USER_RESET_PASSWORD_SMS_CODE', + clientType: 'WECHAT_MINI' })) wx.showToast({ title: '验证码已发送', diff --git a/JY-Artist-WeChat/pages/password-settings/index.js b/JY-Artist-WeChat/pages/password-settings/index.js index e734ef81..94c56b24 100644 --- a/JY-Artist-WeChat/pages/password-settings/index.js +++ b/JY-Artist-WeChat/pages/password-settings/index.js @@ -62,7 +62,8 @@ Page({ try { await runWithLoading(() => userApi.sendVerificationCode({ phone, - sceneCode: 'USER_CHANGE_PASSWORD_SMS_CODE' + sceneCode: 'USER_CHANGE_PASSWORD_SMS_CODE', + clientType: 'WECHAT_MINI' })) wx.showToast({ title: '验证码已发送', icon: 'none' }) } catch (error) { diff --git a/JY-Artist-WeChat/pages/settings/index.js b/JY-Artist-WeChat/pages/settings/index.js index e45ff60f..a6ad8a90 100644 --- a/JY-Artist-WeChat/pages/settings/index.js +++ b/JY-Artist-WeChat/pages/settings/index.js @@ -636,7 +636,8 @@ Page({ try { await runWithLoading(() => userApi.sendVerificationCode({ phone, - sceneCode: 'USER_BIND_PHONE_SMS_CODE' + sceneCode: 'USER_BIND_PHONE_SMS_CODE', + clientType: 'WECHAT_MINI' })) wx.showToast({ title: '验证码已发送', @@ -724,7 +725,8 @@ Page({ try { await runWithLoading(() => userApi.sendVerificationCode({ phone: newPhone, - sceneCode: 'USER_CHANGE_PHONE_SMS_CODE' + sceneCode: 'USER_CHANGE_PHONE_SMS_CODE', + clientType: 'WECHAT_MINI' })) wx.showToast({ title: '验证码已发送', @@ -832,7 +834,8 @@ Page({ try { await runWithLoading(() => authApi.sendVerificationCode({ phone, - sceneCode: 'USER_CHANGE_PASSWORD_SMS_CODE' + sceneCode: 'USER_CHANGE_PASSWORD_SMS_CODE', + clientType: 'WECHAT_MINI' })) wx.showToast({ title: '验证码已发送', diff --git a/JY-Core/src/main/java/com/xiaowang/jayucloud/core/config/MessageHubSmsProperties.java b/JY-Core/src/main/java/com/xiaowang/jayucloud/core/config/MessageHubSmsProperties.java new file mode 100644 index 00000000..0b9c37e5 --- /dev/null +++ b/JY-Core/src/main/java/com/xiaowang/jayucloud/core/config/MessageHubSmsProperties.java @@ -0,0 +1,58 @@ +package com.xiaowang.jayucloud.core.config; + +import lombok.Data; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.cloud.context.config.annotation.RefreshScope; +import org.springframework.context.annotation.Configuration; + +import java.util.HashMap; +import java.util.Map; + +@Data +@Configuration +@RefreshScope +@ConfigurationProperties(prefix = "messagehub.sms") +public class MessageHubSmsProperties { + + private String defaultChannel; + + private String validMinutesText; + + private ClientProperties clients = new ClientProperties(); + + private ChannelProperties channels = new ChannelProperties(); + + @Data + public static class ClientProperties { + + private SourceSystemProperties designer = new SourceSystemProperties(); + + private SourceSystemProperties salon = new SourceSystemProperties(); + } + + @Data + public static class SourceSystemProperties { + + private String sourceSystem; + + private String accessToken; + } + + @Data + public static class ChannelProperties { + + private ChannelDetailProperties aliyun = new ChannelDetailProperties(); + + private ChannelDetailProperties spug = new ChannelDetailProperties(); + } + + @Data + public static class ChannelDetailProperties { + + private Long channelId; + + private String sendMethod; + + private Map templates = new HashMap<>(); + } +} diff --git a/JY-Core/src/main/java/com/xiaowang/jayucloud/core/modules/auth/dto/SendVerificationCodeRequestDTO.java b/JY-Core/src/main/java/com/xiaowang/jayucloud/core/modules/auth/dto/SendVerificationCodeRequestDTO.java index eb2236d5..6295bf01 100644 --- a/JY-Core/src/main/java/com/xiaowang/jayucloud/core/modules/auth/dto/SendVerificationCodeRequestDTO.java +++ b/JY-Core/src/main/java/com/xiaowang/jayucloud/core/modules/auth/dto/SendVerificationCodeRequestDTO.java @@ -22,4 +22,9 @@ public class SendVerificationCodeRequestDTO { * 业务场景编码,用来选择 JayuCloud 投递 MessageHub 时的配置。 */ private String sceneCode; + + /** + * 客户端类型,用于选择设计师或店务 MessageHub 身份。 + */ + private String clientType; } diff --git a/JY-Core/src/main/java/com/xiaowang/jayucloud/core/modules/auth/service/VerificationCodeService.java b/JY-Core/src/main/java/com/xiaowang/jayucloud/core/modules/auth/service/VerificationCodeService.java index 8fa3e5a7..c7543c03 100644 --- a/JY-Core/src/main/java/com/xiaowang/jayucloud/core/modules/auth/service/VerificationCodeService.java +++ b/JY-Core/src/main/java/com/xiaowang/jayucloud/core/modules/auth/service/VerificationCodeService.java @@ -32,6 +32,8 @@ public interface VerificationCodeService { */ void sendVerificationCode(String phone, String sceneCode); + void sendVerificationCode(String phone, String sceneCode, String clientType); + /** * Run business method `verifyCode`. * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. diff --git a/JY-Core/src/main/java/com/xiaowang/jayucloud/core/modules/auth/service/impl/VerificationCodeServiceImpl.java b/JY-Core/src/main/java/com/xiaowang/jayucloud/core/modules/auth/service/impl/VerificationCodeServiceImpl.java index bb0cbc45..62b5dd15 100644 --- a/JY-Core/src/main/java/com/xiaowang/jayucloud/core/modules/auth/service/impl/VerificationCodeServiceImpl.java +++ b/JY-Core/src/main/java/com/xiaowang/jayucloud/core/modules/auth/service/impl/VerificationCodeServiceImpl.java @@ -1,16 +1,23 @@ package com.xiaowang.jayucloud.core.modules.auth.service.impl; -import com.xiaowang.jayucloud.core.modules.integration.service.MessageHubClientService; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.xiaowang.jayucloud.core.common.BusinessException; import com.xiaowang.jayucloud.core.modules.auth.service.VerificationCodeService; +import com.xiaowang.jayucloud.core.modules.integration.service.MessageHubClientService; +import com.xiaowang.jayucloud.core.modules.integration.support.MessageHubSmsChannel; +import com.xiaowang.jayucloud.core.modules.integration.support.MessageHubSmsClientGroup; +import com.xiaowang.jayucloud.core.modules.integration.vo.MessageHubSmsSendResult; +import com.xiaowang.jayucloud.core.modules.integration.vo.MessageHubSmsStatusVO; +import lombok.Data; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.stereotype.Service; +import org.springframework.util.StringUtils; import java.security.SecureRandom; import java.time.Duration; -import com.xiaowang.jayucloud.core.common.Result; /** * 验证码服务实现。 */ @@ -19,46 +26,18 @@ import com.xiaowang.jayucloud.core.common.Result; @RequiredArgsConstructor public class VerificationCodeServiceImpl implements VerificationCodeService { - /** - * Purpose: CODE_PREFIX supports VerificationCodeServiceImpl.java by holding or executing the code prefix business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ private static final String CODE_PREFIX = "verification:code:"; - /** - * Purpose: SEND_TIME_PREFIX supports VerificationCodeServiceImpl.java by holding or executing the send time prefix business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ private static final String SEND_TIME_PREFIX = "verification:send_time:"; - /** - * Purpose: CODE_LENGTH supports VerificationCodeServiceImpl.java by holding or executing the code length business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ + private static final String LAST_MESSAGE_PREFIX = "verification:last_message:"; private static final int CODE_LENGTH = 6; - /** - * Purpose: CODE_EXPIRE_MINUTES supports VerificationCodeServiceImpl.java by holding or executing the code expire minutes business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ private static final int CODE_EXPIRE_MINUTES = 5; - /** - * Purpose: RESEND_INTERVAL_SECONDS supports VerificationCodeServiceImpl.java by holding or executing the resend interval seconds business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ private static final int RESEND_INTERVAL_SECONDS = 60; - /** - * Variable `redisTemplate`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ + private final StringRedisTemplate redisTemplate; - /** - * Variable `messageHubClientService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. - */ private final MessageHubClientService messageHubClientService; + private final ObjectMapper objectMapper; @Override - /** - * Run business method `generateVerificationCode`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return String result consumed by the caller or returned to the frontend - */ public String generateVerificationCode() { SecureRandom random = new SecureRandom(); StringBuilder code = new StringBuilder(); @@ -69,51 +48,48 @@ public class VerificationCodeServiceImpl implements VerificationCodeService { } @Override - /** - * Send or dispatch a message. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param phone parameter `phone` supplied by the caller - */ public void sendVerificationCode(String phone) { - /** - * Send or dispatch a message. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param phone parameter `phone` supplied by the caller - * @param USER_LOGIN_SMS_CODE parameter `USER_LOGIN_SMS_CODE` supplied by the caller - * @return result consumed by the caller or returned to the frontend - */ - sendVerificationCode(phone, "USER_LOGIN_SMS_CODE"); + sendVerificationCode(phone, "USER_LOGIN_SMS_CODE", null); } @Override - /** - * Send or dispatch a message. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param phone parameter `phone` supplied by the caller - * @param sceneCode parameter `sceneCode` supplied by the caller - */ public void sendVerificationCode(String phone, String sceneCode) { - String code = generateVerificationCode(); + sendVerificationCode(phone, sceneCode, null); + } + @Override + public void sendVerificationCode(String phone, String sceneCode, String clientType) { + String normalizedSceneCode = StringUtils.hasText(sceneCode) ? sceneCode.trim() : "USER_LOGIN_SMS_CODE"; + MessageHubSmsClientGroup clientGroup = MessageHubSmsClientGroup.resolve(clientType, normalizedSceneCode); + MessageHubSmsChannel nextChannel = resolveNextChannel(phone, clientGroup); + String code = generateVerificationCode(); String codeKey = CODE_PREFIX + phone; String sendTimeKey = SEND_TIME_PREFIX + phone; + String lastMessageKey = LAST_MESSAGE_PREFIX + phone; - redisTemplate.opsForValue().set(codeKey, code, Duration.ofMinutes(CODE_EXPIRE_MINUTES)); - redisTemplate.opsForValue().set(sendTimeKey, String.valueOf(System.currentTimeMillis()), - Duration.ofSeconds(RESEND_INTERVAL_SECONDS)); - - messageHubClientService.sendSmsVerificationCode(sceneCode, phone, code); - log.info("验证码已发送,手机号: {}, sceneCode: {}", phone, sceneCode); + redisTemplate.delete(codeKey); + try { + MessageHubSmsSendResult sendResult = messageHubClientService.sendSmsVerificationCode( + normalizedSceneCode, + phone, + code, + clientType, + nextChannel + ); + redisTemplate.opsForValue().set(codeKey, code, Duration.ofMinutes(CODE_EXPIRE_MINUTES)); + redisTemplate.opsForValue().set(sendTimeKey, String.valueOf(System.currentTimeMillis()), + Duration.ofSeconds(RESEND_INTERVAL_SECONDS)); + redisTemplate.opsForValue().set(lastMessageKey, toJson(toLastMessage(sendResult)), + Duration.ofMinutes(CODE_EXPIRE_MINUTES)); + log.info("验证码已发送,phone: {}, sceneCode: {}, clientGroup: {}, channelCode: {}, messageId: {}", + phone, normalizedSceneCode, clientGroup.name(), sendResult.getChannelCode(), sendResult.getMessageId()); + } catch (Exception exception) { + redisTemplate.delete(codeKey); + throw exception; + } } @Override - /** - * Run business method `verifyCode`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param phone parameter `phone` supplied by the caller - * @param code parameter `code` supplied by the caller - * @return boolean result consumed by the caller or returned to the frontend - */ public boolean verifyCode(String phone, String code) { String codeKey = CODE_PREFIX + phone; String storedCode = redisTemplate.opsForValue().get(codeKey); @@ -129,20 +105,91 @@ public class VerificationCodeServiceImpl implements VerificationCodeService { } redisTemplate.delete(codeKey); + redisTemplate.delete(LAST_MESSAGE_PREFIX + phone); log.info("验证码验证成功,手机号: {}", phone); return true; } @Override - /** - * Run business method `canResend`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param phone parameter `phone` supplied by the caller - * @return boolean result consumed by the caller or returned to the frontend - */ public boolean canResend(String phone) { String sendTimeKey = SEND_TIME_PREFIX + phone; String sendTime = redisTemplate.opsForValue().get(sendTimeKey); return sendTime == null; } + + private MessageHubSmsChannel resolveNextChannel(String phone, MessageHubSmsClientGroup currentClientGroup) { + LastMessage lastMessage = readLastMessage(phone); + if (lastMessage == null || !StringUtils.hasText(lastMessage.getMessageId())) { + return messageHubClientService.defaultSmsChannel(); + } + MessageHubSmsClientGroup lastClientGroup = MessageHubSmsClientGroup.valueOf(lastMessage.getClientGroup()); + MessageHubSmsStatusVO status = messageHubClientService.querySmsStatus( + lastMessage.getMessageId(), + lastClientGroup, + lastMessage.getSourceSystem() + ); + MessageHubSmsChannel lastChannel = MessageHubSmsChannel.fromCode( + lastMessage.getChannelCode(), + messageHubClientService.defaultSmsChannel() + ); + if (status.isSuccess()) { + return lastChannel; + } + return lastChannel.opposite(); + } + + private LastMessage readLastMessage(String phone) { + String raw = redisTemplate.opsForValue().get(LAST_MESSAGE_PREFIX + phone); + if (!StringUtils.hasText(raw)) { + return null; + } + try { + LastMessage lastMessage = objectMapper.readValue(raw, LastMessage.class); + if (!StringUtils.hasText(lastMessage.getClientGroup())) { + throw new BusinessException("上一条短信元数据缺少 clientGroup"); + } + return lastMessage; + } catch (BusinessException exception) { + throw exception; + } catch (Exception exception) { + throw new BusinessException("上一条短信元数据解析失败:phone=" + phone + ", reason=" + exception.getMessage(), exception); + } + } + + private LastMessage toLastMessage(MessageHubSmsSendResult sendResult) { + LastMessage lastMessage = new LastMessage(); + lastMessage.setMessageId(sendResult.getMessageId()); + lastMessage.setUniqueId(sendResult.getUniqueId()); + lastMessage.setSourceSystem(sendResult.getSourceSystem()); + lastMessage.setChannelCode(sendResult.getChannelCode()); + lastMessage.setClientGroup(sendResult.getClientGroup()); + lastMessage.setSceneCode(sendResult.getSceneCode()); + return lastMessage; + } + + private String toJson(LastMessage lastMessage) { + try { + return objectMapper.writeValueAsString(lastMessage); + } catch (Exception exception) { + throw new BusinessException("上一条短信元数据序列化失败:messageId=" + + lastMessage.getMessageId() + + ", reason=" + exception.getMessage(), exception); + } + } + + @Data + private static class LastMessage { + + private String messageId; + + private String uniqueId; + + private String sourceSystem; + + private String channelCode; + + private String clientGroup; + + private String sceneCode; + } } diff --git a/JY-Core/src/main/java/com/xiaowang/jayucloud/core/modules/integration/service/MessageHubClientService.java b/JY-Core/src/main/java/com/xiaowang/jayucloud/core/modules/integration/service/MessageHubClientService.java index 5184d477..20c1f51a 100644 --- a/JY-Core/src/main/java/com/xiaowang/jayucloud/core/modules/integration/service/MessageHubClientService.java +++ b/JY-Core/src/main/java/com/xiaowang/jayucloud/core/modules/integration/service/MessageHubClientService.java @@ -1,30 +1,28 @@ package com.xiaowang.jayucloud.core.modules.integration.service; +import com.xiaowang.jayucloud.core.modules.integration.support.MessageHubSmsChannel; +import com.xiaowang.jayucloud.core.modules.integration.support.MessageHubSmsClientGroup; +import com.xiaowang.jayucloud.core.modules.integration.vo.MessageHubSmsSendResult; +import com.xiaowang.jayucloud.core.modules.integration.vo.MessageHubSmsStatusVO; -import com.xiaowang.jayucloud.core.common.Result; /** - * MessageHub客户端服务接口 - * 用于调用MessageHub服务发送消息 - * - * @author xiaowang - * @date 2026-03-03 + * MessageHub 客户端服务接口。 */ public interface MessageHubClientService { - /** - * Send or dispatch a message. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param phone parameter `phone` supplied by the caller - * @param code parameter `code` supplied by the caller - */ - void sendSmsVerificationCode(String phone, String code); + MessageHubSmsSendResult sendSmsVerificationCode(String phone, String code); - /** - * Send or dispatch a message. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param sceneCode parameter `sceneCode` supplied by the caller - * @param phone parameter `phone` supplied by the caller - * @param code parameter `code` supplied by the caller - */ - void sendSmsVerificationCode(String sceneCode, String phone, String code); + MessageHubSmsSendResult sendSmsVerificationCode(String sceneCode, String phone, String code); + + MessageHubSmsSendResult sendSmsVerificationCode(String sceneCode, + String phone, + String code, + String clientType, + MessageHubSmsChannel channel); + + MessageHubSmsStatusVO querySmsStatus(String messageId, + MessageHubSmsClientGroup clientGroup, + String sourceSystem); + + MessageHubSmsChannel defaultSmsChannel(); } diff --git a/JY-Core/src/main/java/com/xiaowang/jayucloud/core/modules/integration/service/impl/MessageHubClientServiceImpl.java b/JY-Core/src/main/java/com/xiaowang/jayucloud/core/modules/integration/service/impl/MessageHubClientServiceImpl.java index 816481ce..ba7f013f 100644 --- a/JY-Core/src/main/java/com/xiaowang/jayucloud/core/modules/integration/service/impl/MessageHubClientServiceImpl.java +++ b/JY-Core/src/main/java/com/xiaowang/jayucloud/core/modules/integration/service/impl/MessageHubClientServiceImpl.java @@ -3,9 +3,14 @@ package com.xiaowang.jayucloud.core.modules.integration.service.impl; import com.fasterxml.jackson.databind.ObjectMapper; import com.xiaowang.jayucloud.core.common.BusinessException; import com.xiaowang.jayucloud.core.config.BrandProperties; +import com.xiaowang.jayucloud.core.config.MessageHubSmsProperties; import com.xiaowang.jayucloud.core.modules.integration.entity.MessageHubPushConfigDO; import com.xiaowang.jayucloud.core.modules.integration.service.MessageHubClientService; import com.xiaowang.jayucloud.core.modules.integration.service.MessageHubPushConfigService; +import com.xiaowang.jayucloud.core.modules.integration.support.MessageHubSmsChannel; +import com.xiaowang.jayucloud.core.modules.integration.support.MessageHubSmsClientGroup; +import com.xiaowang.jayucloud.core.modules.integration.vo.MessageHubSmsSendResult; +import com.xiaowang.jayucloud.core.modules.integration.vo.MessageHubSmsStatusVO; import com.xiaowang.jayucloud.core.support.id.TimeOrderedSnowflakeIdGenerator; import lombok.Data; import lombok.RequiredArgsConstructor; @@ -25,12 +30,14 @@ import org.springframework.web.client.RestClientResponseException; import org.springframework.web.client.RestTemplate; import org.springframework.web.util.UriComponentsBuilder; +import javax.annotation.PostConstruct; import java.util.HashMap; import java.util.List; +import java.util.Locale; import java.util.Map; /** - * JayuCloud 到 MessageHub 的投递客户端。 + * JayuCloud 到 MessageHub 的短信投递客户端。 */ @Slf4j @Service @@ -39,97 +46,172 @@ import java.util.Map; public class MessageHubClientServiceImpl implements MessageHubClientService { private static final String ACCESS_TOKEN_HEADER = "X-MessageHub-Access-Token"; - private static final int MAX_SUBMIT_ATTEMPTS = 3; + private static final int MAX_API_ATTEMPTS = 3; private static final int RESPONSE_BODY_LIMIT = 500; + private static final String DEFAULT_SCENE_CODE = "USER_LOGIN_SMS_CODE"; + private static final String DEFAULT_ALIYUN_TEMPLATE_CODE = "100001"; + private static final String DESIGNER_SPUG_TEMPLATE_CODE = "SPUG_SMS_VERIFY_1"; + private static final String SALON_SPUG_TEMPLATE_CODE = "SPUG_SMS_VERIFY_3"; private final ObjectMapper objectMapper; private final TimeOrderedSnowflakeIdGenerator snowflakeIdGenerator; private final MessageHubPushConfigService messageHubPushConfigService; private final RestTemplate restTemplate; private final BrandProperties brandProperties; + private final MessageHubSmsProperties smsProperties; @Value("${messagehub.client.base-url:}") private String baseUrl; @Value("${messagehub.client.source-system:jayucloud}") - private String sourceSystem; + private String legacySourceSystem; @Value("${messagehub.client.access-token:}") - private String accessToken; + private String legacyAccessToken; @Value("${messagehub.client.verify-template-code:100001}") - private String verifyTemplateCode; + private String legacyVerifyTemplateCode; - @Override - public void sendSmsVerificationCode(String phone, String code) { - sendSmsVerificationCode("USER_LOGIN_SMS_CODE", phone, code); - } - - @Override - public void sendSmsVerificationCode(String sceneCode, String phone, String code) { - try { - MessageHubPushConfigDO config = messageHubPushConfigService.getEnabledConfig(sceneCode); - String uniqueId = snowflakeIdGenerator.nextIdString(); - MessageHubSubmitRequest request = buildSmsMessageBody(config, sceneCode, phone, code, uniqueId); - MessageHubSubmitResponse response = submitMessage(request); - log.info("短信验证码消息已提交到 MessageHub,sceneCode: {}, phone: {}, sourceSystem: {}, templateCode: {}, uniqueId: {}, messageId: {}, dispatchStatus: {}, outboxStatus: {}", - sceneCode, phone, request.getSourceSystem(), request.getTemplateCode(), uniqueId, - response.getMessageId(), response.getDispatchStatus(), response.getOutboxStatus()); - } catch (Exception exception) { - log.error("发送短信验证码失败", exception); - throw new BusinessException("发送短信验证码失败: " + exception.getMessage(), exception); + @PostConstruct + public void validateStartupConfiguration() { + requireText(baseUrl, "MessageHub API 地址未配置:messagehub.client.base-url"); + MessageHubSmsChannel defaultChannel = MessageHubSmsChannel.fromCode(smsProperties.getDefaultChannel(), MessageHubSmsChannel.ALIYUN); + requireChannelConfig(defaultChannel); + requireChannelConfig(defaultChannel.opposite()); + requireSourceSystem(resolveClient(MessageHubSmsClientGroup.DESIGNER), "designer"); + requireSourceSystem(resolveClient(MessageHubSmsClientGroup.SALON), "salon"); + requireSpugDesignerName(); + if (!StringUtils.hasText(resolveValidMinutesText())) { + throw new BusinessException("MessageHub SPUG 短信有效分钟数未配置:messagehub.sms.valid-minutes-text"); } } - private MessageHubSubmitRequest buildSmsMessageBody(MessageHubPushConfigDO config, - String sceneCode, + @Override + public MessageHubSmsSendResult sendSmsVerificationCode(String phone, String code) { + return sendSmsVerificationCode(DEFAULT_SCENE_CODE, phone, code); + } + + @Override + public MessageHubSmsSendResult sendSmsVerificationCode(String sceneCode, String phone, String code) { + return sendSmsVerificationCode(sceneCode, phone, code, null, defaultSmsChannel()); + } + + @Override + public MessageHubSmsSendResult sendSmsVerificationCode(String sceneCode, + String phone, + String code, + String clientType, + MessageHubSmsChannel channel) { + MessageHubSmsClientGroup clientGroup = MessageHubSmsClientGroup.resolve(clientType, sceneCode); + MessageHubSmsChannel resolvedChannel = channel == null ? defaultSmsChannel() : channel; + try { + String uniqueId = snowflakeIdGenerator.nextIdString(); + MessageHubSubmitRequest request = buildSmsMessageBody(sceneCode, phone, code, uniqueId, clientGroup, resolvedChannel); + MessageHubSubmitResponse response = submitMessage(request, resolveClient(clientGroup).getAccessToken()); + MessageHubSmsSendResult result = toSendResult(response, request, clientGroup, resolvedChannel, sceneCode); + log.info("短信验证码已提交到 MessageHub,sceneCode: {}, phone: {}, sourceSystem: {}, templateCode: {}, channelCode: {}, uniqueId: {}, messageId: {}, dispatchStatus: {}, outboxStatus: {}", + sceneCode, phone, request.getSourceSystem(), request.getTemplateCode(), resolvedChannel.name(), uniqueId, + response.getMessageId(), response.getDispatchStatus(), response.getOutboxStatus()); + return result; + } catch (BusinessException exception) { + throw exception; + } catch (Exception exception) { + log.error("发送短信验证码失败", exception); + throw new BusinessException("发送短信验证码失败:sceneCode=" + sceneCode + + ", phone=" + phone + + ", clientGroup=" + clientGroup.name() + + ", channelCode=" + resolvedChannel.name() + + ", reason=" + exception.getMessage(), exception); + } + } + + @Override + public MessageHubSmsStatusVO querySmsStatus(String messageId, + MessageHubSmsClientGroup clientGroup, + String sourceSystem) { + MessageHubSmsProperties.SourceSystemProperties client = resolveClient(clientGroup); + String resolvedSourceSystem = StringUtils.hasText(sourceSystem) ? sourceSystem.trim() : client.getSourceSystem(); + requireText(messageId, "MessageHub 短信状态查询缺少 messageId"); + requireText(resolvedSourceSystem, "MessageHub 短信状态查询缺少 sourceSystem"); + requireText(client.getAccessToken(), "MessageHub 短信状态查询缺少 accessToken"); + + String targetUrl = UriComponentsBuilder.fromHttpUrl(baseUrl.trim()) + .path("/api/v1/messages/{messageId}/status") + .queryParam("sourceSystem", resolvedSourceSystem) + .buildAndExpand(messageId.trim()) + .toUriString(); + HttpEntity entity = new HttpEntity<>(jsonHeaders(client.getAccessToken())); + Exception lastException = null; + for (int attempt = 1; attempt <= MAX_API_ATTEMPTS; attempt++) { + try { + ResponseEntity> response = restTemplate.exchange( + targetUrl, + HttpMethod.GET, + entity, + new ParameterizedTypeReference>() { + } + ); + return readStatusResponse(response, messageId, resolvedSourceSystem, targetUrl); + } catch (RestClientResponseException exception) { + if (isNotFoundStatusResponse(exception)) { + return notFoundStatus(messageId, resolvedSourceSystem, exception.getResponseBodyAsString()); + } + lastException = exception; + log.warn("MessageHub 状态查询失败,attempt: {}, url: {}, sourceSystem: {}, messageId: {}, statusCode: {}, responseBody: {}", + attempt, targetUrl, resolvedSourceSystem, messageId, exception.getRawStatusCode(), + limitText(exception.getResponseBodyAsString())); + } catch (RestClientException exception) { + lastException = exception; + log.warn("MessageHub 状态查询失败,attempt: {}, url: {}, sourceSystem: {}, messageId: {}, reason: {}", + attempt, targetUrl, resolvedSourceSystem, messageId, exception.getMessage()); + } + sleepBeforeRetry(attempt); + } + throw new BusinessException("MessageHub 状态查询失败:url=" + targetUrl + + ", sourceSystem=" + resolvedSourceSystem + + ", messageId=" + messageId + + ", reason=" + (lastException == null ? "unknown" : lastException.getMessage()), lastException); + } + + @Override + public MessageHubSmsChannel defaultSmsChannel() { + return MessageHubSmsChannel.fromCode(smsProperties.getDefaultChannel(), MessageHubSmsChannel.ALIYUN); + } + + private MessageHubSubmitRequest buildSmsMessageBody(String sceneCode, String phone, String code, - String uniqueId) { - String platform = config == null ? "SMS" : config.getPlatform(); - String resolvedSendMethod = config == null ? "OTHER" : config.getSendMethod(); + String uniqueId, + MessageHubSmsClientGroup clientGroup, + MessageHubSmsChannel channel) { + MessageHubPushConfigDO databaseConfig = messageHubPushConfigService.getEnabledConfig(sceneCode); + MessageHubSmsProperties.SourceSystemProperties client = resolveClient(clientGroup); + MessageHubSmsProperties.ChannelDetailProperties channelConfig = resolveChannel(channel); MessageHubSubmitRequest request = new MessageHubSubmitRequest(); request.setReceiver(phone); - request.setPlatform(platform); - request.setMsgType(config == null ? "VERIFICATION" : config.getMsgType()); - request.setTemplateCode(config == null ? verifyTemplateCode : config.getTemplateCode()); - request.setSourceSystem(config == null ? sourceSystem : config.getSourceSystem()); + request.setPlatform(resolvePlatform(databaseConfig)); + request.setMsgType(resolveMsgType(databaseConfig)); + request.setTemplateCode(resolveTemplateCode(sceneCode, clientGroup, channel, databaseConfig, channelConfig)); + request.setSourceSystem(client.getSourceSystem()); request.setUniqueId(uniqueId); - if (config != null && config.getChannelId() != null) { - request.setChannelId(config.getChannelId()); - } - - Map templateParams = new HashMap<>(); - templateParams.put("name", brandProperties.getMessageTemplateName()); - templateParams.put("code", code); - templateParams.put("min", "5"); - templateParams.put("minutes", "5"); - templateParams.put("number", "5"); - templateParams.put("sceneCode", sceneCode); - request.setTemplateParams(templateParams); - - Map platformParams = new HashMap<>(); - platformParams.put("sendMethod", StringUtils.hasText(resolvedSendMethod) ? resolvedSendMethod : "OTHER"); - request.setPlatformParams(platformParams); + request.setChannelId(resolveChannelId(databaseConfig, channelConfig)); + request.setTemplateParams(templateParams(sceneCode, code, clientGroup, channel)); + request.setPlatformParams(platformParams(resolveSendMethod(databaseConfig, channelConfig, channel))); return request; } - private MessageHubSubmitResponse submitMessage(MessageHubSubmitRequest request) { + private MessageHubSubmitResponse submitMessage(MessageHubSubmitRequest request, String token) { requireText(baseUrl, "MessageHub API 地址未配置:messagehub.client.base-url"); - requireText(accessToken, "MessageHub 来源系统访问令牌未配置:messagehub.client.access-token"); + requireText(token, "MessageHub 来源系统访问令牌未配置"); String targetUrl = UriComponentsBuilder.fromHttpUrl(baseUrl.trim()) .path("/api/v1/messages") .build() .toUriString(); - HttpHeaders headers = new HttpHeaders(); - headers.setContentType(MediaType.APPLICATION_JSON); - headers.setAccept(List.of(MediaType.APPLICATION_JSON)); - headers.set(ACCESS_TOKEN_HEADER, accessToken.trim()); - HttpEntity entity = new HttpEntity<>(request, headers); + HttpEntity entity = new HttpEntity<>(request, jsonHeaders(token)); Exception lastException = null; - for (int attempt = 1; attempt <= MAX_SUBMIT_ATTEMPTS; attempt++) { + for (int attempt = 1; attempt <= MAX_API_ATTEMPTS; attempt++) { try { ResponseEntity> response = restTemplate.exchange( targetUrl, @@ -189,8 +271,261 @@ public class MessageHubClientServiceImpl implements MessageHubClientService { return data; } + private MessageHubSmsStatusVO readStatusResponse(ResponseEntity> response, + String messageId, + String sourceSystem, + String targetUrl) { + if (!response.getStatusCode().is2xxSuccessful()) { + throw new BusinessException("MessageHub 状态查询返回非成功状态:url=" + targetUrl + + ", statusCode=" + response.getStatusCodeValue() + + ", sourceSystem=" + sourceSystem + + ", messageId=" + messageId); + } + MessageHubApiResponse body = response.getBody(); + if (body == null) { + throw new BusinessException("MessageHub 状态查询返回空响应:url=" + targetUrl + + ", sourceSystem=" + sourceSystem + + ", messageId=" + messageId); + } + if (body.getCode() != 0) { + if (isNotFoundMessage(body.getMessage())) { + return notFoundStatus(messageId, sourceSystem, body.getMessage()); + } + throw new BusinessException("MessageHub 状态查询返回业务失败:url=" + targetUrl + + ", sourceSystem=" + sourceSystem + + ", messageId=" + messageId + + ", code=" + body.getCode() + + ", message=" + body.getMessage()); + } + MessageHubStatusResponse data = body.getData(); + if (data == null || !StringUtils.hasText(data.getDispatchStatus())) { + throw new BusinessException("MessageHub 状态查询返回缺少 dispatchStatus:url=" + targetUrl + + ", sourceSystem=" + sourceSystem + + ", messageId=" + messageId + + ", response=" + limitText(toJson(body))); + } + return toStatusVO(data); + } + + private MessageHubSmsSendResult toSendResult(MessageHubSubmitResponse response, + MessageHubSubmitRequest request, + MessageHubSmsClientGroup clientGroup, + MessageHubSmsChannel channel, + String sceneCode) { + MessageHubSmsSendResult result = new MessageHubSmsSendResult(); + result.setMessageId(response.getMessageId()); + result.setSourceSystem(request.getSourceSystem()); + result.setUniqueId(request.getUniqueId()); + result.setPlatform(response.getPlatform()); + result.setDispatchStatus(response.getDispatchStatus()); + result.setOutboxStatus(response.getOutboxStatus()); + result.setChannelCode(channel.name()); + result.setClientGroup(clientGroup.name()); + result.setSceneCode(sceneCode); + return result; + } + + private MessageHubSmsStatusVO toStatusVO(MessageHubStatusResponse data) { + MessageHubSmsStatusVO vo = new MessageHubSmsStatusVO(); + vo.setMessageId(data.getMessageId()); + vo.setSourceSystem(data.getSourceSystem()); + vo.setUniqueId(data.getUniqueId()); + vo.setPlatform(data.getPlatform()); + vo.setDispatchStatus(data.getDispatchStatus()); + vo.setChannelId(data.getChannelId()); + vo.setProviderCode(data.getProviderCode()); + vo.setFailReason(data.getFailReason()); + vo.setOutboxStatus(data.getOutboxStatus()); + return vo; + } + + private MessageHubSmsProperties.SourceSystemProperties resolveClient(MessageHubSmsClientGroup clientGroup) { + MessageHubSmsProperties.SourceSystemProperties configured = clientGroup == MessageHubSmsClientGroup.SALON + ? smsProperties.getClients().getSalon() + : smsProperties.getClients().getDesigner(); + if (StringUtils.hasText(configured.getSourceSystem()) || StringUtils.hasText(configured.getAccessToken())) { + return configured; + } + MessageHubSmsProperties.SourceSystemProperties fallback = new MessageHubSmsProperties.SourceSystemProperties(); + fallback.setSourceSystem(legacySourceSystem); + fallback.setAccessToken(legacyAccessToken); + return fallback; + } + + private MessageHubSmsProperties.ChannelDetailProperties resolveChannel(MessageHubSmsChannel channel) { + if (channel == MessageHubSmsChannel.SPUG) { + return smsProperties.getChannels().getSpug(); + } + return smsProperties.getChannels().getAliyun(); + } + + private void requireSourceSystem(MessageHubSmsProperties.SourceSystemProperties client, String clientName) { + requireText(client.getSourceSystem(), "MessageHub " + clientName + " 来源系统未配置"); + requireText(client.getAccessToken(), "MessageHub " + clientName + " 访问令牌未配置"); + } + + private void requireChannelConfig(MessageHubSmsChannel channel) { + MessageHubSmsProperties.ChannelDetailProperties channelConfig = resolveChannel(channel); + if (channelConfig.getChannelId() == null) { + throw new BusinessException("MessageHub " + channel.name() + " 短信通道 channelId 未配置"); + } + requireText(channelConfig.getSendMethod(), "MessageHub " + channel.name() + " 短信通道 sendMethod 未配置"); + } + + private String resolveTemplateCode(String sceneCode, + MessageHubSmsClientGroup clientGroup, + MessageHubSmsChannel channel, + MessageHubPushConfigDO databaseConfig, + MessageHubSmsProperties.ChannelDetailProperties channelConfig) { + String configuredTemplate = channelConfig.getTemplates().get(normalizeSceneCode(sceneCode)); + if (StringUtils.hasText(configuredTemplate)) { + return configuredTemplate.trim(); + } + if (channel == MessageHubSmsChannel.SPUG) { + if (clientGroup == MessageHubSmsClientGroup.SALON) { + return SALON_SPUG_TEMPLATE_CODE; + } + return DESIGNER_SPUG_TEMPLATE_CODE; + } + if (databaseConfig != null && StringUtils.hasText(databaseConfig.getTemplateCode())) { + return databaseConfig.getTemplateCode(); + } + if (StringUtils.hasText(legacyVerifyTemplateCode)) { + return legacyVerifyTemplateCode.trim(); + } + return DEFAULT_ALIYUN_TEMPLATE_CODE; + } + + private Long resolveChannelId(MessageHubPushConfigDO databaseConfig, + MessageHubSmsProperties.ChannelDetailProperties channelConfig) { + if (channelConfig.getChannelId() != null) { + return channelConfig.getChannelId(); + } + if (databaseConfig != null) { + return databaseConfig.getChannelId(); + } + return null; + } + + private String resolveSendMethod(MessageHubPushConfigDO databaseConfig, + MessageHubSmsProperties.ChannelDetailProperties channelConfig, + MessageHubSmsChannel channel) { + if (StringUtils.hasText(channelConfig.getSendMethod())) { + return channelConfig.getSendMethod().trim().toUpperCase(Locale.ROOT); + } + if (databaseConfig != null && StringUtils.hasText(databaseConfig.getSendMethod())) { + return databaseConfig.getSendMethod().trim().toUpperCase(Locale.ROOT); + } + if (channel == MessageHubSmsChannel.SPUG) { + return "SPUG"; + } + return "OTHER"; + } + + private String resolvePlatform(MessageHubPushConfigDO databaseConfig) { + if (databaseConfig != null && StringUtils.hasText(databaseConfig.getPlatform())) { + return databaseConfig.getPlatform(); + } + return "SMS"; + } + + private String resolveMsgType(MessageHubPushConfigDO databaseConfig) { + if (databaseConfig != null && StringUtils.hasText(databaseConfig.getMsgType())) { + return databaseConfig.getMsgType(); + } + return "VERIFICATION"; + } + + private Map templateParams(String sceneCode, + String code, + MessageHubSmsClientGroup clientGroup, + MessageHubSmsChannel channel) { + Map params = new HashMap<>(); + if (channel == MessageHubSmsChannel.SPUG) { + if (clientGroup == MessageHubSmsClientGroup.DESIGNER) { + params.put("name", requireSpugDesignerName()); + } + params.put("number", resolveValidMinutesText()); + } else { + params.put("name", brandProperties.getMessageTemplateName()); + params.put("min", "5"); + params.put("minutes", "5"); + params.put("number", "5"); + params.put("sceneCode", sceneCode); + } + params.put("code", code); + return params; + } + + private Map platformParams(String sendMethod) { + Map params = new HashMap<>(); + params.put("sendMethod", StringUtils.hasText(sendMethod) ? sendMethod : "OTHER"); + return params; + } + + private HttpHeaders jsonHeaders(String token) { + HttpHeaders headers = new HttpHeaders(); + headers.setContentType(MediaType.APPLICATION_JSON); + headers.setAccept(List.of(MediaType.APPLICATION_JSON)); + headers.set(ACCESS_TOKEN_HEADER, token.trim()); + return headers; + } + + private String normalizeSceneCode(String sceneCode) { + if (!StringUtils.hasText(sceneCode)) { + return ""; + } + return sceneCode.trim().toUpperCase(Locale.ROOT); + } + + private String resolveValidMinutesText() { + if (StringUtils.hasText(smsProperties.getValidMinutesText())) { + return smsProperties.getValidMinutesText().trim(); + } + return ""; + } + + private String requireSpugDesignerName() { + requireText(brandProperties.getMessageTemplateName(), "SPUG 短信模板 name 参数未配置:brand.message-template-name"); + String name = brandProperties.getMessageTemplateName().trim(); + validateSpugName(name); + return name; + } + + private void validateSpugName(String name) { + if (!StringUtils.hasText(name)) { + return; + } + String trimmed = name.trim(); + if (!trimmed.matches("^[\\u4e00-\\u9fa5A-Za-z]{1,10}$")) { + throw new BusinessException("SPUG 短信模板 name 参数必须为 1-10 位中文或英文字符:name=" + trimmed); + } + } + + private boolean isNotFoundStatusResponse(RestClientResponseException exception) { + int statusCode = exception.getRawStatusCode(); + if (statusCode != 400 && statusCode != 404) { + return false; + } + String body = exception.getResponseBodyAsString(); + return isNotFoundMessage(body); + } + + private boolean isNotFoundMessage(String value) { + return value != null && value.toLowerCase(Locale.ROOT).contains("not found"); + } + + private MessageHubSmsStatusVO notFoundStatus(String messageId, String sourceSystem, String reason) { + MessageHubSmsStatusVO notFound = new MessageHubSmsStatusVO(); + notFound.setMessageId(messageId); + notFound.setSourceSystem(sourceSystem); + notFound.setDispatchStatus("FAILED"); + notFound.setFailReason("MessageHub 状态查询未找到上一条消息:" + limitText(reason)); + return notFound; + } + private void sleepBeforeRetry(int attempt) { - if (attempt >= MAX_SUBMIT_ATTEMPTS) { + if (attempt >= MAX_API_ATTEMPTS) { return; } try { @@ -274,4 +609,26 @@ public class MessageHubClientServiceImpl implements MessageHubClientService { private String outboxStatus; } + + @Data + private static class MessageHubStatusResponse { + + private String messageId; + + private String sourceSystem; + + private String uniqueId; + + private String platform; + + private String dispatchStatus; + + private Long channelId; + + private String providerCode; + + private String failReason; + + private String outboxStatus; + } } diff --git a/JY-Core/src/main/java/com/xiaowang/jayucloud/core/modules/integration/support/MessageHubSmsChannel.java b/JY-Core/src/main/java/com/xiaowang/jayucloud/core/modules/integration/support/MessageHubSmsChannel.java new file mode 100644 index 00000000..19b97034 --- /dev/null +++ b/JY-Core/src/main/java/com/xiaowang/jayucloud/core/modules/integration/support/MessageHubSmsChannel.java @@ -0,0 +1,31 @@ +package com.xiaowang.jayucloud.core.modules.integration.support; + +import com.xiaowang.jayucloud.core.common.BusinessException; +import org.springframework.util.StringUtils; + +import java.util.Locale; + +public enum MessageHubSmsChannel { + ALIYUN, + SPUG; + + public static MessageHubSmsChannel fromCode(String code, MessageHubSmsChannel fallback) { + if (!StringUtils.hasText(code)) { + return fallback; + } + String normalized = code.trim().toUpperCase(Locale.ROOT); + for (MessageHubSmsChannel channel : values()) { + if (channel.name().equals(normalized)) { + return channel; + } + } + throw new BusinessException("不支持的 MessageHub 短信通道:" + code); + } + + public MessageHubSmsChannel opposite() { + if (this == ALIYUN) { + return SPUG; + } + return ALIYUN; + } +} diff --git a/JY-Core/src/main/java/com/xiaowang/jayucloud/core/modules/integration/support/MessageHubSmsClientGroup.java b/JY-Core/src/main/java/com/xiaowang/jayucloud/core/modules/integration/support/MessageHubSmsClientGroup.java new file mode 100644 index 00000000..4ea040f2 --- /dev/null +++ b/JY-Core/src/main/java/com/xiaowang/jayucloud/core/modules/integration/support/MessageHubSmsClientGroup.java @@ -0,0 +1,33 @@ +package com.xiaowang.jayucloud.core.modules.integration.support; + +import org.springframework.util.StringUtils; + +import java.util.Locale; + +public enum MessageHubSmsClientGroup { + DESIGNER, + SALON; + + private static final String MANAGER_WEB = "MANAGER_WEB"; + private static final String SALON_WECHAT_MINI = "SALON_WECHAT_MINI"; + private static final String PLANNING_MANAGER_REGISTER = "PLANNING_MANAGER_REGISTER"; + + public static MessageHubSmsClientGroup resolve(String clientType, String sceneCode) { + String normalizedClientType = normalize(clientType); + if (MANAGER_WEB.equals(normalizedClientType) || SALON_WECHAT_MINI.equals(normalizedClientType)) { + return SALON; + } + String normalizedSceneCode = normalize(sceneCode); + if (PLANNING_MANAGER_REGISTER.equals(normalizedSceneCode)) { + return SALON; + } + return DESIGNER; + } + + private static String normalize(String value) { + if (!StringUtils.hasText(value)) { + return ""; + } + return value.trim().toUpperCase(Locale.ROOT); + } +} diff --git a/JY-Core/src/main/java/com/xiaowang/jayucloud/core/modules/integration/vo/MessageHubSmsSendResult.java b/JY-Core/src/main/java/com/xiaowang/jayucloud/core/modules/integration/vo/MessageHubSmsSendResult.java new file mode 100644 index 00000000..77c3881d --- /dev/null +++ b/JY-Core/src/main/java/com/xiaowang/jayucloud/core/modules/integration/vo/MessageHubSmsSendResult.java @@ -0,0 +1,25 @@ +package com.xiaowang.jayucloud.core.modules.integration.vo; + +import lombok.Data; + +@Data +public class MessageHubSmsSendResult { + + private String messageId; + + private String sourceSystem; + + private String uniqueId; + + private String platform; + + private String dispatchStatus; + + private String outboxStatus; + + private String channelCode; + + private String clientGroup; + + private String sceneCode; +} diff --git a/JY-Core/src/main/java/com/xiaowang/jayucloud/core/modules/integration/vo/MessageHubSmsStatusVO.java b/JY-Core/src/main/java/com/xiaowang/jayucloud/core/modules/integration/vo/MessageHubSmsStatusVO.java new file mode 100644 index 00000000..fca09831 --- /dev/null +++ b/JY-Core/src/main/java/com/xiaowang/jayucloud/core/modules/integration/vo/MessageHubSmsStatusVO.java @@ -0,0 +1,29 @@ +package com.xiaowang.jayucloud.core.modules.integration.vo; + +import lombok.Data; + +@Data +public class MessageHubSmsStatusVO { + + private String messageId; + + private String sourceSystem; + + private String uniqueId; + + private String platform; + + private String dispatchStatus; + + private Long channelId; + + private String providerCode; + + private String failReason; + + private String outboxStatus; + + public boolean isSuccess() { + return "SUCCESS".equalsIgnoreCase(dispatchStatus); + } +} diff --git a/JY-Core/src/main/java/com/xiaowang/jayucloud/core/modules/user/controller/front/UserController.java b/JY-Core/src/main/java/com/xiaowang/jayucloud/core/modules/user/controller/front/UserController.java index 1921979f..1dd7af53 100644 --- a/JY-Core/src/main/java/com/xiaowang/jayucloud/core/modules/user/controller/front/UserController.java +++ b/JY-Core/src/main/java/com/xiaowang/jayucloud/core/modules/user/controller/front/UserController.java @@ -610,7 +610,11 @@ public class UserController { */ throw new RuntimeException("验证码发送过于频繁,请1分钟后再试"); } - verificationCodeService.sendVerificationCode(sendVerificationCodeRequestDTO.getPhone(), sendVerificationCodeRequestDTO.getSceneCode()); + verificationCodeService.sendVerificationCode( + sendVerificationCodeRequestDTO.getPhone(), + sendVerificationCodeRequestDTO.getSceneCode(), + sendVerificationCodeRequestDTO.getClientType() + ); return Result.success(true); } diff --git a/JY-Core/src/main/java/com/xiaowang/jayucloud/core/modules/user/service/impl/UserServiceImpl.java b/JY-Core/src/main/java/com/xiaowang/jayucloud/core/modules/user/service/impl/UserServiceImpl.java index 5aaf2df5..52e409bd 100644 --- a/JY-Core/src/main/java/com/xiaowang/jayucloud/core/modules/user/service/impl/UserServiceImpl.java +++ b/JY-Core/src/main/java/com/xiaowang/jayucloud/core/modules/user/service/impl/UserServiceImpl.java @@ -1220,6 +1220,7 @@ public class UserServiceImpl extends ServiceImpl implements */ private static final String ENCODED_UNSET_PASSWORD = "$2a$10$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW"; // 加密后的特殊标识 private static final String MANAGER_WEB_CLIENT_TYPE = "MANAGER_WEB"; + private static final String SALON_WECHAT_MINI_CLIENT_TYPE = "SALON_WECHAT_MINI"; /** * Run the registration flow. @@ -1460,7 +1461,9 @@ public class UserServiceImpl extends ServiceImpl implements } private boolean isManagerWebClient(String clientType) { - return MANAGER_WEB_CLIENT_TYPE.equalsIgnoreCase(clientType == null ? "" : clientType.trim()); + String normalizedClientType = clientType == null ? "" : clientType.trim(); + return MANAGER_WEB_CLIENT_TYPE.equalsIgnoreCase(normalizedClientType) + || SALON_WECHAT_MINI_CLIENT_TYPE.equalsIgnoreCase(normalizedClientType); } private boolean isManagerLoginUser(UserDO userDO) { diff --git a/JY-Core/src/test/java/com/xiaowang/jayucloud/core/modules/auth/service/impl/VerificationCodeServiceImplTest.java b/JY-Core/src/test/java/com/xiaowang/jayucloud/core/modules/auth/service/impl/VerificationCodeServiceImplTest.java new file mode 100644 index 00000000..f930687d --- /dev/null +++ b/JY-Core/src/test/java/com/xiaowang/jayucloud/core/modules/auth/service/impl/VerificationCodeServiceImplTest.java @@ -0,0 +1,139 @@ +package com.xiaowang.jayucloud.core.modules.auth.service.impl; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.xiaowang.jayucloud.core.common.BusinessException; +import com.xiaowang.jayucloud.core.modules.integration.service.MessageHubClientService; +import com.xiaowang.jayucloud.core.modules.integration.support.MessageHubSmsChannel; +import com.xiaowang.jayucloud.core.modules.integration.support.MessageHubSmsClientGroup; +import com.xiaowang.jayucloud.core.modules.integration.vo.MessageHubSmsSendResult; +import com.xiaowang.jayucloud.core.modules.integration.vo.MessageHubSmsStatusVO; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.springframework.data.redis.core.StringRedisTemplate; +import org.springframework.data.redis.core.ValueOperations; + +import java.time.Duration; + +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +class VerificationCodeServiceImplTest { + + @Mock + private StringRedisTemplate redisTemplate; + + @Mock + private ValueOperations valueOperations; + + @Mock + private MessageHubClientService messageHubClientService; + + private VerificationCodeServiceImpl service; + + @BeforeEach + void setUp() { + MockitoAnnotations.openMocks(this); + when(redisTemplate.opsForValue()).thenReturn(valueOperations); + when(messageHubClientService.defaultSmsChannel()).thenReturn(MessageHubSmsChannel.ALIYUN); + service = new VerificationCodeServiceImpl(redisTemplate, messageHubClientService, new ObjectMapper()); + } + + @Test + void firstSendDoesNotQueryStatusAndUsesDefaultChannel() { + when(valueOperations.get("verification:last_message:13800138000")).thenReturn(null); + when(messageHubClientService.sendSmsVerificationCode(eq("USER_LOGIN_SMS_CODE"), eq("13800138000"), any(), eq("WEB"), eq(MessageHubSmsChannel.ALIYUN))) + .thenReturn(sendResult("message-1", MessageHubSmsChannel.ALIYUN, MessageHubSmsClientGroup.DESIGNER)); + + service.sendVerificationCode("13800138000", "USER_LOGIN_SMS_CODE", "WEB"); + + verify(messageHubClientService, never()).querySmsStatus(any(), any(), any()); + verify(valueOperations).set(eq("verification:code:13800138000"), any(), eq(Duration.ofMinutes(5))); + verify(valueOperations).set(eq("verification:send_time:13800138000"), any(), eq(Duration.ofSeconds(60))); + verify(valueOperations).set(eq("verification:last_message:13800138000"), any(), eq(Duration.ofMinutes(5))); + } + + @Test + void resendKeepsPreviousChannelWhenLastMessageSucceeded() { + when(valueOperations.get("verification:last_message:13800138000")).thenReturn(""" + {"messageId":"message-1","uniqueId":"unique-1","sourceSystem":"jayucloud-designer","channelCode":"ALIYUN","clientGroup":"DESIGNER","sceneCode":"USER_LOGIN_SMS_CODE"} + """); + when(messageHubClientService.querySmsStatus("message-1", MessageHubSmsClientGroup.DESIGNER, "jayucloud-designer")) + .thenReturn(status("SUCCESS")); + when(messageHubClientService.sendSmsVerificationCode(eq("USER_LOGIN_SMS_CODE"), eq("13800138000"), any(), eq("WEB"), eq(MessageHubSmsChannel.ALIYUN))) + .thenReturn(sendResult("message-2", MessageHubSmsChannel.ALIYUN, MessageHubSmsClientGroup.DESIGNER)); + + service.sendVerificationCode("13800138000", "USER_LOGIN_SMS_CODE", "WEB"); + + verify(messageHubClientService).sendSmsVerificationCode(eq("USER_LOGIN_SMS_CODE"), eq("13800138000"), any(), eq("WEB"), eq(MessageHubSmsChannel.ALIYUN)); + } + + @Test + void resendKeepsPreviousChannelWhenLastMessageSucceededEvenIfClientGroupChanged() { + when(valueOperations.get("verification:last_message:13800138000")).thenReturn(""" + {"messageId":"message-1","uniqueId":"unique-1","sourceSystem":"jayucloud-designer","channelCode":"ALIYUN","clientGroup":"DESIGNER","sceneCode":"USER_LOGIN_SMS_CODE"} + """); + when(messageHubClientService.querySmsStatus("message-1", MessageHubSmsClientGroup.DESIGNER, "jayucloud-designer")) + .thenReturn(status("SUCCESS")); + when(messageHubClientService.sendSmsVerificationCode(eq("USER_LOGIN_SMS_CODE"), eq("13800138000"), any(), eq("MANAGER_WEB"), eq(MessageHubSmsChannel.ALIYUN))) + .thenReturn(sendResult("message-2", MessageHubSmsChannel.ALIYUN, MessageHubSmsClientGroup.SALON)); + + service.sendVerificationCode("13800138000", "USER_LOGIN_SMS_CODE", "MANAGER_WEB"); + + verify(messageHubClientService).sendSmsVerificationCode(eq("USER_LOGIN_SMS_CODE"), eq("13800138000"), any(), eq("MANAGER_WEB"), eq(MessageHubSmsChannel.ALIYUN)); + } + + @Test + void resendSwitchesChannelWhenLastMessageIsPending() { + when(valueOperations.get("verification:last_message:13800138000")).thenReturn(""" + {"messageId":"message-1","uniqueId":"unique-1","sourceSystem":"jayucloud-designer","channelCode":"ALIYUN","clientGroup":"DESIGNER","sceneCode":"USER_LOGIN_SMS_CODE"} + """); + when(messageHubClientService.querySmsStatus("message-1", MessageHubSmsClientGroup.DESIGNER, "jayucloud-designer")) + .thenReturn(status("PENDING")); + when(messageHubClientService.sendSmsVerificationCode(eq("USER_LOGIN_SMS_CODE"), eq("13800138000"), any(), eq("WEB"), eq(MessageHubSmsChannel.SPUG))) + .thenReturn(sendResult("message-2", MessageHubSmsChannel.SPUG, MessageHubSmsClientGroup.DESIGNER)); + + service.sendVerificationCode("13800138000", "USER_LOGIN_SMS_CODE", "WEB"); + + verify(messageHubClientService).sendSmsVerificationCode(eq("USER_LOGIN_SMS_CODE"), eq("13800138000"), any(), eq("WEB"), eq(MessageHubSmsChannel.SPUG)); + } + + @Test + void statusQueryFailureStopsBeforeNewCodeIsStored() { + when(valueOperations.get("verification:last_message:13800138000")).thenReturn(""" + {"messageId":"message-1","uniqueId":"unique-1","sourceSystem":"jayucloud-designer","channelCode":"ALIYUN","clientGroup":"DESIGNER","sceneCode":"USER_LOGIN_SMS_CODE"} + """); + when(messageHubClientService.querySmsStatus("message-1", MessageHubSmsClientGroup.DESIGNER, "jayucloud-designer")) + .thenThrow(new BusinessException("MessageHub 状态查询失败")); + + assertThrows(BusinessException.class, () -> service.sendVerificationCode("13800138000", "USER_LOGIN_SMS_CODE", "WEB")); + + verify(messageHubClientService, never()).sendSmsVerificationCode(any(), any(), any(), any(), any()); + verify(valueOperations, never()).set(eq("verification:code:13800138000"), any(), any(Duration.class)); + } + + private MessageHubSmsStatusVO status(String dispatchStatus) { + MessageHubSmsStatusVO status = new MessageHubSmsStatusVO(); + status.setMessageId("message-1"); + status.setDispatchStatus(dispatchStatus); + return status; + } + + private MessageHubSmsSendResult sendResult(String messageId, + MessageHubSmsChannel channel, + MessageHubSmsClientGroup clientGroup) { + MessageHubSmsSendResult result = new MessageHubSmsSendResult(); + result.setMessageId(messageId); + result.setUniqueId("unique-" + messageId); + result.setSourceSystem(clientGroup == MessageHubSmsClientGroup.SALON ? "jayucloud-salon" : "jayucloud-designer"); + result.setChannelCode(channel.name()); + result.setClientGroup(clientGroup.name()); + result.setSceneCode("USER_LOGIN_SMS_CODE"); + return result; + } +} diff --git a/JY-Core/src/test/java/com/xiaowang/jayucloud/core/modules/integration/service/impl/MessageHubClientServiceImplTest.java b/JY-Core/src/test/java/com/xiaowang/jayucloud/core/modules/integration/service/impl/MessageHubClientServiceImplTest.java index 7435b078..d317899b 100644 --- a/JY-Core/src/test/java/com/xiaowang/jayucloud/core/modules/integration/service/impl/MessageHubClientServiceImplTest.java +++ b/JY-Core/src/test/java/com/xiaowang/jayucloud/core/modules/integration/service/impl/MessageHubClientServiceImplTest.java @@ -1,8 +1,13 @@ package com.xiaowang.jayucloud.core.modules.integration.service.impl; +import com.fasterxml.jackson.databind.ObjectMapper; import com.xiaowang.jayucloud.core.config.BrandProperties; +import com.xiaowang.jayucloud.core.config.MessageHubSmsProperties; import com.xiaowang.jayucloud.core.modules.integration.entity.MessageHubPushConfigDO; import com.xiaowang.jayucloud.core.modules.integration.service.MessageHubPushConfigService; +import com.xiaowang.jayucloud.core.modules.integration.support.MessageHubSmsChannel; +import com.xiaowang.jayucloud.core.modules.integration.support.MessageHubSmsClientGroup; +import com.xiaowang.jayucloud.core.modules.integration.vo.MessageHubSmsStatusVO; import com.xiaowang.jayucloud.core.support.id.TimeOrderedSnowflakeIdGenerator; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -14,7 +19,9 @@ import org.springframework.test.web.client.MockRestServiceServer; import org.springframework.web.client.RestTemplate; import static org.hamcrest.Matchers.is; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.when; +import static org.springframework.test.web.client.match.MockRestRequestMatchers.content; import static org.springframework.test.web.client.match.MockRestRequestMatchers.header; import static org.springframework.test.web.client.match.MockRestRequestMatchers.jsonPath; import static org.springframework.test.web.client.match.MockRestRequestMatchers.method; @@ -24,8 +31,10 @@ import static org.springframework.test.web.client.response.MockRestResponseCreat class MessageHubClientServiceImplTest { private static final long ALIYUN_CHANNEL_ID = 314055468907909120L; + private static final long SPUG_CHANNEL_ID = 314055468907909121L; private static final String MESSAGEHUB_URL = "http://messagehub.test"; - private static final String ACCESS_TOKEN = "test-token"; + private static final String DESIGNER_TOKEN = "designer-token"; + private static final String SALON_TOKEN = "salon-token"; @Mock private TimeOrderedSnowflakeIdGenerator snowflakeIdGenerator; @@ -46,18 +55,19 @@ class MessageHubClientServiceImplTest { restTemplate = new RestTemplate(); mockServer = MockRestServiceServer.createServer(restTemplate); service = new MessageHubClientServiceImpl( - new com.fasterxml.jackson.databind.ObjectMapper(), + new ObjectMapper(), snowflakeIdGenerator, messageHubPushConfigService, restTemplate, - brandProperties + brandProperties, + smsProperties() ); ReflectionTestUtils.setField(service, "baseUrl", MESSAGEHUB_URL); - ReflectionTestUtils.setField(service, "sourceSystem", "jayucloud"); - ReflectionTestUtils.setField(service, "accessToken", ACCESS_TOKEN); - ReflectionTestUtils.setField(service, "verifyTemplateCode", "100001"); + ReflectionTestUtils.setField(service, "legacySourceSystem", "jayucloud"); + ReflectionTestUtils.setField(service, "legacyAccessToken", "legacy-token"); + ReflectionTestUtils.setField(service, "legacyVerifyTemplateCode", "100001"); when(snowflakeIdGenerator.nextIdString()).thenReturn("sms-message-1"); - when(brandProperties.getMessageTemplateName()).thenReturn("甲屿云"); + when(brandProperties.getMessageTemplateName()).thenReturn("甲屿"); } @Test @@ -65,57 +75,128 @@ class MessageHubClientServiceImplTest { String sceneCode = "USER_REGISTER_SMS_CODE"; when(messageHubPushConfigService.getEnabledConfig(sceneCode)) .thenReturn(aliyunConfig(sceneCode, "100001")); - expectSubmit("100001", "123456"); + expectAliyunSubmit("100001", "123456"); - service.sendSmsVerificationCode(sceneCode, "13800138000", "123456"); + service.sendSmsVerificationCode(sceneCode, "13800138000", "123456", "WEB", MessageHubSmsChannel.ALIYUN); mockServer.verify(); } @Test - void resetPasswordVerificationMessageUsesResetTemplateWithAliyunParameters() { - String sceneCode = "USER_RESET_PASSWORD_SMS_CODE"; - when(messageHubPushConfigService.getEnabledConfig(sceneCode)) - .thenReturn(aliyunConfig(sceneCode, "100003")); - expectSubmit("100003", "654321"); + void designerSpugVerificationMessageUsesTemplateOne() { + String sceneCode = "USER_LOGIN_SMS_CODE"; + when(messageHubPushConfigService.getEnabledConfig(sceneCode)).thenReturn(null); + expectDesignerSpugSubmit(sceneCode, "123456"); - service.sendSmsVerificationCode(sceneCode, "13800138000", "654321"); + service.sendSmsVerificationCode(sceneCode, "13800138000", "123456", "WEB", MessageHubSmsChannel.SPUG); mockServer.verify(); } - private void expectSubmit(String templateCode, String code) { - mockServer.expect(requestTo(MESSAGEHUB_URL + "/api/v1/messages")) - .andExpect(method(org.springframework.http.HttpMethod.POST)) - .andExpect(header("X-MessageHub-Access-Token", ACCESS_TOKEN)) - .andExpect(jsonPath("$.sourceSystem", is("jayucloud"))) - .andExpect(jsonPath("$.platform", is("SMS"))) - .andExpect(jsonPath("$.receiver", is("13800138000"))) - .andExpect(jsonPath("$.msgType", is("VERIFICATION"))) - .andExpect(jsonPath("$.templateCode", is(templateCode))) - .andExpect(jsonPath("$.channelId", is(ALIYUN_CHANNEL_ID))) - .andExpect(jsonPath("$.uniqueId", is("sms-message-1"))) - .andExpect(jsonPath("$.templateParams.name", is("甲屿云"))) - .andExpect(jsonPath("$.templateParams.code", is(code))) - .andExpect(jsonPath("$.templateParams.min", is("5"))) - .andExpect(jsonPath("$.templateParams.minutes", is("5"))) - .andExpect(jsonPath("$.templateParams.number", is("5"))) - .andExpect(jsonPath("$.platformParams.sendMethod", is("OTHER"))) + @Test + void salonSpugVerificationMessageUsesTemplateThreeWithoutName() { + String sceneCode = "USER_LOGIN_SMS_CODE"; + when(messageHubPushConfigService.getEnabledConfig(sceneCode)).thenReturn(null); + expectSalonSpugSubmit(sceneCode, "654321"); + + service.sendSmsVerificationCode(sceneCode, "13800138000", "654321", "MANAGER_WEB", MessageHubSmsChannel.SPUG); + + mockServer.verify(); + } + + @Test + void statusQueryUsesClientTokenAndParsesSuccess() { + mockServer.expect(requestTo(MESSAGEHUB_URL + "/api/v1/messages/messagehub-message-1/status?sourceSystem=jayucloud-designer")) + .andExpect(method(org.springframework.http.HttpMethod.GET)) + .andExpect(header("X-MessageHub-Access-Token", DESIGNER_TOKEN)) .andRespond(withSuccess(""" { "code": 0, "message": "success", "data": { "messageId": "messagehub-message-1", - "sourceSystem": "jayucloud", + "sourceSystem": "jayucloud-designer", "uniqueId": "sms-message-1", "platform": "SMS", - "dispatchStatus": "ACCEPTED", - "idempotentHit": false, - "outboxStatus": "PENDING" + "dispatchStatus": "SUCCESS", + "channelId": 314055468907909121, + "providerCode": "SPUG", + "outboxStatus": "SENT" } } """, MediaType.APPLICATION_JSON)); + + MessageHubSmsStatusVO status = service.querySmsStatus("messagehub-message-1", MessageHubSmsClientGroup.DESIGNER, "jayucloud-designer"); + + assertTrue(status.isSuccess()); + mockServer.verify(); + } + + private void expectAliyunSubmit(String templateCode, String code) { + mockServer.expect(requestTo(MESSAGEHUB_URL + "/api/v1/messages")) + .andExpect(method(org.springframework.http.HttpMethod.POST)) + .andExpect(header("X-MessageHub-Access-Token", DESIGNER_TOKEN)) + .andExpect(jsonPath("$.sourceSystem", is("jayucloud-designer"))) + .andExpect(jsonPath("$.platform", is("SMS"))) + .andExpect(jsonPath("$.receiver", is("13800138000"))) + .andExpect(jsonPath("$.msgType", is("VERIFICATION"))) + .andExpect(jsonPath("$.templateCode", is(templateCode))) + .andExpect(jsonPath("$.channelId", is(ALIYUN_CHANNEL_ID))) + .andExpect(jsonPath("$.uniqueId", is("sms-message-1"))) + .andExpect(jsonPath("$.templateParams.name", is("甲屿"))) + .andExpect(jsonPath("$.templateParams.code", is(code))) + .andExpect(jsonPath("$.templateParams.min", is("5"))) + .andExpect(jsonPath("$.templateParams.minutes", is("5"))) + .andExpect(jsonPath("$.templateParams.number", is("5"))) + .andExpect(jsonPath("$.platformParams.sendMethod", is("OTHER"))) + .andRespond(successSubmit()); + } + + private void expectDesignerSpugSubmit(String sceneCode, String code) { + mockServer.expect(requestTo(MESSAGEHUB_URL + "/api/v1/messages")) + .andExpect(method(org.springframework.http.HttpMethod.POST)) + .andExpect(header("X-MessageHub-Access-Token", DESIGNER_TOKEN)) + .andExpect(jsonPath("$.sourceSystem", is("jayucloud-designer"))) + .andExpect(jsonPath("$.templateCode", is("SPUG_SMS_VERIFY_1"))) + .andExpect(jsonPath("$.channelId", is(SPUG_CHANNEL_ID))) + .andExpect(jsonPath("$.templateParams.name", is("甲屿"))) + .andExpect(jsonPath("$.templateParams.code", is(code))) + .andExpect(jsonPath("$.templateParams.number", is("五"))) + .andExpect(content().string(org.hamcrest.Matchers.not(org.hamcrest.Matchers.containsString("sceneCode")))) + .andExpect(jsonPath("$.platformParams.sendMethod", is("SPUG"))) + .andRespond(successSubmit()); + } + + private void expectSalonSpugSubmit(String sceneCode, String code) { + mockServer.expect(requestTo(MESSAGEHUB_URL + "/api/v1/messages")) + .andExpect(method(org.springframework.http.HttpMethod.POST)) + .andExpect(header("X-MessageHub-Access-Token", SALON_TOKEN)) + .andExpect(jsonPath("$.sourceSystem", is("jayucloud-salon"))) + .andExpect(jsonPath("$.templateCode", is("SPUG_SMS_VERIFY_3"))) + .andExpect(jsonPath("$.channelId", is(SPUG_CHANNEL_ID))) + .andExpect(jsonPath("$.templateParams.code", is(code))) + .andExpect(jsonPath("$.templateParams.number", is("五"))) + .andExpect(content().string(org.hamcrest.Matchers.not(org.hamcrest.Matchers.containsString("sceneCode")))) + .andExpect(jsonPath("$.platformParams.sendMethod", is("SPUG"))) + .andRespond(successSubmit()); + } + + private org.springframework.test.web.client.ResponseCreator successSubmit() { + return withSuccess(""" + { + "code": 0, + "message": "success", + "data": { + "messageId": "messagehub-message-1", + "sourceSystem": "jayucloud-designer", + "uniqueId": "sms-message-1", + "platform": "SMS", + "dispatchStatus": "ACCEPTED", + "idempotentHit": false, + "outboxStatus": "PENDING" + } + } + """, MediaType.APPLICATION_JSON); } private MessageHubPushConfigDO aliyunConfig(String sceneCode, String templateCode) { @@ -132,4 +213,19 @@ class MessageHubClientServiceImplTest { config.setIsDelete(0); return config; } + + private MessageHubSmsProperties smsProperties() { + MessageHubSmsProperties properties = new MessageHubSmsProperties(); + properties.setDefaultChannel("ALIYUN"); + properties.setValidMinutesText("五"); + properties.getClients().getDesigner().setSourceSystem("jayucloud-designer"); + properties.getClients().getDesigner().setAccessToken(DESIGNER_TOKEN); + properties.getClients().getSalon().setSourceSystem("jayucloud-salon"); + properties.getClients().getSalon().setAccessToken(SALON_TOKEN); + properties.getChannels().getAliyun().setChannelId(ALIYUN_CHANNEL_ID); + properties.getChannels().getAliyun().setSendMethod("OTHER"); + properties.getChannels().getSpug().setChannelId(SPUG_CHANNEL_ID); + properties.getChannels().getSpug().setSendMethod("SPUG"); + return properties; + } } diff --git a/JY-Core/src/test/java/com/xiaowang/jayucloud/core/modules/user/service/impl/UserServiceImplPermissionAssignmentTest.java b/JY-Core/src/test/java/com/xiaowang/jayucloud/core/modules/user/service/impl/UserServiceImplPermissionAssignmentTest.java index e8ff18fc..5cf4fa5b 100644 --- a/JY-Core/src/test/java/com/xiaowang/jayucloud/core/modules/user/service/impl/UserServiceImplPermissionAssignmentTest.java +++ b/JY-Core/src/test/java/com/xiaowang/jayucloud/core/modules/user/service/impl/UserServiceImplPermissionAssignmentTest.java @@ -209,6 +209,29 @@ class UserServiceImplPermissionAssignmentTest { .hasMessageContaining("仅店长或美甲师可登录店务端"); } + @Test + void salonWechatMiniPhoneLoginRejectsPlainCustomer() { + PhoneLoginRequestDTO request = new PhoneLoginRequestDTO(); + request.setPhone("13900000002"); + request.setVerificationCode("123456"); + request.setClientType("SALON_WECHAT_MINI"); + + UserDO customer = new UserDO(); + customer.setId(1002L); + customer.setAccount("plaincustomer"); + customer.setPhone("13900000002"); + customer.setType(0); + customer.setStatus(1); + customer.setIsDelete(0); + + when(verificationCodeService.verifyCode("13900000002", "123456")).thenReturn(true); + when(userMapper.selectOne(org.mockito.ArgumentMatchers.any())).thenReturn(customer); + + assertThatThrownBy(() -> service.phoneLogin(request)) + .isInstanceOf(RuntimeException.class) + .hasMessageContaining("仅店长或美甲师可登录店务端"); + } + @Test void managerLoginShopSelectionRejectsPlainCustomerPhone() { UserDO customer = new UserDO(); diff --git a/JY-Salon-Front/src/api/auth.ts b/JY-Salon-Front/src/api/auth.ts index 34f2f0bf..21df10d1 100644 --- a/JY-Salon-Front/src/api/auth.ts +++ b/JY-Salon-Front/src/api/auth.ts @@ -39,10 +39,10 @@ export const authApi = { return adminApi.get(`/auth/login-shops/${encodeURIComponent(account)}`) }, sendRegisterCode(phone: string): Promise { - return api.post('/user/send-verification-code', { phone, sceneCode: 'PLANNING_MANAGER_REGISTER' }) + return api.post('/user/send-verification-code', { phone, sceneCode: 'PLANNING_MANAGER_REGISTER', clientType: 'MANAGER_WEB' }) }, sendLoginCode(phone: string): Promise { - return api.post('/user/send-verification-code', { phone, sceneCode: 'USER_LOGIN_SMS_CODE' }) + return api.post('/user/send-verification-code', { phone, sceneCode: 'USER_LOGIN_SMS_CODE', clientType: 'MANAGER_WEB' }) }, phoneLogin(data: PhoneLoginRequest): Promise { return api.post('/user/phone-login', data) diff --git a/JY-Salon-WeChat/api/auth.js b/JY-Salon-WeChat/api/auth.js index 40ed96ba..fa00481d 100644 --- a/JY-Salon-WeChat/api/auth.js +++ b/JY-Salon-WeChat/api/auth.js @@ -34,7 +34,8 @@ module.exports = { }, data: { phone, - sceneCode: 'PLANNING_MANAGER_REGISTER' + sceneCode: 'PLANNING_MANAGER_REGISTER', + clientType: 'SALON_WECHAT_MINI' } }) }, @@ -48,7 +49,8 @@ module.exports = { }, data: { phone, - sceneCode: 'USER_LOGIN_SMS_CODE' + sceneCode: 'USER_LOGIN_SMS_CODE', + clientType: 'SALON_WECHAT_MINI' } }) }, diff --git a/JY-Salon-WeChat/pages/login/index.js b/JY-Salon-WeChat/pages/login/index.js index 58bf55c5..62ca5a47 100644 --- a/JY-Salon-WeChat/pages/login/index.js +++ b/JY-Salon-WeChat/pages/login/index.js @@ -238,7 +238,7 @@ Page({ return { agreementAccepted: !!this.data.agreementAccepted, agreementVersions, - clientType: 'WECHAT_MINI' + clientType: 'SALON_WECHAT_MINI' } }, diff --git a/docs/运维配置与集成说明.md b/docs/运维配置与集成说明.md index e86899a6..251a89ba 100644 --- a/docs/运维配置与集成说明.md +++ b/docs/运维配置与集成说明.md @@ -770,3 +770,49 @@ $env:NACOS_USERNAME='nacos' - API 代理:`/api/` 和 `/admin/api/` 均代理到 `jayu_cloud_gateway`。 - 当前证书状态:`/etc/letsencrypt/live/yunail.art/fullchain.pem` 为 DNS-01 新签发证书,SAN 覆盖 `yunail.art`、`www.yunail.art`、`salon.yunail.art`,有效期至 2026-10-07 06:14:28 UTC。 - 当前续期要求:本次使用手动 DNS-01 TXT 记录签发;后续续期前需保留或重新添加 `_acme-challenge` 记录,或补齐阿里云 DNS API 凭据后改为自动 DNS-01。 + +### MessageHub SPUG 短信模板与兜底发送配置 + +JayuCloud 验证码短信通过 Nacos `messagehub.sms` 配置首发默认通道、设计师端来源系统、店务端来源系统和各供应商通道参数。敏感 token 只放在 Nacos/secret 配置中,本文档只记录配置项,不记录明文。 + +```yaml +messagehub: + client: + base-url: https://messagehub.example.com + sms: + default-channel: ALIYUN + valid-minutes-text: 五 + clients: + designer: + source-system: jayucloud-designer + access-token: ${MESSAGEHUB_DESIGNER_ACCESS_TOKEN} + salon: + source-system: jayucloud-salon + access-token: ${MESSAGEHUB_SALON_ACCESS_TOKEN} + channels: + aliyun: + channel-id: + send-method: OTHER + templates: + USER_LOGIN_SMS_CODE: "100001" + USER_REGISTER_SMS_CODE: "100001" + USER_RESET_PASSWORD_SMS_CODE: "100003" + USER_CHANGE_PHONE_SMS_CODE: "100002" + USER_BIND_PHONE_SMS_CODE: "100004" + USER_VERIFY_BIND_PHONE_SMS_CODE: "100005" + spug: + channel-id: + send-method: SPUG + templates: + USER_LOGIN_SMS_CODE: SPUG_SMS_VERIFY_1 + USER_REGISTER_SMS_CODE: SPUG_SMS_VERIFY_1 + PLANNING_MANAGER_REGISTER: SPUG_SMS_VERIFY_3 +``` + +- `default-channel` 支持 `ALIYUN` 或 `SPUG`,只决定首次发送和无历史记录时的起点。 +- 设计师 Web/小程序分别传 `WEB`、`WECHAT_MINI`,使用 `clients.designer`;店务 Web/小程序分别传 `MANAGER_WEB`、`SALON_WECHAT_MINI`,使用 `clients.salon`。 +- SPUG 设计师端默认使用 `SPUG_SMS_VERIFY_1`,参数为 `name`、`code`、`number`;店务端默认使用 `SPUG_SMS_VERIFY_3`,参数为 `code`、`number`。 +- Core 启动时会校验 `base-url`、设计师/店务来源系统、默认通道和兜底通道 `channel-id`/`send-method`、SPUG `name` 和 `valid-minutes-text`,缺失时启动失败并提示具体配置项。 +- 用户允许重发时,Core 会先用上一条 `messageId` 查询 MessageHub 状态;只有 `SUCCESS` 算成功并沿用上一条通道,`FAILED`、`ACCEPTED`、`PENDING` 或查不到都作废旧验证码并切换到另一个通道。 +- 状态查询发生网络、鉴权或非 not found 业务异常时不生成新验证码,直接返回明确错误,避免不确定状态下重复下发。 +- MessageHub 管理端需要为两个来源系统授予 SMS 权限,并允许阿里云与 SPUG 对应 `channel-id`;SPUG 通道必须已配置 `baseUrl`、`apiKey` 和模板 externalId。 diff --git a/docs/项目变更记录.md b/docs/项目变更记录.md index 838b706f..ca6e90a8 100644 --- a/docs/项目变更记录.md +++ b/docs/项目变更记录.md @@ -96,3 +96,11 @@ - 影响范围:仅影响 Web/Nginx 证书、静态站点按域名分发和 HTTPS 入口;不修改后端 JAR、数据库、Nacos 配置和小程序。 - 验证方式:`nginx -t` 通过并 reload 后保持 `nginx.service active`;公网 HTTPS 正常校验下 `https://yunail.art/` 和 `https://www.yunail.art/` 返回设计师端入口,`https://salon.yunail.art/` 返回店务端入口,`https://salon.yunail.art/health/check` 返回 Jayu Cloud gateway JSON。 - 后续事项:本次为手动 DNS-01 签发,后续续期前需保留或重新添加 `_acme-challenge` TXT 记录,或补齐阿里云 DNS API 凭据改为自动 DNS-01。 + +## 2026-07-10 MessageHub SPUG 短信模板与兜底发送 + +- 变更原因:验证码短信需要在保留阿里云通道的同时接入 SPUG 模板,并按设计师端、店务端拆分 MessageHub 来源系统密钥;重发时需要根据上一条 MessageHub 状态决定沿用或切换通道。 +- 处理方式:新增 `messagehub.sms` Nacos 配置模型、短信通道枚举、端分组枚举、MessageHub 提交结果和状态查询对象;验证码发送接口新增可选 `clientType`,四端发送验证码请求均补传端类型;重发时先查询上一条 `messageId` 状态,`SUCCESS` 沿用上一通道,其余未成功状态切换到另一个通道。 +- 配置说明:配置项已追加到 `docs/运维配置与集成说明.md`,只记录 `source-system`、`channel-id`、模板码和 token 占位,不记录任何 MessageHub access token 明文。 +- 影响范围:JY-Core 验证码发送、MessageHub 客户端、设计师 Web/小程序、店务 Web/小程序发送验证码请求体和店务小程序手机号登录端类型识别;不修改初始化 SQL,不新增数据库表。 +- 验证方式:新增并通过 `MessageHubClientServiceImplTest`、`VerificationCodeServiceImplTest`、`UserServiceImplPermissionAssignmentTest`,覆盖阿里云提交、SPUG 模板 1/3、状态查询、首发不查状态、重发成功沿用、未成功切换、状态查询异常不生成新码和店务小程序端类型识别;已运行 `JY-Core` 全量测试、设计师 Web 构建、店务 Web 构建、小程序 JS 语法检查、GitNexus impact/detect-changes、`git diff --check` 和 MessageHub token 扫描。