AliSmsHttpClient.java
2.74 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package com.diligrp.cashier.assistant.client;
import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.dysmsapi20170525.models.SendSmsResponseBody;
import com.aliyun.teaopenapi.models.Config;
import com.diligrp.cashier.assistant.domain.SmsMessage;
import com.diligrp.cashier.assistant.exception.AssistantServiceException;
import com.diligrp.cashier.shared.ErrorCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Objects;
import java.util.stream.Collectors;
public class AliSmsHttpClient {
private static final Logger LOGGER = LoggerFactory.getLogger(AliSmsHttpClient.class);
private final Client client;
public AliSmsHttpClient(String endPoint, String accessKeyId, String accessKeySecret) {
Config config = new Config().setAccessKeyId(accessKeyId).setAccessKeySecret(accessKeySecret);
config.endpoint = endPoint;
try {
this.client = new Client(config);
} catch (Exception e) {
throw new AssistantServiceException(ErrorCode.SERVICE_ACCESS_ERROR, "阿里云短信通道初始化错误");
}
}
public String sendSmsMessage(SmsMessage message) {
String telephones = message.getTelephones().stream().reduce((telephone1, telephone2) ->
"".concat(telephone1).concat(",").concat(telephone2)).get();
SendSmsRequest request = new SendSmsRequest();
request.setPhoneNumbers(telephones);
request.setSignName(message.getSignature());
request.setTemplateCode(message.getTemplateId());
if (Objects.nonNull(message.getParams())) {
String json = message.getParams().entrySet().stream()
.filter(p -> Objects.nonNull(p.getKey()) && Objects.nonNull(p.getValue()))
.map(p -> String.format("\"%s\": \"%s\"", p.getKey(), p.getValue()))
.collect(Collectors.joining(",", "{", "}"));
request.setTemplateParam(json);
}
SendSmsResponse response;
try {
response = this.client.sendSms(request);
} catch (Exception ex) {
LOGGER.error("Failed to send ali sms message", ex);
throw new AssistantServiceException(ErrorCode.SERVICE_ACCESS_ERROR, "发送短信失败: 未知错误");
}
SendSmsResponseBody body = response.getBody();
if ("OK".equalsIgnoreCase(body.getCode())) {
return body.getBizId();
} else {
LOGGER.error("Failed to send ali sms message, {}:{}", body.getCode(), body.getMessage());
throw new AssistantServiceException(ErrorCode.SERVICE_ACCESS_ERROR, "发送短信失败: " + body.getMessage());
}
}
}