Commit 0c8ee55a172a97aa99847c36ec1809ea1e2110c0

Authored by YunaiV
1 parent dc267ea5

【代码优化】SYSTEM:去除阿里云短信的 maven 依赖

yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/framework/sms/core/client/impl/AliyunSmsClient.java
@@ -4,7 +4,6 @@ import cn.hutool.core.date.format.FastDateFormat; @@ -4,7 +4,6 @@ import cn.hutool.core.date.format.FastDateFormat;
4 import cn.hutool.core.lang.Assert; 4 import cn.hutool.core.lang.Assert;
5 import cn.hutool.core.util.IdUtil; 5 import cn.hutool.core.util.IdUtil;
6 import cn.hutool.core.util.ObjectUtil; 6 import cn.hutool.core.util.ObjectUtil;
7 -import cn.hutool.core.util.URLUtil;  
8 import cn.hutool.crypto.SecureUtil; 7 import cn.hutool.crypto.SecureUtil;
9 import cn.hutool.crypto.digest.DigestUtil; 8 import cn.hutool.crypto.digest.DigestUtil;
10 import cn.hutool.http.HttpRequest; 9 import cn.hutool.http.HttpRequest;
@@ -21,10 +20,11 @@ import cn.iocoder.yudao.module.system.framework.sms.core.client.dto.SmsTemplateR @@ -21,10 +20,11 @@ import cn.iocoder.yudao.module.system.framework.sms.core.client.dto.SmsTemplateR
21 import cn.iocoder.yudao.module.system.framework.sms.core.enums.SmsTemplateAuditStatusEnum; 20 import cn.iocoder.yudao.module.system.framework.sms.core.enums.SmsTemplateAuditStatusEnum;
22 import cn.iocoder.yudao.module.system.framework.sms.core.property.SmsChannelProperties; 21 import cn.iocoder.yudao.module.system.framework.sms.core.property.SmsChannelProperties;
23 import com.google.common.annotations.VisibleForTesting; 22 import com.google.common.annotations.VisibleForTesting;
  23 +import lombok.SneakyThrows;
24 import lombok.extern.slf4j.Slf4j; 24 import lombok.extern.slf4j.Slf4j;
25 25
26 -import java.io.UnsupportedEncodingException;  
27 import java.net.URLEncoder; 26 import java.net.URLEncoder;
  27 +import java.nio.charset.StandardCharsets;
