适配MessageHub正式ingress投递
This commit is contained in:
@@ -51,8 +51,6 @@ public class MessageHubSmsProperties {
|
||||
|
||||
private Long channelId;
|
||||
|
||||
private String sendMethod;
|
||||
|
||||
private Map<String, String> templates = new HashMap<>();
|
||||
}
|
||||
}
|
||||
|
||||
+129
-41
@@ -15,6 +15,11 @@ import com.xiaowang.jayucloud.core.support.id.TimeOrderedSnowflakeIdGenerator;
|
||||
import lombok.Data;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.amqp.AmqpException;
|
||||
import org.springframework.amqp.core.Message;
|
||||
import org.springframework.amqp.core.MessageBuilder;
|
||||
import org.springframework.amqp.core.MessageProperties;
|
||||
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;
|
||||
@@ -31,6 +36,8 @@ import org.springframework.web.client.RestTemplate;
|
||||
import org.springframework.web.util.UriComponentsBuilder;
|
||||
|
||||
import javax.annotation.PostConstruct;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Date;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
@@ -52,11 +59,14 @@ public class MessageHubClientServiceImpl implements MessageHubClientService {
|
||||
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 static final String DEFAULT_INGRESS_EXCHANGE = "messagehub.ingress.exchange";
|
||||
private static final String DEFAULT_INGRESS_ROUTING_KEY = "message.send";
|
||||
|
||||
private final ObjectMapper objectMapper;
|
||||
private final TimeOrderedSnowflakeIdGenerator snowflakeIdGenerator;
|
||||
private final MessageHubPushConfigService messageHubPushConfigService;
|
||||
private final RestTemplate restTemplate;
|
||||
private final RabbitTemplate rabbitTemplate;
|
||||
private final BrandProperties brandProperties;
|
||||
private final MessageHubSmsProperties smsProperties;
|
||||
|
||||
@@ -72,9 +82,17 @@ public class MessageHubClientServiceImpl implements MessageHubClientService {
|
||||
@Value("${messagehub.client.verify-template-code:100001}")
|
||||
private String legacyVerifyTemplateCode;
|
||||
|
||||
@Value("${messagehub.ingress.exchange:messagehub.ingress.exchange}")
|
||||
private String ingressExchange;
|
||||
|
||||
@Value("${messagehub.ingress.routing-key:message.send}")
|
||||
private String ingressRoutingKey;
|
||||
|
||||
@PostConstruct
|
||||
public void validateStartupConfiguration() {
|
||||
requireText(baseUrl, "MessageHub API 地址未配置:messagehub.client.base-url");
|
||||
requireText(resolveIngressExchange(), "MessageHub ingress exchange 未配置:messagehub.ingress.exchange");
|
||||
requireText(resolveIngressRoutingKey(), "MessageHub ingress routing-key 未配置:messagehub.ingress.routing-key");
|
||||
MessageHubSmsChannel defaultChannel = MessageHubSmsChannel.fromCode(smsProperties.getDefaultChannel(), MessageHubSmsChannel.ALIYUN);
|
||||
requireChannelConfig(defaultChannel);
|
||||
requireChannelConfig(defaultChannel.opposite());
|
||||
@@ -197,78 +215,130 @@ public class MessageHubClientServiceImpl implements MessageHubClientService {
|
||||
request.setUniqueId(uniqueId);
|
||||
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, String token) {
|
||||
requireText(baseUrl, "MessageHub API 地址未配置:messagehub.client.base-url");
|
||||
requireText(token, "MessageHub 来源系统访问令牌未配置");
|
||||
String messageId = reserveMessageId(request, token);
|
||||
request.setMessageId(messageId);
|
||||
publishIngressMessage(request, token);
|
||||
return acceptedSubmitResponse(request);
|
||||
}
|
||||
|
||||
private String reserveMessageId(MessageHubSubmitRequest request, String token) {
|
||||
String targetUrl = UriComponentsBuilder.fromHttpUrl(baseUrl.trim())
|
||||
.path("/api/v1/messages")
|
||||
.path("/api/v1/messages/ids")
|
||||
.build()
|
||||
.toUriString();
|
||||
HttpEntity<MessageHubSubmitRequest> entity = new HttpEntity<>(request, jsonHeaders(token));
|
||||
MessageHubMessageIdReserveRequest reserveRequest = new MessageHubMessageIdReserveRequest();
|
||||
reserveRequest.setSourceSystem(request.getSourceSystem());
|
||||
HttpEntity<MessageHubMessageIdReserveRequest> entity = new HttpEntity<>(reserveRequest, jsonHeaders(token));
|
||||
|
||||
Exception lastException = null;
|
||||
for (int attempt = 1; attempt <= MAX_API_ATTEMPTS; attempt++) {
|
||||
try {
|
||||
ResponseEntity<MessageHubApiResponse<MessageHubSubmitResponse>> response = restTemplate.exchange(
|
||||
ResponseEntity<MessageHubApiResponse<MessageHubMessageIdReserveResponse>> response = restTemplate.exchange(
|
||||
targetUrl,
|
||||
HttpMethod.POST,
|
||||
entity,
|
||||
new ParameterizedTypeReference<MessageHubApiResponse<MessageHubSubmitResponse>>() {
|
||||
new ParameterizedTypeReference<MessageHubApiResponse<MessageHubMessageIdReserveResponse>>() {
|
||||
}
|
||||
);
|
||||
return readSubmitResponse(response, request, targetUrl);
|
||||
return readReservedMessageId(response, request, targetUrl);
|
||||
} catch (RestClientResponseException exception) {
|
||||
lastException = exception;
|
||||
log.warn("MessageHub API 调用失败,attempt: {}, url: {}, sourceSystem: {}, uniqueId: {}, statusCode: {}, responseBody: {}",
|
||||
log.warn("MessageHub messageId 预取失败,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: {}",
|
||||
log.warn("MessageHub messageId 预取失败,attempt: {}, url: {}, sourceSystem: {}, uniqueId: {}, reason: {}",
|
||||
attempt, targetUrl, request.getSourceSystem(), request.getUniqueId(), exception.getMessage());
|
||||
}
|
||||
sleepBeforeRetry(attempt);
|
||||
}
|
||||
throw new BusinessException("MessageHub API 调用失败:url=" + targetUrl
|
||||
throw new BusinessException("MessageHub messageId 预取失败: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) {
|
||||
private String readReservedMessageId(ResponseEntity<MessageHubApiResponse<MessageHubMessageIdReserveResponse>> response,
|
||||
MessageHubSubmitRequest request,
|
||||
String targetUrl) {
|
||||
if (!response.getStatusCode().is2xxSuccessful()) {
|
||||
throw new BusinessException("MessageHub API 返回非成功状态:url=" + targetUrl
|
||||
throw new BusinessException("MessageHub messageId 预取返回非成功状态:url=" + targetUrl
|
||||
+ ", statusCode=" + response.getStatusCodeValue()
|
||||
+ ", sourceSystem=" + request.getSourceSystem()
|
||||
+ ", uniqueId=" + request.getUniqueId());
|
||||
}
|
||||
MessageHubApiResponse<MessageHubSubmitResponse> body = response.getBody();
|
||||
MessageHubApiResponse<MessageHubMessageIdReserveResponse> body = response.getBody();
|
||||
if (body == null) {
|
||||
throw new BusinessException("MessageHub API 返回空响应:url=" + targetUrl
|
||||
throw new BusinessException("MessageHub messageId 预取返回空响应:url=" + targetUrl
|
||||
+ ", sourceSystem=" + request.getSourceSystem()
|
||||
+ ", uniqueId=" + request.getUniqueId());
|
||||
}
|
||||
if (body.getCode() != 0) {
|
||||
throw new BusinessException("MessageHub API 返回业务失败:url=" + targetUrl
|
||||
throw new BusinessException("MessageHub messageId 预取返回业务失败:url=" + targetUrl
|
||||
+ ", sourceSystem=" + request.getSourceSystem()
|
||||
+ ", uniqueId=" + request.getUniqueId()
|
||||
+ ", code=" + body.getCode()
|
||||
+ ", message=" + body.getMessage());
|
||||
}
|
||||
MessageHubSubmitResponse data = body.getData();
|
||||
MessageHubMessageIdReserveResponse data = body.getData();
|
||||
if (data == null || !StringUtils.hasText(data.getMessageId())) {
|
||||
throw new BusinessException("MessageHub API 返回缺少 messageId:url=" + targetUrl
|
||||
throw new BusinessException("MessageHub messageId 预取返回缺少 messageId:url=" + targetUrl
|
||||
+ ", sourceSystem=" + request.getSourceSystem()
|
||||
+ ", uniqueId=" + request.getUniqueId()
|
||||
+ ", response=" + limitText(toJson(body)));
|
||||
}
|
||||
return data;
|
||||
return data.getMessageId();
|
||||
}
|
||||
|
||||
private void publishIngressMessage(MessageHubSubmitRequest request, String token) {
|
||||
String exchange = resolveIngressExchange();
|
||||
String routingKey = resolveIngressRoutingKey();
|
||||
byte[] body = writeMessageBody(request);
|
||||
Message message = MessageBuilder.withBody(body)
|
||||
.setContentType(MessageProperties.CONTENT_TYPE_JSON)
|
||||
.setMessageId(request.getMessageId())
|
||||
.setTimestamp(new Date())
|
||||
.build();
|
||||
message.getMessageProperties().setContentEncoding(StandardCharsets.UTF_8.name());
|
||||
message.getMessageProperties().setHeader(ACCESS_TOKEN_HEADER, token.trim());
|
||||
|
||||
Exception lastException = null;
|
||||
for (int attempt = 1; attempt <= MAX_API_ATTEMPTS; attempt++) {
|
||||
try {
|
||||
rabbitTemplate.send(exchange, routingKey, message);
|
||||
return;
|
||||
} catch (AmqpException exception) {
|
||||
lastException = exception;
|
||||
log.warn("MessageHub ingress MQ 投递失败,attempt: {}, exchange: {}, routingKey: {}, sourceSystem: {}, uniqueId: {}, messageId: {}, reason: {}",
|
||||
attempt, exchange, routingKey, request.getSourceSystem(), request.getUniqueId(),
|
||||
request.getMessageId(), exception.getMessage());
|
||||
}
|
||||
sleepBeforeRetry(attempt);
|
||||
}
|
||||
throw new BusinessException("MessageHub ingress MQ 投递失败:exchange=" + exchange
|
||||
+ ", routingKey=" + routingKey
|
||||
+ ", sourceSystem=" + request.getSourceSystem()
|
||||
+ ", uniqueId=" + request.getUniqueId()
|
||||
+ ", messageId=" + request.getMessageId()
|
||||
+ ", reason=" + (lastException == null ? "unknown" : lastException.getMessage()), lastException);
|
||||
}
|
||||
|
||||
private MessageHubSubmitResponse acceptedSubmitResponse(MessageHubSubmitRequest request) {
|
||||
MessageHubSubmitResponse response = new MessageHubSubmitResponse();
|
||||
response.setMessageId(request.getMessageId());
|
||||
response.setSourceSystem(request.getSourceSystem());
|
||||
response.setUniqueId(request.getUniqueId());
|
||||
response.setPlatform(request.getPlatform());
|
||||
response.setDispatchStatus("ACCEPTED");
|
||||
response.setOutboxStatus("PENDING");
|
||||
return response;
|
||||
}
|
||||
|
||||
private MessageHubSmsStatusVO readStatusResponse(ResponseEntity<MessageHubApiResponse<MessageHubStatusResponse>> response,
|
||||
@@ -369,7 +439,6 @@ public class MessageHubClientServiceImpl implements MessageHubClientService {
|
||||
if (channelConfig.getChannelId() == null) {
|
||||
throw new BusinessException("MessageHub " + channel.name() + " 短信通道 channelId 未配置");
|
||||
}
|
||||
requireText(channelConfig.getSendMethod(), "MessageHub " + channel.name() + " 短信通道 sendMethod 未配置");
|
||||
}
|
||||
|
||||
private String resolveTemplateCode(String sceneCode,
|
||||
@@ -407,21 +476,6 @@ public class MessageHubClientServiceImpl implements MessageHubClientService {
|
||||
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();
|
||||
@@ -455,12 +509,6 @@ public class MessageHubClientServiceImpl implements MessageHubClientService {
|
||||
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);
|
||||
@@ -469,6 +517,20 @@ public class MessageHubClientServiceImpl implements MessageHubClientService {
|
||||
return headers;
|
||||
}
|
||||
|
||||
private String resolveIngressExchange() {
|
||||
if (StringUtils.hasText(ingressExchange)) {
|
||||
return ingressExchange.trim();
|
||||
}
|
||||
return DEFAULT_INGRESS_EXCHANGE;
|
||||
}
|
||||
|
||||
private String resolveIngressRoutingKey() {
|
||||
if (StringUtils.hasText(ingressRoutingKey)) {
|
||||
return ingressRoutingKey.trim();
|
||||
}
|
||||
return DEFAULT_INGRESS_ROUTING_KEY;
|
||||
}
|
||||
|
||||
private String normalizeSceneCode(String sceneCode) {
|
||||
if (!StringUtils.hasText(sceneCode)) {
|
||||
return "";
|
||||
@@ -542,6 +604,16 @@ public class MessageHubClientServiceImpl implements MessageHubClientService {
|
||||
}
|
||||
}
|
||||
|
||||
private byte[] writeMessageBody(MessageHubSubmitRequest request) {
|
||||
try {
|
||||
return objectMapper.writeValueAsBytes(request);
|
||||
} catch (Exception exception) {
|
||||
throw new BusinessException("MessageHub ingress 消息序列化失败:sourceSystem=" + request.getSourceSystem()
|
||||
+ ", uniqueId=" + request.getUniqueId()
|
||||
+ ", messageId=" + request.getMessageId(), exception);
|
||||
}
|
||||
}
|
||||
|
||||
private String limitText(String value) {
|
||||
if (value == null) {
|
||||
return "";
|
||||
@@ -561,6 +633,8 @@ public class MessageHubClientServiceImpl implements MessageHubClientService {
|
||||
@Data
|
||||
private static class MessageHubSubmitRequest {
|
||||
|
||||
private String messageId;
|
||||
|
||||
private String sourceSystem;
|
||||
|
||||
private String platform;
|
||||
@@ -580,6 +654,20 @@ public class MessageHubClientServiceImpl implements MessageHubClientService {
|
||||
private Map<String, String> platformParams = new HashMap<>();
|
||||
}
|
||||
|
||||
@Data
|
||||
private static class MessageHubMessageIdReserveRequest {
|
||||
|
||||
private String sourceSystem;
|
||||
}
|
||||
|
||||
@Data
|
||||
private static class MessageHubMessageIdReserveResponse {
|
||||
|
||||
private String messageId;
|
||||
|
||||
private String dispatchStatus;
|
||||
}
|
||||
|
||||
@Data
|
||||
private static class MessageHubApiResponse<T> {
|
||||
|
||||
|
||||
+89
-63
@@ -1,5 +1,6 @@
|
||||
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.config.MessageHubSmsProperties;
|
||||
@@ -11,17 +12,27 @@ 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;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.MockitoAnnotations;
|
||||
import org.springframework.amqp.core.Message;
|
||||
import org.springframework.amqp.core.MessageProperties;
|
||||
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.hamcrest.Matchers.is;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.verify;
|
||||
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;
|
||||
@@ -45,6 +56,10 @@ class MessageHubClientServiceImplTest {
|
||||
@Mock
|
||||
private BrandProperties brandProperties;
|
||||
|
||||
@Mock
|
||||
private RabbitTemplate rabbitTemplate;
|
||||
|
||||
private ObjectMapper objectMapper;
|
||||
private RestTemplate restTemplate;
|
||||
private MockRestServiceServer mockServer;
|
||||
private MessageHubClientServiceImpl service;
|
||||
@@ -52,13 +67,15 @@ class MessageHubClientServiceImplTest {
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
MockitoAnnotations.openMocks(this);
|
||||
objectMapper = new ObjectMapper();
|
||||
restTemplate = new RestTemplate();
|
||||
mockServer = MockRestServiceServer.createServer(restTemplate);
|
||||
service = new MessageHubClientServiceImpl(
|
||||
new ObjectMapper(),
|
||||
objectMapper,
|
||||
snowflakeIdGenerator,
|
||||
messageHubPushConfigService,
|
||||
restTemplate,
|
||||
rabbitTemplate,
|
||||
brandProperties,
|
||||
smsProperties()
|
||||
);
|
||||
@@ -67,40 +84,76 @@ class MessageHubClientServiceImplTest {
|
||||
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("JayuCloud");
|
||||
}
|
||||
|
||||
@Test
|
||||
void registerVerificationMessageSubmitsAliyunTemplateToMessageHub() {
|
||||
void registerVerificationMessageSubmitsAliyunTemplateToMessageHub() throws Exception {
|
||||
String sceneCode = "USER_REGISTER_SMS_CODE";
|
||||
when(messageHubPushConfigService.getEnabledConfig(sceneCode))
|
||||
.thenReturn(aliyunConfig(sceneCode, "100001"));
|
||||
expectAliyunSubmit("100001", "123456");
|
||||
expectMessageIdReserve("jayucloud-designer", DESIGNER_TOKEN);
|
||||
|
||||
service.sendSmsVerificationCode(sceneCode, "13800138000", "123456", "WEB", MessageHubSmsChannel.ALIYUN);
|
||||
|
||||
Map<String, Object> body = verifyPublishedMessage(DESIGNER_TOKEN);
|
||||
assertEquals("messagehub-message-1", body.get("messageId"));
|
||||
assertEquals("jayucloud-designer", body.get("sourceSystem"));
|
||||
assertEquals("SMS", body.get("platform"));
|
||||
assertEquals("13800138000", body.get("receiver"));
|
||||
assertEquals("VERIFICATION", body.get("msgType"));
|
||||
assertEquals("100001", body.get("templateCode"));
|
||||
assertEquals(ALIYUN_CHANNEL_ID, ((Number) body.get("channelId")).longValue());
|
||||
assertEquals("sms-message-1", body.get("uniqueId"));
|
||||
Map<?, ?> templateParams = mapAt(body, "templateParams");
|
||||
assertEquals("JayuCloud", templateParams.get("name"));
|
||||
assertEquals("123456", templateParams.get("code"));
|
||||
assertEquals("5", templateParams.get("min"));
|
||||
assertEquals("5", templateParams.get("minutes"));
|
||||
assertEquals("5", templateParams.get("number"));
|
||||
assertNoSendMethod(body);
|
||||
mockServer.verify();
|
||||
}
|
||||
|
||||
@Test
|
||||
void designerSpugVerificationMessageUsesTemplateOne() {
|
||||
void designerSpugVerificationMessageUsesTemplateOne() throws Exception {
|
||||
String sceneCode = "USER_LOGIN_SMS_CODE";
|
||||
when(messageHubPushConfigService.getEnabledConfig(sceneCode)).thenReturn(null);
|
||||
expectDesignerSpugSubmit(sceneCode, "123456");
|
||||
expectMessageIdReserve("jayucloud-designer", DESIGNER_TOKEN);
|
||||
|
||||
service.sendSmsVerificationCode(sceneCode, "13800138000", "123456", "WEB", MessageHubSmsChannel.SPUG);
|
||||
|
||||
Map<String, Object> body = verifyPublishedMessage(DESIGNER_TOKEN);
|
||||
assertEquals("jayucloud-designer", body.get("sourceSystem"));
|
||||
assertEquals("SPUG_SMS_VERIFY_1", body.get("templateCode"));
|
||||
assertEquals(SPUG_CHANNEL_ID, ((Number) body.get("channelId")).longValue());
|
||||
Map<?, ?> templateParams = mapAt(body, "templateParams");
|
||||
assertEquals("JayuCloud", templateParams.get("name"));
|
||||
assertEquals("123456", templateParams.get("code"));
|
||||
assertEquals("5", templateParams.get("number"));
|
||||
assertFalse(templateParams.containsKey("sceneCode"));
|
||||
assertNoSendMethod(body);
|
||||
mockServer.verify();
|
||||
}
|
||||
|
||||
@Test
|
||||
void salonSpugVerificationMessageUsesTemplateThreeWithName() {
|
||||
void salonSpugVerificationMessageUsesTemplateThreeWithName() throws Exception {
|
||||
String sceneCode = "USER_LOGIN_SMS_CODE";
|
||||
when(messageHubPushConfigService.getEnabledConfig(sceneCode)).thenReturn(null);
|
||||
expectSalonSpugSubmit(sceneCode, "654321");
|
||||
expectMessageIdReserve("jayucloud-salon", SALON_TOKEN);
|
||||
|
||||
service.sendSmsVerificationCode(sceneCode, "13800138000", "654321", "MANAGER_WEB", MessageHubSmsChannel.SPUG);
|
||||
|
||||
Map<String, Object> body = verifyPublishedMessage(SALON_TOKEN);
|
||||
assertEquals("jayucloud-salon", body.get("sourceSystem"));
|
||||
assertEquals("SPUG_SMS_VERIFY_3", body.get("templateCode"));
|
||||
assertEquals(SPUG_CHANNEL_ID, ((Number) body.get("channelId")).longValue());
|
||||
Map<?, ?> templateParams = mapAt(body, "templateParams");
|
||||
assertEquals("JayuCloud", templateParams.get("name"));
|
||||
assertEquals("654321", templateParams.get("code"));
|
||||
assertEquals("5", templateParams.get("number"));
|
||||
assertFalse(templateParams.containsKey("sceneCode"));
|
||||
assertNoSendMethod(body);
|
||||
mockServer.verify();
|
||||
}
|
||||
|
||||
@@ -132,69 +185,45 @@ class MessageHubClientServiceImplTest {
|
||||
mockServer.verify();
|
||||
}
|
||||
|
||||
private void expectAliyunSubmit(String templateCode, String code) {
|
||||
mockServer.expect(requestTo(MESSAGEHUB_URL + "/api/v1/messages"))
|
||||
private void expectMessageIdReserve(String sourceSystem, String accessToken) {
|
||||
mockServer.expect(requestTo(MESSAGEHUB_URL + "/api/v1/messages/ids"))
|
||||
.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());
|
||||
.andExpect(header("X-MessageHub-Access-Token", accessToken))
|
||||
.andExpect(jsonPath("$.sourceSystem", is(sourceSystem)))
|
||||
.andRespond(messageIdReserved());
|
||||
}
|
||||
|
||||
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 Map<String, Object> verifyPublishedMessage(String accessToken) throws Exception {
|
||||
ArgumentCaptor<Message> messageCaptor = ArgumentCaptor.forClass(Message.class);
|
||||
verify(rabbitTemplate).send(eq("messagehub.ingress.exchange"), eq("message.send"), messageCaptor.capture());
|
||||
Message message = messageCaptor.getValue();
|
||||
assertEquals("messagehub-message-1", message.getMessageProperties().getMessageId());
|
||||
assertEquals(MessageProperties.CONTENT_TYPE_JSON, message.getMessageProperties().getContentType());
|
||||
assertEquals(StandardCharsets.UTF_8.name(), message.getMessageProperties().getContentEncoding());
|
||||
assertEquals(accessToken, message.getMessageProperties().getHeaders().get("X-MessageHub-Access-Token"));
|
||||
String body = new String(message.getBody(), StandardCharsets.UTF_8);
|
||||
return objectMapper.readValue(body, new TypeReference<Map<String, Object>>() {
|
||||
});
|
||||
}
|
||||
|
||||
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.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 Map<?, ?> mapAt(Map<String, Object> body, String key) {
|
||||
Object value = body.get(key);
|
||||
assertTrue(value instanceof Map);
|
||||
return (Map<?, ?>) value;
|
||||
}
|
||||
|
||||
private org.springframework.test.web.client.ResponseCreator successSubmit() {
|
||||
private void assertNoSendMethod(Map<String, Object> body) {
|
||||
assertFalse(mapAt(body, "platformParams").containsKey("sendMethod"));
|
||||
}
|
||||
|
||||
private org.springframework.test.web.client.ResponseCreator messageIdReserved() {
|
||||
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"
|
||||
"dispatchStatus": "ACCEPTED"
|
||||
}
|
||||
}
|
||||
""", MediaType.APPLICATION_JSON);
|
||||
@@ -209,7 +238,6 @@ class MessageHubClientServiceImplTest {
|
||||
config.setSourceSystem("jayucloud");
|
||||
config.setTemplateCode(templateCode);
|
||||
config.setChannelId(ALIYUN_CHANNEL_ID);
|
||||
config.setSendMethod("OTHER");
|
||||
config.setEnabled(1);
|
||||
config.setIsDelete(0);
|
||||
return config;
|
||||
@@ -218,15 +246,13 @@ class MessageHubClientServiceImplTest {
|
||||
private MessageHubSmsProperties smsProperties() {
|
||||
MessageHubSmsProperties properties = new MessageHubSmsProperties();
|
||||
properties.setDefaultChannel("ALIYUN");
|
||||
properties.setValidMinutesText("五");
|
||||
properties.setValidMinutesText("5");
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user