新增 SPUG 短信模板与短信兜底发送

This commit is contained in:
2026-07-10 12:27:35 +08:00
parent f19a609462
commit 58a7932f54
28 changed files with 1125 additions and 206 deletions
@@ -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<String, String> templates = new HashMap<>();
}
}
@@ -22,4 +22,9 @@ public class SendVerificationCodeRequestDTO {
* 业务场景编码,用来选择 JayuCloud 投递 MessageHub 时的配置。
*/
private String sceneCode;
/**
* 客户端类型,用于选择设计师或店务 MessageHub 身份。
*/
private String clientType;
}
@@ -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.
@@ -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;
}
}
@@ -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();
}
@@ -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<Void> entity = new HttpEntity<>(jsonHeaders(client.getAccessToken()));
Exception lastException = null;
for (int attempt = 1; attempt <= MAX_API_ATTEMPTS; attempt++) {
try {
ResponseEntity<MessageHubApiResponse<MessageHubStatusResponse>> response = restTemplate.exchange(
targetUrl,
HttpMethod.GET,
entity,
new ParameterizedTypeReference<MessageHubApiResponse<MessageHubStatusResponse>>() {
}
);
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<String, String> 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<String, String> 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<MessageHubSubmitRequest> entity = new HttpEntity<>(request, headers);
HttpEntity<MessageHubSubmitRequest> 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<MessageHubApiResponse<MessageHubSubmitResponse>> response = restTemplate.exchange(
targetUrl,
@@ -189,8 +271,261 @@ public class MessageHubClientServiceImpl implements MessageHubClientService {
return data;
}
private MessageHubSmsStatusVO readStatusResponse(ResponseEntity<MessageHubApiResponse<MessageHubStatusResponse>> 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<MessageHubStatusResponse> 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<String, String> templateParams(String sceneCode,
String code,
MessageHubSmsClientGroup clientGroup,
MessageHubSmsChannel channel) {
Map<String, String> 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<String, String> platformParams(String sendMethod) {
Map<String, String> 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;
}
}
@@ -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;
}
}
@@ -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);
}
}
@@ -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;
}
@@ -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);
}
}
@@ -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);
}
@@ -1220,6 +1220,7 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> 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<UserMapper, UserDO> 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) {