Commit 2dd66847cfe5affca733de4a281e9eaba395b343

Authored by YunaiV
2 parents 7ba3b123 22ff197f

Merge branch 'develop' of https://gitee.com/scholarli/ruoyi-vue-pro_1 into develop

# Conflicts:
#	yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/framework/sms/core/client/impl/HuaweiSmsClient.java
yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/framework/sms/core/client/impl/AliyunSmsClient.java
1 1 package cn.iocoder.yudao.module.system.framework.sms.core.client.impl;
2 2  
3 3 import cn.hutool.core.lang.Assert;
  4 +import cn.hutool.core.util.HexUtil;
  5 +import cn.hutool.core.util.URLUtil;
  6 +import cn.hutool.crypto.SecureUtil;
  7 +import cn.hutool.crypto.digest.DigestUtil;
  8 +import cn.hutool.http.HttpRequest;
  9 +import cn.hutool.http.HttpResponse;
  10 +import cn.hutool.json.JSONObject;
  11 +import cn.hutool.json.JSONUtil;
4 12 import cn.iocoder.yudao.framework.common.core.KeyValue;
5 13 import cn.iocoder.yudao.framework.common.util.collection.MapUtils;
6 14 import cn.iocoder.yudao.framework.common.util.json.JsonUtils;
... ... @@ -9,27 +17,23 @@ import cn.iocoder.yudao.module.system.framework.sms.core.client.dto.SmsSendRespD
9 17 import cn.iocoder.yudao.module.system.framework.sms.core.client.dto.SmsTemplateRespDTO;
10 18 import cn.iocoder.yudao.module.system.framework.sms.core.enums.SmsTemplateAuditStatusEnum;
11 19 import cn.iocoder.yudao.module.system.framework.sms.core.property.SmsChannelProperties;
12   -import com.aliyuncs.DefaultAcsClient;
13   -import com.aliyuncs.IAcsClient;
14   -import com.aliyuncs.dysmsapi.model.v20170525.QuerySmsTemplateRequest;
15   -import com.aliyuncs.dysmsapi.model.v20170525.QuerySmsTemplateResponse;
16   -import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
17   -import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
18   -import com.aliyuncs.profile.DefaultProfile;
19   -import com.aliyuncs.profile.IClientProfile;
20 20 import com.fasterxml.jackson.annotation.JsonFormat;
21 21 import com.fasterxml.jackson.annotation.JsonProperty;
22 22 import com.google.common.annotations.VisibleForTesting;
23 23 import lombok.Data;
24 24 import lombok.extern.slf4j.Slf4j;
25 25  
  26 +import java.io.IOException;
  27 +import java.io.UnsupportedEncodingException;
  28 +import java.net.URISyntaxException;
  29 +import java.net.URLEncoder;
26 30 import java.time.LocalDateTime;
27   -import java.util.List;
28   -import java.util.Objects;
  31 +import java.util.*;
29 32  
30 33 import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertList;
31 34 import static cn.iocoder.yudao.framework.common.util.date.DateUtils.FORMAT_YEAR_MONTH_DAY_HOUR_MINUTE_SECOND;
32 35 import static cn.iocoder.yudao.framework.common.util.date.DateUtils.TIME_ZONE_DEFAULT;
  36 +import java.text.SimpleDateFormat;