28 import java.util.*; 28 import java.util.*;
29 import java.util.stream.Collectors; 29 import java.util.stream.Collectors;
30 30
@@ -176,10 +176,8 @@ public class AliyunSmsClient extends AbstractSmsClient { @@ -176,10 +176,8 @@ public class AliyunSmsClient extends AbstractSmsClient {
176 + ", " + "SignedHeaders=" + signedHeaders + ", " + "Signature=" + signature); 176 + ", " + "SignedHeaders=" + signedHeaders + ", " + "Signature=" + signature);
177 177
178 // 5. 发起请求 178 // 5. 发起请求
179 - String urlWithParams = URL + "?" + queryString;  
180 -  
181 - System.out.println("urlWithParams ======" + urlWithParams);  
182 - try (HttpResponse response = HttpRequest.post(urlWithParams).addHeaders(headers).body(requestBody).execute()) { 179 + try (HttpResponse response = HttpRequest.post(URL + "?" + queryString)
  180 + .addHeaders(headers).body(requestBody).execute()) {
183 return JSONUtil.parseObj(response.body()); 181 return JSONUtil.parseObj(response.body());
184 } 182 }
185 } 183 }
@@ -187,18 +185,16 @@ public class AliyunSmsClient extends AbstractSmsClient { @@ -187,18 +185,16 @@ public class AliyunSmsClient extends AbstractSmsClient {
187 /** 185 /**
188 * 对指定的字符串进行 URL 编码,并对特定的字符进行替换,以符合URL编码规范 186 * 对指定的字符串进行 URL 编码,并对特定的字符进行替换,以符合URL编码规范
189 * 187 *
190 - * @param str 需要进行URL编码的字符串 188 + * @param str 需要进行 URL 编码的字符串
191 * @return 编码后的字符串 189 * @return 编码后的字符串
192 */ 190 */
193 - public static String percentCode(String str) {  
194 - if (str == null) {  
195 - throw new IllegalArgumentException("输入字符串不可为null");  
196 - }  
197 - try {  
198 - return URLEncoder.encode(str, "UTF-8").replace("+", "%20").replace("*", "%2A").replace("%7E", "~");  
199 - } catch (UnsupportedEncodingException e) {  
200 - throw new RuntimeException("UTF-8编码不被支持", e);  
201 - } 191 + @SneakyThrows
  192 + private static String percentCode(String str) {
  193 + Assert.notNull(str, "str 不能为空");
  194 + return URLEncoder.encode(str, StandardCharsets.UTF_8.name())
  195 + .replace("+", "%20") // 加号 "+" 被替换为 "%20"
  196 + .replace("*", "%2A") // 星号 "*" 被替换为 "%2A"
  197 + .replace("%7E", "~"); // 波浪号 "%7E" 被替换为 "~"
202 } 198 }
203 199
204 } 200 }
205 \ No newline at end of file 201 \ No newline at end of file
yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/framework/sms/core/client/impl/AliyunSmsClient_old.java deleted
1 -package cn.iocoder.yudao.module.system.framework.sms.core.client.impl;  
2 -  
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;  
12 -import cn.iocoder.yudao.framework.common.core.KeyValue;  
13 -import cn.iocoder.yudao.framework.common.util.collection.MapUtils;  
14 -import cn.iocoder.yudao.framework.common.util.json.JsonUtils;  
15 -import cn.iocoder.yudao.module.system.framework.sms.core.client.dto.SmsReceiveRespDTO;  
16 -import cn.iocoder.yudao.module.system.framework.sms.core.client.dto.SmsSendRespDTO;  
17 -import cn.iocoder.yudao.module.system.framework.sms.core.client.dto.SmsTemplateRespDTO;  
18 -import cn.iocoder.yudao.module.system.framework.sms.core.enums.SmsTemplateAuditStatusEnum;  
19 -import cn.iocoder.yudao.module.system.framework.sms.core.property.SmsChannelProperties;  
20 -import com.fasterxml.jackson.annotation.JsonFormat;  
21 -import com.fasterxml.jackson.annotation.JsonProperty;  
22 -import com.google.common.annotations.VisibleForTesting;  
23 -import lombok.Data;  
24 -import lombok.extern.slf4j.Slf4j;  
25 -  
26 -import java.io.IOException;  
27 -import java.io.UnsupportedEncodingException;  
28 -import java.net.URISyntaxException;  
29 -import java.net.URLEncoder;  
30 -import java.text.SimpleDateFormat;  
31 -import java.time.LocalDateTime;  
32 -import java.util.*;  
33 -  
34 -import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertList;  
35 -import static cn.iocoder.yudao.framework.common.util.date.DateUtils.FORMAT_YEAR_MONTH_DAY_HOUR_MINUTE_SECOND;  
36 -import static cn.iocoder.yudao.framework.common.util.date.DateUtils.TIME_ZONE_DEFAULT;  
37 -  
38 -/**  
39 - * 阿里短信客户端的实现类  
40 - *  
41 - * @author zzf  
42 - * @since 2021/1/25 14:17  
43 - */  
44 -@Slf4j  
45 -public class AliyunSmsClient_old extends AbstractSmsClient {  
46 -  
47 - public AliyunSmsClient_old(SmsChannelProperties properties) {  
48 - super(properties);  
49 - Assert.notEmpty(properties.getApiKey(), "apiKey 不能为空");  
50 - Assert.notEmpty(properties.getApiSecret(), "apiSecret 不能为空");  
51 - }  
52 -  
53 - @Override  
54 - protected void doInit() {  
55 -// IClientProfile profile = DefaultProfile.getProfile(ENDPOINT, properties.getApiKey(), properties.getApiSecret());  
56 -// client = new DefaultAcsClient(profile);  
57 - }  
58 -  
59 - @Override  
60 - public SmsSendRespDTO sendSms(Long sendLogId, String mobile, String apiTemplateId,  
61 - List<KeyValue<String, Object>> templateParams) throws Throwable {  
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());  
165 - }  
166 -  
167 - @Override  
168 - public List<SmsReceiveRespDTO> parseSmsReceiveStatus(String text) {  
169 - List<SmsReceiveStatus> statuses = JsonUtils.parseArray(text, SmsReceiveStatus.class);  
170 - return convertList(statuses, status -> new SmsReceiveRespDTO().setSuccess(status.getSuccess())  
171 - .setErrorCode(status.getErrCode()).setErrorMsg(status.getErrMsg())  
172 - .setMobile(status.getPhoneNumber()).setReceiveTime(status.getReportTime())  
173 - .setSerialNo(status.getBizId()).setLogId(Long.valueOf(status.getOutId())));  
174 - }  
175 -  
176 - @Override  
177 - public SmsTemplateRespDTO getSmsTemplate(String apiTemplateId) throws Throwable {  
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 -  
187 - }  
188 -  
189 - @VisibleForTesting  
190 - Integer convertSmsTemplateAuditStatus(Integer templateStatus) {  
191 - switch (templateStatus) {  
192 - case 0: return SmsTemplateAuditStatusEnum.CHECKING.getStatus();  
193 - case 1: return SmsTemplateAuditStatusEnum.SUCCESS.getStatus();  
194 - case 2: return SmsTemplateAuditStatusEnum.FAIL.getStatus();  
195 - default: throw new IllegalArgumentException(String.format("未知审核状态(%d)", templateStatus));  
196 - }  
197 - }  
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 -  
286 - /**  
287 - * 短信接收状态  
288 - *  
289 - * 参见 <a href="https://help.aliyun.com/document_detail/101867.html">文档</a>  
290 - *  
291 - * @author 润普源码  
292 - */  
293 - @Data  
294 - public static class SmsReceiveStatus {  
295 -  
296 - /**  
297 - * 手机号  
298 - */  
299 - @JsonProperty("phone_number")  
300 - private String phoneNumber;  
301 - /**  
302 - * 发送时间  
303 - */  
304 - @JsonProperty("send_time")  
305 - @JsonFormat(pattern = FORMAT_YEAR_MONTH_DAY_HOUR_MINUTE_SECOND, timezone = TIME_ZONE_DEFAULT)  
306 - private LocalDateTime sendTime;  
307 - /**  
308 - * 状态报告时间  
309 - */  
310 - @JsonProperty("report_time")  
311 - @JsonFormat(pattern = FORMAT_YEAR_MONTH_DAY_HOUR_MINUTE_SECOND, timezone = TIME_ZONE_DEFAULT)  
312 - private LocalDateTime reportTime;  
313 - /**  
314 - * 是否接收成功  
315 - */  
316 - private Boolean success;  
317 - /**  
318 - * 状态报告说明  
319 - */  
320 - @JsonProperty("err_msg")  
321 - private String errMsg;  
322 - /**  
323 - * 状态报告编码  
324 - */  
325 - @JsonProperty("err_code")  
326 - private String errCode;  
327 - /**  
328 - * 发送序列号  
329 - */  
330 - @JsonProperty("biz_id")  
331 - private String bizId;  
332 - /**  
333 - * 用户序列号  
334 - *  
335 - * 这里我们传递的是 SysSmsLogDO 的日志编号  
336 - */  
337 - @JsonProperty("out_id")  
338 - private String outId;  
339 - /**  
340 - * 短信长度,例如说 1、2、3  
341 - *  
342 - * 140 字节算一条短信,短信长度超过 140 字节时会拆分成多条短信发送  
343 - */  
344 - @JsonProperty("sms_size")  
345 - private Integer smsSize;  
346 -  
347 - }  
348 -  
349 -}