Commit f81d56eb8836297076c790b264bc2d0a7191125a
1 parent
0c8163c4
阿里云短信,减少为SDK依赖,修改为基于API方式。
Showing
1 changed file
with
216 additions
and
49 deletions
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 { | ... | ... |