33 37  
34 38 /**
35 39 * 阿里短信客户端的实现类
... ... @@ -40,21 +44,6 @@ import static cn.iocoder.yudao.framework.common.util.date.DateUtils.TIME_ZONE_DE
40 44 @Slf4j
41 45 public class AliyunSmsClient extends AbstractSmsClient {
42 46  
43   - /**
44   - * 调用成功 code
45   - */
46   - public static final String API_CODE_SUCCESS = "OK";
47   -
48   - /**
49   - * REGION, 使用杭州
50   - */
51   - private static final String ENDPOINT = "cn-hangzhou";
52   -
53   - /**
54   - * 阿里云客户端
55   - */
56   - private volatile IAcsClient client;
57   -
58 47 public AliyunSmsClient(SmsChannelProperties properties) {
59 48 super(properties);
60 49 Assert.notEmpty(properties.getApiKey(), "apiKey 不能为空");
... ... @@ -63,24 +52,116 @@ public class AliyunSmsClient extends AbstractSmsClient {
63 52  
64 53 @Override
65 54 protected void doInit() {
66   - IClientProfile profile = DefaultProfile.getProfile(ENDPOINT, properties.getApiKey(), properties.getApiSecret());
67   - client = new DefaultAcsClient(profile);
  55 +// IClientProfile profile = DefaultProfile.getProfile(ENDPOINT, properties.getApiKey(), properties.getApiSecret());
  56 +// client = new DefaultAcsClient(profile);
68 57 }
69 58  
70 59 @Override
71 60 public SmsSendRespDTO sendSms(Long sendLogId, String mobile, String apiTemplateId,
72 61 List<KeyValue<String, Object>> templateParams) throws Throwable {
73   - // 构建请求
74   - SendSmsRequest request = new SendSmsRequest();
75   - request.setPhoneNumbers(mobile);
76   - request.setSignName(properties.getSignature());
77   - request.setTemplateCode(apiTemplateId);
78   - request.setTemplateParam(JsonUtils.toJsonString(MapUtils.convertMap(templateParams)));
79   - request.setOutId(String.valueOf(sendLogId));
80   - // 执行请求
81   - SendSmsResponse response = client.getAcsResponse(request);
82   - return new SmsSendRespDTO().setSuccess(Objects.equals(response.getCode(), API_CODE_SUCCESS)).setSerialNo(response.getBizId())
83   - .setApiRequestId(response.getRequestId()).setApiCode(response.getCode()).setApiMsg(response.getMessage());
  62 +
  63 + TreeMap<String, Object> queryParam = new TreeMap<>();
  64 + queryParam.put("PhoneNumbers",mobile);
  65 + queryParam.put("SignName",properties.getSignature());
  66 + queryParam.put("TemplateCode",apiTemplateId);
  67 + queryParam.put("TemplateParam",JsonUtils.toJsonString(MapUtils.convertMap(templateParams)));
  68 +
  69 + JSONObject response = sendSmsRequest(queryParam,"sendSms");
  70 + SmsResponse smsResponse = getSmsSendResponse(response);
  71 +
  72 + return new SmsSendRespDTO().setSuccess(smsResponse.success).setApiMsg(smsResponse.data.toString());
  73 + }
  74 +
  75 + JSONObject sendSmsRequest(TreeMap<String, Object> queryParam,String apiName) throws IOException, URISyntaxException {
  76 +
  77 + // ************* 步骤 1:拼接规范请求串 *************
  78 + String url = "https://dysmsapi.aliyuncs.com"; //APP接入地址+接口访问URI
  79 + String httpMethod = "POST"; // 请求方式
  80 + String canonicalUri = "/";
  81 + // 请求参数,当请求的查询字符串为空时,使用空字符串作为规范化查询字符串
  82 + StringBuilder canonicalQueryString = new StringBuilder();
  83 + queryParam.entrySet().stream().map(entry -> percentCode(entry.getKey()) + "=" + percentCode(String.valueOf(entry.getValue()))).forEachOrdered(queryPart -> {
  84 + // 如果canonicalQueryString已经不是空的,则在查询参数前添加"&"
  85 + if (!canonicalQueryString.isEmpty()) {
  86 + canonicalQueryString.append("&");
  87 + }
  88 + canonicalQueryString.append(queryPart);
  89 + System.out.println("canonicalQueryString=========>\n" + canonicalQueryString);
  90 + });
  91 +
  92 + SimpleDateFormat SDF = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
  93 + SDF.setTimeZone(new SimpleTimeZone(0, "GMT"));
  94 + String SdfTime = SDF.format(new Date());
  95 + String randomUUID = UUID.randomUUID().toString();
  96 +
  97 + TreeMap<String, String> headers = new TreeMap<>();
  98 + headers.put("host", "dysmsapi.aliyuncs.com");
  99 + headers.put("x-acs-action", apiName);
  100 + headers.put("x-acs-version", "2017-05-25");
  101 + headers.put("x-acs-date", SdfTime);
  102 + headers.put("x-acs-signature-nonce", randomUUID);
  103 +// headers.put("content-type", "application/json;charset=utf-8");
  104 +
  105 + // 构造请求头,多个规范化消息头,按照消息头名称(小写)的字符代码顺序以升序排列后拼接在一起
  106 + StringBuilder canonicalHeaders = new StringBuilder();
  107 + // 已签名消息头列表,多个请求头名称(小写)按首字母升序排列并以英文分号(;)分隔
  108 + StringBuilder signedHeadersSb = new StringBuilder();
  109 + headers.entrySet().stream().filter(entry -> entry.getKey().toLowerCase().startsWith("x-acs-") || entry.getKey().equalsIgnoreCase("host") || entry.getKey().equalsIgnoreCase("content-type")).sorted(Map.Entry.comparingByKey()).forEach(entry -> {
  110 + String lowerKey = entry.getKey().toLowerCase();
  111 + String value = String.valueOf(entry.getValue()).trim();
  112 + canonicalHeaders.append(lowerKey).append(":").append(value).append("\n");
  113 + signedHeadersSb.append(lowerKey).append(";");
  114 + });
  115 + String signedHeaders = signedHeadersSb.substring(0, signedHeadersSb.length() - 1);
  116 +
  117 + String body = "";//短信API为RPC接口,query parameters在uri中拼接,因此request body如果没有特殊要求,设置为空。
  118 + String hashedRequestBody = HexUtil.encodeHexStr(DigestUtil.sha256(body));
  119 +
  120 +
  121 + String canonicalRequest = httpMethod + "\n" + canonicalUri + "\n" + canonicalQueryString + "\n" + canonicalHeaders + "\n" + signedHeaders + "\n" + hashedRequestBody;
  122 + System.out.println("canonicalRequest=========>\n" + canonicalRequest);
  123 +
  124 + // ************* 步骤 2:拼接待签名字符串 *************
  125 + String hashedCanonicalRequest = HexUtil.encodeHexStr(DigestUtil.sha256(canonicalRequest));
  126 + String stringToSign = "ACS3-HMAC-SHA256" + "\n" + hashedCanonicalRequest;
  127 +
  128 + // ************* 步骤 3:计算签名 *************
  129 + String signature = SecureUtil.hmacSha256(properties.getApiSecret()).digestHex(stringToSign);
  130 +
  131 + // ************* 步骤 4:拼接 Authorization *************
  132 + String authorization = "ACS3-HMAC-SHA256" + " " + "Credential=" + properties.getApiKey() + ", "
  133 + + "SignedHeaders=" + signedHeaders + ", " + "Signature=" + signature;
  134 + headers.put("Authorization", authorization);
  135 +
  136 + // ************* 步骤 5:构造HttpRequest 并执行request请求,获得response *************
  137 +// url = url + canonicalUri;
  138 + String urlWithParams = url + "?" + URLUtil.buildQuery(queryParam, null);
  139 +
  140 + HttpResponse response = HttpRequest.post(urlWithParams)
  141 + .addHeaders(headers)
  142 + .body(body)
  143 + .execute();
  144 +// URIBuilder uriBuilder = new URIBuilder(url);
  145 +// // 添加请求参数
  146 +// for (Map.Entry<String, Object> entry : queryParam.entrySet()) {
  147 +// uriBuilder.addParameter(entry.getKey(), String.valueOf(entry.getValue()));
  148 +// }
  149 +// HttpUriRequest httpRequest = new HttpPost(uriBuilder.build());
  150 +//// HttpPost httpPost = new HttpPost(uriBuilder.build());
  151 +//// httpRequest = httpPost;
  152 +//
  153 +// // 添加http请求头
  154 +// for (Map.Entry<String, Object> entry : headers.entrySet()) {
  155 +// httpRequest.addHeader(entry.getKey(), String.valueOf(entry.getValue()));
  156 +// }
  157 +//
  158 +// // 发送请求
  159 +// CloseableHttpClient httpClient = HttpClients.createDefault();
  160 +// CloseableHttpResponse response = httpClient.execute(httpRequest);
  161 + System.out.println("getEntity====="+response.body());
  162 + System.out.println("response====="+response);
  163 +
  164 + return JSONUtil.parseObj(response.body());
84 165 }
85 166  
86 167 @Override
... ... @@ -94,16 +175,15 @@ public class AliyunSmsClient extends AbstractSmsClient {
94 175  
95 176 @Override
96 177 public SmsTemplateRespDTO getSmsTemplate(String apiTemplateId) throws Throwable {
97   - // 构建请求
98   - QuerySmsTemplateRequest request = new QuerySmsTemplateRequest();
99   - request.setTemplateCode(apiTemplateId);
100   - // 执行请求
101   - QuerySmsTemplateResponse response = client.getAcsResponse(request);
102   - if (response.getTemplateStatus() == null) {
103   - return null;
104   - }
105   - return new SmsTemplateRespDTO().setId(response.getTemplateCode()).setContent(response.getTemplateContent())
106   - .setAuditStatus(convertSmsTemplateAuditStatus(response.getTemplateStatus())).setAuditReason(response.getReason());
  178 +
  179 + TreeMap<String, Object> queryParam = new TreeMap<>();
  180 + queryParam.put("TemplateCode",apiTemplateId);
  181 +
  182 + JSONObject response = sendSmsRequest(queryParam,"QuerySmsTemplate");
  183 + QuerySmsTemplateResponse smsTemplateResponse = getSmsTemplateResponse(response);
  184 + return new SmsTemplateRespDTO().setId(smsTemplateResponse.getTemplateCode()).setContent(smsTemplateResponse.getTemplateContent())
  185 + .setAuditStatus(convertSmsTemplateAuditStatus(smsTemplateResponse.getTemplateStatus())).setAuditReason(smsTemplateResponse.getReason());
  186 +
107 187 }
108 188  
109 189 @VisibleForTesting
... ... @@ -116,12 +196,99 @@ public class AliyunSmsClient extends AbstractSmsClient {
116 196 }
117 197 }
118 198  
  199 +
  200 + /**
  201 + * 对指定的字符串进行URL编码。
  202 + * 使用UTF-8编码字符集对字符串进行编码,并对特定的字符进行替换,以符合URL编码规范。
  203 + *
  204 + * @param str 需要进行URL编码的字符串。
  205 + * @return 编码后的字符串。其中,加号"+"被替换为"%20",星号"*"被替换为"%2A",波浪号"%7E"被替换为"~"。
  206 + */
  207 + public static String percentCode(String str) {
  208 + if (str == null) {
  209 + throw new IllegalArgumentException("输入字符串不可为null");
  210 + }
  211 + try {
  212 + return URLEncoder.encode(str, "UTF-8").replace("+", "%20").replace("*", "%2A").replace("%7E", "~");
  213 + } catch (UnsupportedEncodingException e) {
  214 + throw new RuntimeException("UTF-8编码不被支持", e);
  215 + }
  216 + }
  217 +
  218 + private SmsResponse getSmsSendResponse(JSONObject resJson) {
  219 + SmsResponse smsResponse = new SmsResponse();
  220 + smsResponse.setSuccess("OK".equals(resJson.getStr("Code")));
  221 + smsResponse.setData(resJson);
  222 +// smsResponse.setConfigId(getConfigId());
  223 + return smsResponse;
  224 + }
  225 +
  226 + private QuerySmsTemplateResponse getSmsTemplateResponse(JSONObject resJson) {
  227 +
  228 + QuerySmsTemplateResponse smsTemplateResponse = new QuerySmsTemplateResponse();
  229 +
  230 + smsTemplateResponse.setRequestId(resJson.getStr("RequestId"));
  231 + smsTemplateResponse.setTemplateContent(resJson.getStr("TemplateContent"));
  232 + smsTemplateResponse.setReason(resJson.getStr("Reason"));
  233 + smsTemplateResponse.setTemplateStatus(resJson.getInt("TemplateStatus"));
  234 +
  235 + return smsTemplateResponse;
  236 + }
  237 +
  238 + /**
  239 + * <p>类名: SmsResponse
  240 + * <p>说明: 发送短信返回信息
  241 + *
  242 + * @author :scholar
  243 + * 2024/07/17 0:25
  244 + **/
  245 + @Data
  246 + public static class SmsResponse {
  247 +
  248 + /**
  249 + * 是否成功
  250 + */
  251 + private boolean success;
  252 +
  253 + /**
  254 + * 厂商原返回体
  255 + */
  256 + private Object data;
  257 +
  258 + /**
  259 + * 配置标识名 如未配置取对应渠道名例如 Alibaba
  260 + */
  261 + private String configId;
  262 + }
  263 +
  264 +
  265 + /**
  266 + * <p>类名: QuerySmsTemplateResponse
  267 + * <p>说明: sms模板查询返回信息
  268 + *
  269 + * @author :scholar
  270 + * 2024/07/17 0:25
  271 + **/
  272 + @Data
  273 + public static class QuerySmsTemplateResponse {
  274 + private String requestId;
  275 + private String code;
  276 + private String message;
  277 + private Integer templateStatus;
  278 + private String reason;
  279 + private String templateCode;
  280 + private Integer templateType;
  281 + private String templateName;
  282 + private String templateContent;
  283 + private String createDate;
  284 + }
  285 +
119 286 /**
120 287 * 短信接收状态
121 288 *
122 289 * 参见 <a href="https://help.aliyun.com/document_detail/101867.html">文档</a>
123 290 *
124   - * @author 芋道源码
  291 + * @author 润普源码
125 292 */
126 293 @Data
127 294 public static class SmsReceiveStatus {
... ...
yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/framework/sms/core/client/impl/HuaweiSmsClient.java
1 1 package cn.iocoder.yudao.module.system.framework.sms.core.client.impl;
2 2  
  3 +
3 4 import cn.hutool.core.lang.Assert;
4   -import cn.hutool.core.util.HexUtil;
5 5 import cn.hutool.core.util.StrUtil;
  6 +
6 7 import cn.hutool.crypto.SecureUtil;
7   -import cn.hutool.crypto.digest.DigestUtil;
8   -import cn.hutool.json.JSONArray;
  8 +import cn.hutool.http.HttpRequest;
  9 +import cn.hutool.http.HttpResponse;
  10 +import cn.hutool.json.JSONObject;
  11 +import cn.hutool.json.JSONUtil;
9 12 import cn.iocoder.yudao.framework.common.core.KeyValue;
  13 +import cn.iocoder.yudao.framework.common.util.collection.CollectionUtils;
10 14 import cn.iocoder.yudao.framework.common.util.json.JsonUtils;
11 15 import cn.iocoder.yudao.module.system.framework.sms.core.client.dto.SmsReceiveRespDTO;
12 16 import cn.iocoder.yudao.module.system.framework.sms.core.client.dto.SmsSendRespDTO;
13 17 import cn.iocoder.yudao.module.system.framework.sms.core.client.dto.SmsTemplateRespDTO;
14 18 import cn.iocoder.yudao.module.system.framework.sms.core.enums.SmsTemplateAuditStatusEnum;
15 19 import cn.iocoder.yudao.module.system.framework.sms.core.property.SmsChannelProperties;
  20 +
16 21 import com.fasterxml.jackson.annotation.JsonFormat;
17 22 import com.fasterxml.jackson.annotation.JsonProperty;
18 23 import lombok.Data;
19 24 import lombok.extern.slf4j.Slf4j;
20   -import org.apache.http.HttpResponse;
21   -import org.apache.http.client.methods.HttpUriRequest;
22   -import org.apache.http.client.methods.RequestBuilder;
23   -import org.apache.http.entity.StringEntity;
24   -import org.apache.http.impl.client.CloseableHttpClient;
25   -import org.apache.http.impl.client.HttpClientBuilder;
26 25  
  26 +import java.io.UnsupportedEncodingException;
27 27 import java.net.URLEncoder;
28   -import java.nio.charset.StandardCharsets;
29 28 import java.text.SimpleDateFormat;
30   -import java.time.LocalDateTime;
31 29 import java.util.*;
32 30  
  31 +
  32 +import java.time.LocalDateTime;
  33 +
  34 +
  35 +import static cn.hutool.crypto.digest.DigestUtil.sha256Hex;
33 36 import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertList;
34 37 import static cn.iocoder.yudao.framework.common.util.date.DateUtils.FORMAT_YEAR_MONTH_DAY_HOUR_MINUTE_SECOND;
35 38 import static cn.iocoder.yudao.framework.common.util.date.DateUtils.TIME_ZONE_DEFAULT;
36 39  
  40 +
37 41 /**
38 42 * 华为短信客户端的实现类
39 43 *
... ... @@ -46,7 +50,14 @@ public class HuaweiSmsClient extends AbstractSmsClient {
46 50 /**
47 51 * 调用成功 code
48 52 */
49   - public static final String API_CODE_SUCCESS = "OK";
  53 + public static final String URL = "https://smsapi.cn-north-4.myhuaweicloud.com:443/sms/batchSendSms/v1";//APP接入地址+接口访问URI
  54 + public static final String HOST = "smsapi.cn-north-4.myhuaweicloud.com:443";
  55 + public static final String SIGNEDHEADERS = "content-type;host;x-sdk-date";
  56 +
  57 + @Override
  58 + protected void doInit() {
  59 +
  60 + }
50 61  
51 62 public HuaweiSmsClient(SmsChannelProperties properties) {
52 63 super(properties);
... ... @@ -55,95 +66,78 @@ public class HuaweiSmsClient extends AbstractSmsClient {
55 66 }
56 67  
57 68 @Override
58   - protected void doInit() {
59   - }
60   -
61   - @Override
62 69 public SmsSendRespDTO sendSms(Long sendLogId, String mobile, String apiTemplateId,
63 70 List<KeyValue<String, Object>> templateParams) throws Throwable {
64   - // TODO @scholar:https://smsapi.cn-north-4.myhuaweicloud.com:443 是不是枚举成静态变量
65   - String url = "https://smsapi.cn-north-4.myhuaweicloud.com:443/sms/batchSendSms/v1"; //APP接入地址+接口访问URI
66 71 // 相比较阿里短信,华为短信发送的时候需要额外的参数“通道号”,考虑到不破坏原有的的结构
67 72 // 所以将 通道号 拼接到 apiTemplateId 字段中,格式为 "apiTemplateId 通道号"。空格为分隔符。
68   - // TODO @scholar:暂时只考虑中国大陆,所以不需要 sender 哈
69 73 String sender = StrUtil.subAfter(apiTemplateId, " ", true); //中国大陆短信签名通道号或全球短信通道号
70 74 String templateId = StrUtil.subBefore(apiTemplateId, " ", true); //模板ID
71 75  
72   - // 选填,短信状态报告接收地址,推荐使用域名,为空或者不填表示不接收状态报告
  76 + //选填,短信状态报告接收地址,推荐使用域名,为空或者不填表示不接收状态报告
73 77 String statusCallBack = properties.getCallbackUrl();
74 78  
75   - // TODO @scholar:1)是不是用 LocalDateTimeUtil.format();这样 3 行变成一行
76   - // TODO @scholar:singerDate 叫 sdkDate 会更合适哈,这样理解起来简单。另外,singer 应该是 signed 么?
  79 + List<String> templateParas = CollectionUtils.convertList(templateParams, kv -> String.valueOf(kv.getValue()));
  80 +
  81 + JSONObject JsonResponse = sendSmsRequest(sender,mobile,templateId,templateParas,statusCallBack);
  82 + SmsResponse smsResponse = getSmsSendResponse(JsonResponse);
  83 +
  84 + return new SmsSendRespDTO().setSuccess(smsResponse.success).setApiMsg(smsResponse.data.toString());
  85 + }
  86 +
  87 + JSONObject sendSmsRequest(String sender,String mobile,String templateId,List<String> templateParas,String statusCallBack) throws UnsupportedEncodingException {
  88 +
77 89 SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd'T'HHmmss'Z'", Locale.ENGLISH);
78 90 sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
79   - String singerDate = sdf.format(new Date());
  91 + String sdkDate = sdf.format(new Date());
80 92  
81   - // TODO @scholar:整个处理加密的过程,是不是应该抽成一个 private 方法哈。这样整个调用的主干更清晰。
82 93 // ************* 步骤 1:拼接规范请求串 *************
83 94 String httpRequestMethod = "POST";
84 95 String canonicalUri = "/sms/batchSendSms/v1/";
85   - String canonicalQueryString = ""; // 查询参数为空
  96 + String canonicalQueryString = "";//查询参数为空
86 97 String canonicalHeaders = "content-type:application/x-www-form-urlencoded\n"
87   - + "host:smsapi.cn-north-4.myhuaweicloud.com:443\n"
88   - + "x-sdk-date:" + singerDate + "\n";
89   - // TODO @scholar:静态枚举了
90   - String signedHeaders = "content-type;host;x-sdk-date";
91   - // TODO @scholar:下面的注释,可以考虑去掉
92   - /*
93   - * 选填,使用无变量模板时请赋空值 String templateParas = "";
94   - * 单变量模板示例:模板内容为"您的验证码是${NUM_6}"时,templateParas可填写为"[\"111111\"]"
95   - * 双变量模板示例:模板内容为"您有${NUM_2}件快递请到${TXT_20}领取"时,templateParas可填写为"[\"3\",\"人民公园正门\"]"
96   - */
97   - // TODO @scholar:CollectionUtils.convertList 可以把 4 行变成 1 行。
98   - // TODO @scholar:templateParams 拼写错误哈
99   - List<String> templateParas = new ArrayList<>();
100   - for (KeyValue<String, Object> kv : templateParams) {
101   - templateParas.add(String.valueOf(kv.getValue()));
102   - }
103   -
104   - // 请求Body,不携带签名名称时,signature请填null
  98 + + "host:"+ HOST +"\n"
  99 + + "x-sdk-date:" + sdkDate + "\n";
  100 + //请求Body,不携带签名名称时,signature请填null
105 101 String body = buildRequestBody(sender, mobile, templateId, templateParas, statusCallBack, null);
106   - // TODO @scholar:Assert 断言,抛出异常
107 102 if (null == body || body.isEmpty()) {
108 103 return null;
109 104 }
110   - String hashedRequestBody = HexUtil.encodeHexStr(DigestUtil.sha256(body));
  105 + String hashedRequestBody = sha256Hex(body);
111 106 String canonicalRequest = httpRequestMethod + "\n" + canonicalUri + "\n" + canonicalQueryString + "\n"
112   - + canonicalHeaders + "\n" + signedHeaders + "\n" + hashedRequestBody;
  107 + + canonicalHeaders + "\n" + SIGNEDHEADERS + "\n" + hashedRequestBody;
113 108  
114 109 // ************* 步骤 2:拼接待签名字符串 *************
115   - // TODO @scholar:sha256Hex 是不是更简洁哈
116   - String hashedCanonicalRequest = HexUtil.encodeHexStr(DigestUtil.sha256(canonicalRequest));
117   - String stringToSign = "SDK-HMAC-SHA256" + "\n" + singerDate + "\n" + hashedCanonicalRequest;
  110 + String hashedCanonicalRequest = sha256Hex(canonicalRequest);
  111 + String stringToSign = "SDK-HMAC-SHA256" + "\n" + sdkDate + "\n" + hashedCanonicalRequest;
118 112  
119 113 // ************* 步骤 3:计算签名 *************
120 114 String signature = SecureUtil.hmacSha256(properties.getApiSecret()).digestHex(stringToSign);
121 115  
122 116 // ************* 步骤 4:拼接 Authorization *************
123 117 String authorization = "SDK-HMAC-SHA256" + " " + "Access=" + properties.getApiKey() + ", "
124   - + "SignedHeaders=" + signedHeaders + ", " + "Signature=" + signature;
  118 + + "SignedHeaders=" + SIGNEDHEADERS + ", " + "Signature=" + signature;
125 119  
126 120 // ************* 步骤 5:构造HttpRequest 并执行request请求,获得response *************
127   - // TODO @scholar:考虑了下,还是换 hutool 的 httpUtils。因为未来 httpclient 我们可能会移除掉
128   - HttpUriRequest postMethod = RequestBuilder.post()
129   - .setUri(url)
130   - .setEntity(new StringEntity(body, StandardCharsets.UTF_8))
131   - .setHeader("Content-Type","application/x-www-form-urlencoded")
132   - .setHeader("X-Sdk-Date", singerDate)
133   - .setHeader("Authorization", authorization)
134   - .build();
135   - // TODO @scholar:这种不太适合一直 new 的哈
136   - CloseableHttpClient client = HttpClientBuilder.create().build();
137   - HttpResponse response = client.execute(postMethod);
138   - // TODO @scholar:失败的情况下的处理
139   - // TODO @scholar:setSerialNo(Integer.toString(response.getStatusLine().getStatusCode())) 这部分,空一行。一行代码太多了,阅读性不太好哈
140   - return new SmsSendRespDTO().setSuccess(Objects.equals(response.getStatusLine().getReasonPhrase(), API_CODE_SUCCESS)).setSerialNo(Integer.toString(response.getStatusLine().getStatusCode()))
141   - .setApiRequestId(null).setApiCode(null).setApiMsg(null);
  121 + HttpResponse response = HttpRequest.post(URL)
  122 + .header("Content-Type", "application/x-www-form-urlencoded")
  123 + .header("X-Sdk-Date", sdkDate)
  124 + .header("host",HOST)
  125 + .header("Authorization", authorization)
  126 + .body(body)
  127 + .execute();
  128 +
  129 + return JSONUtil.parseObj(response.body());
  130 + }
  131 +
  132 + private SmsResponse getSmsSendResponse(JSONObject resJson) {
  133 + SmsResponse smsResponse = new SmsResponse();
  134 + smsResponse.setSuccess("000000".equals(resJson.getStr("code")));
  135 + smsResponse.setData(resJson);
  136 + return smsResponse;
142 137 }
143 138  
144 139 static String buildRequestBody(String sender, String receiver, String templateId, List<String> templateParas,
145   - String statusCallBack, @SuppressWarnings("SameParameterValue") String signature) {
146   - // TODO @scholar:参数不满足,是不是抛出异常更好哈;通过 hutool 的 Assert 去断言
  140 + String statusCallBack, String signature) throws UnsupportedEncodingException {
147 141 if (null == sender || null == receiver || null == templateId || sender.isEmpty() || receiver.isEmpty()
148 142 || templateId.isEmpty()) {
149 143 System.out.println("buildRequestBody(): sender, receiver or templateId is null.");
... ... @@ -154,20 +148,17 @@ public class HuaweiSmsClient extends AbstractSmsClient {
154 148 appendToBody(body, "from=", sender);
155 149 appendToBody(body, "&to=", receiver);
156 150 appendToBody(body, "&templateId=", templateId);
157   - // TODO @scholar:new JSONArray(templateParas).toString(),是不是 JsonUtils.toString 呀?
158   - appendToBody(body, "&templateParas=", new JSONArray(templateParas).toString());
  151 + appendToBody(body, "&templateParas=", JsonUtils.toJsonString(templateParas));
159 152 appendToBody(body, "&statusCallback=", statusCallBack);
160 153 appendToBody(body, "&signature=", signature);
161 154 return body.toString();
162 155 }
163 156  
164   - private static void appendToBody(StringBuilder body, String key, String val) {
165   - // TODO @scholar:StrUtils.isNotEmpty(val),是不是更简洁哈
  157 + private static void appendToBody(StringBuilder body, String key, String val) throws UnsupportedEncodingException {
166 158 if (null != val && !val.isEmpty()) {
167   - body.append(key).append(URLEncoder.encode(val, StandardCharsets.UTF_8));
  159 + body.append(key).append(URLEncoder.encode(val, "UTF-8"));
168 160 }
169 161 }
170   -
171 162 @Override
172 163 public List<SmsReceiveRespDTO> parseSmsReceiveStatus(String text) {
173 164 List<SmsReceiveStatus> statuses = JsonUtils.parseArray(text, SmsReceiveStatus.class);
... ... @@ -179,12 +170,28 @@ public class HuaweiSmsClient extends AbstractSmsClient {
179 170  
180 171 @Override
181 172 public SmsTemplateRespDTO getSmsTemplate(String apiTemplateId) throws Throwable {
182   - // 华为短信模板查询和发送短信,是不同的两套 key 和 secret,与阿里、腾讯的区别较大,这里模板查询校验暂不实现
183   - // 对应文档 https://support.huaweicloud.com/api-msgsms/sms_05_0040.html
184   - return new SmsTemplateRespDTO().setId(apiTemplateId).setContent(null)
  173 + //华为短信模板查询和发送短信,是不同的两套key和secret,与阿里、腾讯的区别较大,这里模板查询校验暂不实现。
  174 + return new SmsTemplateRespDTO().setId(null).setContent(null)
185 175 .setAuditStatus(SmsTemplateAuditStatusEnum.SUCCESS.getStatus()).setAuditReason(null);
  176 +
  177 + }
  178 +
  179 + @Data
  180 + public static class SmsResponse {
  181 +
  182 + /**
  183 + * 是否成功
  184 + */
  185 + private boolean success;
  186 +
  187 + /**
  188 + * 厂商原返回体
  189 + */
  190 + private Object data;
  191 +
186 192 }
187 193  
  194 +
188 195 /**
189 196 * 短信接收状态
190 197 *
... ...