对接开发环境MessageHub
This commit is contained in:
+213
-107
@@ -1,171 +1,277 @@
|
||||
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.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.support.id.TimeOrderedSnowflakeIdGenerator;
|
||||
import lombok.Data;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.amqp.core.Message;
|
||||
import org.springframework.amqp.core.MessageBuilder;
|
||||
import org.springframework.amqp.rabbit.core.RabbitTemplate;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.cloud.context.config.annotation.RefreshScope;
|
||||
import org.springframework.core.ParameterizedTypeReference;
|
||||
import org.springframework.http.HttpEntity;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.HttpMethod;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.util.StringUtils;
|
||||
import org.springframework.web.client.RestClientException;
|
||||
import org.springframework.web.client.RestClientResponseException;
|
||||
import org.springframework.web.client.RestTemplate;
|
||||
import org.springframework.web.util.UriComponentsBuilder;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import com.xiaowang.jayucloud.core.common.Result;
|
||||
/**
|
||||
* JayuCloud 到 MessageHub 的投递客户端。
|
||||
*
|
||||
* <p>JayuCloud 只决定某个业务场景使用哪组 MessageHub 对接参数,不直接连接 Spug、
|
||||
* 阿里云等短信供应商。真实通道选择和供应商密钥仍归 MessageHub 管理。</p>
|
||||
*/
|
||||
@Slf4j
|
||||
@Service
|
||||
@RefreshScope
|
||||
@RequiredArgsConstructor
|
||||
public class MessageHubClientServiceImpl implements MessageHubClientService {
|
||||
/**
|
||||
* Variable `rabbitTemplate`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
|
||||
*/
|
||||
private final RabbitTemplate rabbitTemplate;
|
||||
/**
|
||||
* Variable `objectMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
|
||||
*/
|
||||
|
||||
private static final String ACCESS_TOKEN_HEADER = "X-MessageHub-Access-Token";
|
||||
private static final int MAX_SUBMIT_ATTEMPTS = 3;
|
||||
private static final int RESPONSE_BODY_LIMIT = 500;
|
||||
|
||||
private final ObjectMapper objectMapper;
|
||||
/**
|
||||
* Variable `snowflakeIdGenerator`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
|
||||
*/
|
||||
private final TimeOrderedSnowflakeIdGenerator snowflakeIdGenerator;
|
||||
/**
|
||||
* Variable `messageHubPushConfigService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
|
||||
*/
|
||||
private final MessageHubPushConfigService messageHubPushConfigService;
|
||||
/**
|
||||
* 平台品牌文案配置。
|
||||
*/
|
||||
private final RestTemplate restTemplate;
|
||||
private final BrandProperties brandProperties;
|
||||
|
||||
@Value("${messagehub.client.sms-queue:smsQueue}")
|
||||
/**
|
||||
* Purpose: smsQueue supports MessageHubClientServiceImpl.java by holding or executing the sms queue business role.
|
||||
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
|
||||
*/
|
||||
private String smsQueue;
|
||||
@Value("${messagehub.client.base-url:}")
|
||||
private String baseUrl;
|
||||
|
||||
@Value("${messagehub.client.source-system:jayucloud}")
|
||||
/**
|
||||
* Purpose: sourceSystem supports MessageHubClientServiceImpl.java by holding or executing the source system business role.
|
||||
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
|
||||
*/
|
||||
private String sourceSystem;
|
||||
|
||||
@Value("${messagehub.client.verify-template-code:SPUG0001}")
|
||||
/**
|
||||
* Purpose: verifyTemplateCode supports MessageHubClientServiceImpl.java by holding or executing the verify template code business role.
|
||||
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
|
||||
*/
|
||||
@Value("${messagehub.client.access-token:}")
|
||||
private String accessToken;
|
||||
|
||||
@Value("${messagehub.client.verify-template-code:100001}")
|
||||
private String verifyTemplateCode;
|
||||
|
||||
@Value("${messagehub.client.send-method:SPUG}")
|
||||
/**
|
||||
* Purpose: sendMethod supports MessageHubClientServiceImpl.java by holding or executing the send method business role.
|
||||
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
|
||||
*/
|
||||
private String sendMethod;
|
||||
|
||||
@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 code parameter `code` supplied by the caller
|
||||
*/
|
||||
public void 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 USER_LOGIN_SMS_CODE parameter `USER_LOGIN_SMS_CODE` supplied by the caller
|
||||
* @param phone parameter `phone` supplied by the caller
|
||||
* @param code parameter `code` supplied by the caller
|
||||
* @return result consumed by the caller or returned to the frontend
|
||||
*/
|
||||
sendSmsVerificationCode("USER_LOGIN_SMS_CODE", phone, code);
|
||||
}
|
||||
|
||||
@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 sceneCode parameter `sceneCode` supplied by the caller
|
||||
* @param phone parameter `phone` supplied by the caller
|
||||
* @param code parameter `code` supplied by the caller
|
||||
*/
|
||||
public void sendSmsVerificationCode(String sceneCode, String phone, String code) {
|
||||
try {
|
||||
MessageHubPushConfigDO config = messageHubPushConfigService.getEnabledConfig(sceneCode);
|
||||
String messageId = snowflakeIdGenerator.nextIdString();
|
||||
Map<String, Object> messageBody = buildSmsMessageBody(config, sceneCode, phone, code, messageId);
|
||||
String jsonBody = objectMapper.writeValueAsString(messageBody);
|
||||
Message message = MessageBuilder
|
||||
.withBody(jsonBody.getBytes(StandardCharsets.UTF_8))
|
||||
.setContentType("application/json")
|
||||
.setContentEncoding(StandardCharsets.UTF_8.name())
|
||||
.setMessageId(messageId)
|
||||
.build();
|
||||
|
||||
String queueName = config == null ? smsQueue : config.getQueueName();
|
||||
rabbitTemplate.convertAndSend(queueName, message);
|
||||
log.info("短信验证码消息已投递到 MessageHub,sceneCode: {}, phone: {}, queue: {}, sourceSystem: {}, templateCode: {}",
|
||||
sceneCode, phone, queueName, messageBody.get("sourceSystem"), messageBody.get("templateCode"));
|
||||
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 RuntimeException("发送短信验证码失败: " + exception.getMessage(), exception);
|
||||
throw new BusinessException("发送短信验证码失败: " + exception.getMessage(), exception);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Run business method `buildSmsMessageBody`.
|
||||
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
|
||||
* @param config parameter `config` supplied by the caller
|
||||
* @param sceneCode parameter `sceneCode` supplied by the caller
|
||||
* @param phone parameter `phone` supplied by the caller
|
||||
* @param code parameter `code` supplied by the caller
|
||||
* @param messageId parameter `messageId` supplied by the caller
|
||||
* @return private Map<String, Object> result consumed by the caller or returned to the frontend
|
||||
*/
|
||||
private Map<String, Object> buildSmsMessageBody(MessageHubPushConfigDO config, String sceneCode, String phone, String code, String messageId) {
|
||||
private MessageHubSubmitRequest buildSmsMessageBody(MessageHubPushConfigDO config,
|
||||
String sceneCode,
|
||||
String phone,
|
||||
String code,
|
||||
String uniqueId) {
|
||||
String platform = config == null ? "SMS" : config.getPlatform();
|
||||
String resolvedSendMethod = config == null ? sendMethod : config.getSendMethod();
|
||||
String resolvedSendMethod = config == null ? "OTHER" : config.getSendMethod();
|
||||
|
||||
Map<String, Object> messageBody = new HashMap<>();
|
||||
messageBody.put("receiver", phone);
|
||||
messageBody.put("channelType", platform);
|
||||
messageBody.put("platform", platform);
|
||||
messageBody.put("msgType", config == null ? "VERIFICATION" : config.getMsgType());
|
||||
messageBody.put("templateCode", config == null ? verifyTemplateCode : config.getTemplateCode());
|
||||
messageBody.put("sourceSystem", config == null ? sourceSystem : config.getSourceSystem());
|
||||
messageBody.put("uniqueId", messageId);
|
||||
messageBody.put("sendMethod", StringUtils.hasText(resolvedSendMethod) ? resolvedSendMethod : "OTHER");
|
||||
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.setUniqueId(uniqueId);
|
||||
if (config != null && config.getChannelId() != null) {
|
||||
messageBody.put("channelId", config.getChannelId());
|
||||
request.setChannelId(config.getChannelId());
|
||||
}
|
||||
|
||||
Map<String, Object> templateParams = new HashMap<>();
|
||||
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);
|
||||
messageBody.put("templateParams", templateParams);
|
||||
return messageBody;
|
||||
request.setTemplateParams(templateParams);
|
||||
|
||||
Map<String, String> platformParams = new HashMap<>();
|
||||
platformParams.put("sendMethod", StringUtils.hasText(resolvedSendMethod) ? resolvedSendMethod : "OTHER");
|
||||
request.setPlatformParams(platformParams);
|
||||
return request;
|
||||
}
|
||||
|
||||
private MessageHubSubmitResponse submitMessage(MessageHubSubmitRequest request) {
|
||||
requireText(baseUrl, "MessageHub API 地址未配置:messagehub.client.base-url");
|
||||
requireText(accessToken, "MessageHub 来源系统访问令牌未配置:messagehub.client.access-token");
|
||||
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);
|
||||
|
||||
Exception lastException = null;
|
||||
for (int attempt = 1; attempt <= MAX_SUBMIT_ATTEMPTS; attempt++) {
|
||||
try {
|
||||
ResponseEntity<MessageHubApiResponse<MessageHubSubmitResponse>> response = restTemplate.exchange(
|
||||
targetUrl,
|
||||
HttpMethod.POST,
|
||||
entity,
|
||||
new ParameterizedTypeReference<MessageHubApiResponse<MessageHubSubmitResponse>>() {
|
||||
}
|
||||
);
|
||||
return readSubmitResponse(response, request, targetUrl);
|
||||
} catch (RestClientResponseException exception) {
|
||||
lastException = exception;
|
||||
log.warn("MessageHub API 调用失败,attempt: {}, url: {}, sourceSystem: {}, uniqueId: {}, statusCode: {}, responseBody: {}",
|
||||
attempt, targetUrl, request.getSourceSystem(), request.getUniqueId(),
|
||||
exception.getRawStatusCode(), limitText(exception.getResponseBodyAsString()));
|
||||
} catch (RestClientException exception) {
|
||||
lastException = exception;
|
||||
log.warn("MessageHub API 调用失败,attempt: {}, url: {}, sourceSystem: {}, uniqueId: {}, reason: {}",
|
||||
attempt, targetUrl, request.getSourceSystem(), request.getUniqueId(), exception.getMessage());
|
||||
}
|
||||
sleepBeforeRetry(attempt);
|
||||
}
|
||||
throw new BusinessException("MessageHub API 调用失败:url=" + targetUrl
|
||||
+ ", sourceSystem=" + request.getSourceSystem()
|
||||
+ ", uniqueId=" + request.getUniqueId()
|
||||
+ ", reason=" + (lastException == null ? "unknown" : lastException.getMessage()), lastException);
|
||||
}
|
||||
|
||||
private MessageHubSubmitResponse readSubmitResponse(ResponseEntity<MessageHubApiResponse<MessageHubSubmitResponse>> response,
|
||||
MessageHubSubmitRequest request,
|
||||
String targetUrl) {
|
||||
if (!response.getStatusCode().is2xxSuccessful()) {
|
||||
throw new BusinessException("MessageHub API 返回非成功状态:url=" + targetUrl
|
||||
+ ", statusCode=" + response.getStatusCodeValue()
|
||||
+ ", sourceSystem=" + request.getSourceSystem()
|
||||
+ ", uniqueId=" + request.getUniqueId());
|
||||
}
|
||||
MessageHubApiResponse<MessageHubSubmitResponse> body = response.getBody();
|
||||
if (body == null) {
|
||||
throw new BusinessException("MessageHub API 返回空响应:url=" + targetUrl
|
||||
+ ", sourceSystem=" + request.getSourceSystem()
|
||||
+ ", uniqueId=" + request.getUniqueId());
|
||||
}
|
||||
if (body.getCode() != 0) {
|
||||
throw new BusinessException("MessageHub API 返回业务失败:url=" + targetUrl
|
||||
+ ", sourceSystem=" + request.getSourceSystem()
|
||||
+ ", uniqueId=" + request.getUniqueId()
|
||||
+ ", code=" + body.getCode()
|
||||
+ ", message=" + body.getMessage());
|
||||
}
|
||||
MessageHubSubmitResponse data = body.getData();
|
||||
if (data == null || !StringUtils.hasText(data.getMessageId())) {
|
||||
throw new BusinessException("MessageHub API 返回缺少 messageId:url=" + targetUrl
|
||||
+ ", sourceSystem=" + request.getSourceSystem()
|
||||
+ ", uniqueId=" + request.getUniqueId()
|
||||
+ ", response=" + limitText(toJson(body)));
|
||||
}
|
||||
return data;
|
||||
}
|
||||
|
||||
private void sleepBeforeRetry(int attempt) {
|
||||
if (attempt >= MAX_SUBMIT_ATTEMPTS) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
Thread.sleep(200L * attempt);
|
||||
} catch (InterruptedException exception) {
|
||||
Thread.currentThread().interrupt();
|
||||
throw new BusinessException("MessageHub API 重试等待被中断", exception);
|
||||
}
|
||||
}
|
||||
|
||||
private String toJson(Object value) {
|
||||
try {
|
||||
return objectMapper.writeValueAsString(value);
|
||||
} catch (Exception exception) {
|
||||
return String.valueOf(value);
|
||||
}
|
||||
}
|
||||
|
||||
private String limitText(String value) {
|
||||
if (value == null) {
|
||||
return "";
|
||||
}
|
||||
if (value.length() <= RESPONSE_BODY_LIMIT) {
|
||||
return value;
|
||||
}
|
||||
return value.substring(0, RESPONSE_BODY_LIMIT);
|
||||
}
|
||||
|
||||
private void requireText(String value, String message) {
|
||||
if (!StringUtils.hasText(value)) {
|
||||
throw new BusinessException(message);
|
||||
}
|
||||
}
|
||||
|
||||
@Data
|
||||
private static class MessageHubSubmitRequest {
|
||||
|
||||
private String sourceSystem;
|
||||
|
||||
private String platform;
|
||||
|
||||
private String receiver;
|
||||
|
||||
private String msgType;
|
||||
|
||||
private String templateCode;
|
||||
|
||||
private Map<String, String> templateParams = new HashMap<>();
|
||||
|
||||
private Long channelId;
|
||||
|
||||
private String uniqueId;
|
||||
|
||||
private Map<String, String> platformParams = new HashMap<>();
|
||||
}
|
||||
|
||||
@Data
|
||||
private static class MessageHubApiResponse<T> {
|
||||
|
||||
private int code;
|
||||
|
||||
private String message;
|
||||
|
||||
private T data;
|
||||
}
|
||||
|
||||
@Data
|
||||
private static class MessageHubSubmitResponse {
|
||||
|
||||
private String messageId;
|
||||
|
||||
private String sourceSystem;
|
||||
|
||||
private String uniqueId;
|
||||
|
||||
private String platform;
|
||||
|
||||
private String dispatchStatus;
|
||||
|
||||
private boolean idempotentHit;
|
||||
|
||||
private String outboxStatus;
|
||||
}
|
||||
}
|
||||
|
||||
+63
-55
@@ -1,33 +1,31 @@
|
||||
package com.xiaowang.jayucloud.core.modules.integration.service.impl;
|
||||
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.xiaowang.jayucloud.core.config.BrandProperties;
|
||||
import com.xiaowang.jayucloud.core.modules.integration.entity.MessageHubPushConfigDO;
|
||||
import com.xiaowang.jayucloud.core.modules.integration.service.MessageHubPushConfigService;
|
||||
import com.xiaowang.jayucloud.core.support.id.TimeOrderedSnowflakeIdGenerator;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.MockitoAnnotations;
|
||||
import org.springframework.amqp.core.Message;
|
||||
import org.springframework.amqp.rabbit.core.RabbitTemplate;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.test.util.ReflectionTestUtils;
|
||||
import org.springframework.test.web.client.MockRestServiceServer;
|
||||
import org.springframework.web.client.RestTemplate;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.hamcrest.Matchers.is;
|
||||
import static org.mockito.Mockito.when;
|
||||
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;
|
||||
import static org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo;
|
||||
import static org.springframework.test.web.client.response.MockRestResponseCreators.withSuccess;
|
||||
|
||||
class MessageHubClientServiceImplTest {
|
||||
|
||||
private static final long ALIYUN_CHANNEL_ID = 314055468907909120L;
|
||||
|
||||
@Mock
|
||||
private RabbitTemplate rabbitTemplate;
|
||||
private static final String MESSAGEHUB_URL = "http://messagehub.test";
|
||||
private static final String ACCESS_TOKEN = "test-token";
|
||||
|
||||
@Mock
|
||||
private TimeOrderedSnowflakeIdGenerator snowflakeIdGenerator;
|
||||
@@ -38,64 +36,86 @@ class MessageHubClientServiceImplTest {
|
||||
@Mock
|
||||
private BrandProperties brandProperties;
|
||||
|
||||
private final ObjectMapper objectMapper = new ObjectMapper();
|
||||
|
||||
private RestTemplate restTemplate;
|
||||
private MockRestServiceServer mockServer;
|
||||
private MessageHubClientServiceImpl service;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
MockitoAnnotations.openMocks(this);
|
||||
restTemplate = new RestTemplate();
|
||||
mockServer = MockRestServiceServer.createServer(restTemplate);
|
||||
service = new MessageHubClientServiceImpl(
|
||||
rabbitTemplate,
|
||||
objectMapper,
|
||||
new com.fasterxml.jackson.databind.ObjectMapper(),
|
||||
snowflakeIdGenerator,
|
||||
messageHubPushConfigService,
|
||||
restTemplate,
|
||||
brandProperties
|
||||
);
|
||||
ReflectionTestUtils.setField(service, "baseUrl", MESSAGEHUB_URL);
|
||||
ReflectionTestUtils.setField(service, "sourceSystem", "jayucloud");
|
||||
ReflectionTestUtils.setField(service, "accessToken", ACCESS_TOKEN);
|
||||
ReflectionTestUtils.setField(service, "verifyTemplateCode", "100001");
|
||||
when(snowflakeIdGenerator.nextIdString()).thenReturn("sms-message-1");
|
||||
when(brandProperties.getMessageTemplateName()).thenReturn("甲屿云");
|
||||
}
|
||||
|
||||
@Test
|
||||
void registerVerificationMessageIncludesAliyunTemplateParameters() throws Exception {
|
||||
void registerVerificationMessageSubmitsAliyunTemplateToMessageHub() {
|
||||
String sceneCode = "USER_REGISTER_SMS_CODE";
|
||||
when(messageHubPushConfigService.getEnabledConfig(sceneCode))
|
||||
.thenReturn(aliyunConfig(sceneCode, "100001"));
|
||||
expectSubmit("100001", "123456");
|
||||
|
||||
service.sendSmsVerificationCode(sceneCode, "13800138000", "123456");
|
||||
|
||||
Map<String, Object> messageBody = capturedMessageBody();
|
||||
assertThat(messageBody)
|
||||
.containsEntry("templateCode", "100001")
|
||||
.containsEntry("sourceSystem", "jayucloud")
|
||||
.containsEntry("sendMethod", "OTHER");
|
||||
assertThat(((Number) messageBody.get("channelId")).longValue()).isEqualTo(ALIYUN_CHANNEL_ID);
|
||||
|
||||
Map<String, Object> templateParams = templateParams(messageBody);
|
||||
assertThat(templateParams)
|
||||
.containsEntry("code", "123456")
|
||||
.containsEntry("min", "5")
|
||||
.containsEntry("minutes", "5")
|
||||
.containsEntry("number", "5");
|
||||
mockServer.verify();
|
||||
}
|
||||
|
||||
@Test
|
||||
void resetPasswordVerificationMessageUsesResetTemplateWithAliyunParameters() throws Exception {
|
||||
void resetPasswordVerificationMessageUsesResetTemplateWithAliyunParameters() {
|
||||
String sceneCode = "USER_RESET_PASSWORD_SMS_CODE";
|
||||
when(messageHubPushConfigService.getEnabledConfig(sceneCode))
|
||||
.thenReturn(aliyunConfig(sceneCode, "100003"));
|
||||
expectSubmit("100003", "654321");
|
||||
|
||||
service.sendSmsVerificationCode(sceneCode, "13800138000", "654321");
|
||||
|
||||
Map<String, Object> messageBody = capturedMessageBody();
|
||||
assertThat(messageBody).containsEntry("templateCode", "100003");
|
||||
assertThat(((Number) messageBody.get("channelId")).longValue()).isEqualTo(ALIYUN_CHANNEL_ID);
|
||||
mockServer.verify();
|
||||
}
|
||||
|
||||
Map<String, Object> templateParams = templateParams(messageBody);
|
||||
assertThat(templateParams)
|
||||
.containsEntry("code", "654321")
|
||||
.containsEntry("min", "5")
|
||||
.containsEntry("minutes", "5")
|
||||
.containsEntry("number", "5");
|
||||
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")))
|
||||
.andRespond(withSuccess("""
|
||||
{
|
||||
"code": 0,
|
||||
"message": "success",
|
||||
"data": {
|
||||
"messageId": "messagehub-message-1",
|
||||
"sourceSystem": "jayucloud",
|
||||
"uniqueId": "sms-message-1",
|
||||
"platform": "SMS",
|
||||
"dispatchStatus": "ACCEPTED",
|
||||
"idempotentHit": false,
|
||||
"outboxStatus": "PENDING"
|
||||
}
|
||||
}
|
||||
""", MediaType.APPLICATION_JSON));
|
||||
}
|
||||
|
||||
private MessageHubPushConfigDO aliyunConfig(String sceneCode, String templateCode) {
|
||||
@@ -103,7 +123,7 @@ class MessageHubClientServiceImplTest {
|
||||
config.setSceneCode(sceneCode);
|
||||
config.setPlatform("SMS");
|
||||
config.setMsgType("VERIFICATION");
|
||||
config.setQueueName("smsQueue");
|
||||
config.setQueueName("messagehub.ingress.queue");
|
||||
config.setSourceSystem("jayucloud");
|
||||
config.setTemplateCode(templateCode);
|
||||
config.setChannelId(ALIYUN_CHANNEL_ID);
|
||||
@@ -112,16 +132,4 @@ class MessageHubClientServiceImplTest {
|
||||
config.setIsDelete(0);
|
||||
return config;
|
||||
}
|
||||
|
||||
private Map<String, Object> capturedMessageBody() throws Exception {
|
||||
ArgumentCaptor<Message> messageCaptor = ArgumentCaptor.forClass(Message.class);
|
||||
verify(rabbitTemplate).convertAndSend(eq("smsQueue"), messageCaptor.capture());
|
||||
String jsonBody = new String(messageCaptor.getValue().getBody(), StandardCharsets.UTF_8);
|
||||
return objectMapper.readValue(jsonBody, new TypeReference<Map<String, Object>>() {});
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private Map<String, Object> templateParams(Map<String, Object> messageBody) {
|
||||
return (Map<String, Object>) messageBody.get("templateParams");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
# MessageHub开发环境对接配置说明
|
||||
|
||||
## 配置位置
|
||||
|
||||
JayuCloud 开发环境通过 Nacos `JayuCloud-Dev` 命名空间配置 MessageHub:
|
||||
|
||||
- `core.yaml`:配置 `messagehub.client.base-url`
|
||||
- `secret.yaml`:配置 `messagehub.client.access-token`
|
||||
|
||||
## 配置内容
|
||||
|
||||
```yaml
|
||||
messagehub:
|
||||
client:
|
||||
base-url: http://192.168.5.58:8080
|
||||
access-token: <由 MessageHub 来源系统 jayucloud 生成的 X-MessageHub-Access-Token>
|
||||
```
|
||||
|
||||
## MessageHub 管理端要求
|
||||
|
||||
MessageHub 中需要存在并启用来源系统 `jayucloud`,允许平台包含 `SMS`,并配置可用的默认阿里云短信通道。JayuCloud 不再写死短信通道 ID,实际供应商通道由 MessageHub 按来源系统默认通道选择。
|
||||
|
||||
## 数据库配置
|
||||
|
||||
执行 `scripts/sql/migrations/messagehub开发对接/MessageHub开发环境阿里云模板对接_20260705.sql`,将 JayuCloud 六个短信验证码场景切换为 MessageHub 阿里云模板:
|
||||
|
||||
- 注册、登录:`100001`
|
||||
- 找回密码、修改密码:`100003`
|
||||
- 绑定手机号:`100004`
|
||||
- 修改手机号:`100002`
|
||||
|
||||
## 验证方式
|
||||
|
||||
1. 在 JayuCloud 触发登录或注册验证码。
|
||||
2. MessageHub 管理端推送日志中应出现来源系统 `jayucloud`、平台 `SMS`、对应模板码。
|
||||
3. MessageHub outbox 状态应从 `PENDING` 进入已发布或完成状态。
|
||||
@@ -0,0 +1,44 @@
|
||||
-- MessageHub开发环境阿里云模板对接_20260705.sql
|
||||
-- 用途:将 JayuCloud 短信验证码场景切换到 MessageHub 最新 ingress 队列和阿里云短信模板。
|
||||
-- 说明:不修改 0.0.1 初始化 SQL;后续环境通过执行本版本化脚本完成配置迭代。
|
||||
|
||||
START TRANSACTION;
|
||||
|
||||
INSERT INTO `t_messagehub_push_config` (
|
||||
`id`,
|
||||
`scene_code`,
|
||||
`scene_name`,
|
||||
`platform`,
|
||||
`msg_type`,
|
||||
`queue_name`,
|
||||
`source_system`,
|
||||
`template_code`,
|
||||
`channel_id`,
|
||||
`send_method`,
|
||||
`enabled`,
|
||||
`remark`,
|
||||
`create_time`,
|
||||
`update_time`,
|
||||
`is_delete`
|
||||
) VALUES
|
||||
(313931273555137001, 'USER_REGISTER_SMS_CODE', '用户注册验证码', 'SMS', 'VERIFICATION', 'messagehub.ingress.queue', 'jayucloud', '100001', NULL, 'OTHER', 1, '注册功能发送验证码时使用 MessageHub 阿里云登录/注册模板', NOW(), NOW(), 0),
|
||||
(313931273555137002, 'USER_LOGIN_SMS_CODE', '手机号登录验证码', 'SMS', 'VERIFICATION', 'messagehub.ingress.queue', 'jayucloud', '100001', NULL, 'OTHER', 1, '手机号验证码登录时使用 MessageHub 阿里云登录/注册模板', NOW(), NOW(), 0),
|
||||
(313931273555137003, 'USER_RESET_PASSWORD_SMS_CODE', '找回密码验证码', 'SMS', 'VERIFICATION', 'messagehub.ingress.queue', 'jayucloud', '100003', NULL, 'OTHER', 1, '找回密码时使用 MessageHub 阿里云重置密码模板', NOW(), NOW(), 0),
|
||||
(313931273555137004, 'USER_BIND_PHONE_SMS_CODE', '绑定手机号验证码', 'SMS', 'VERIFICATION', 'messagehub.ingress.queue', 'jayucloud', '100004', NULL, 'OTHER', 1, '绑定手机号时使用 MessageHub 阿里云绑定新手机号模板', NOW(), NOW(), 0),
|
||||
(313931273555137005, 'USER_CHANGE_PHONE_SMS_CODE', '修改手机号验证码', 'SMS', 'VERIFICATION', 'messagehub.ingress.queue', 'jayucloud', '100002', NULL, 'OTHER', 1, '修改手机号时使用 MessageHub 阿里云修改绑定手机号模板', NOW(), NOW(), 0),
|
||||
(313931273555137006, 'USER_CHANGE_PASSWORD_SMS_CODE', '修改密码验证码', 'SMS', 'VERIFICATION', 'messagehub.ingress.queue', 'jayucloud', '100003', NULL, 'OTHER', 1, '修改密码时使用 MessageHub 阿里云重置密码模板', NOW(), NOW(), 0)
|
||||
ON DUPLICATE KEY UPDATE
|
||||
`scene_name` = VALUES(`scene_name`),
|
||||
`platform` = VALUES(`platform`),
|
||||
`msg_type` = VALUES(`msg_type`),
|
||||
`queue_name` = VALUES(`queue_name`),
|
||||
`source_system` = VALUES(`source_system`),
|
||||
`template_code` = VALUES(`template_code`),
|
||||
`channel_id` = VALUES(`channel_id`),
|
||||
`send_method` = VALUES(`send_method`),
|
||||
`enabled` = VALUES(`enabled`),
|
||||
`remark` = VALUES(`remark`),
|
||||
`update_time` = NOW(),
|
||||
`is_delete` = 0;
|
||||
|
||||
COMMIT;
|
||||
Reference in New Issue
Block a user