新增腾讯云短信发送

This commit is contained in:
yxz 2025-01-09 16:44:55 +08:00
parent 1f1cfb6c4c
commit 4ad3862704
6 changed files with 89 additions and 40 deletions

View File

@ -335,6 +335,11 @@
<artifactId>dysmsapi20170525</artifactId> <artifactId>dysmsapi20170525</artifactId>
<version>3.1.0</version> <version>3.1.0</version>
</dependency> </dependency>
<dependency>
<groupId>com.tencentcloudapi</groupId>
<artifactId>tencentcloud-sdk-java</artifactId>
<version>3.1.270</version>
</dependency>
</dependencies> </dependencies>

View File

@ -0,0 +1,23 @@
package com.zbkj.common.config;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
/**
* 腾讯云配置
* @Version: 1.0
* @since: 2025/1/9
* @author: yxz
*/
@Configuration
@Data
@ConfigurationProperties(prefix = "tencent.sms")
public class TencentConfig {
private String appId;
private String signName;
private String secretId;
private String secretKey;
private String templateId;
}

View File

@ -82,7 +82,7 @@ public class LoginController {
@ApiImplicitParam(name="phone", value="手机号码", required = true) @ApiImplicitParam(name="phone", value="手机号码", required = true)
}) })
public CommonResult<Object> sendCode(@RequestParam String phone) throws Exception { public CommonResult<Object> sendCode(@RequestParam String phone) throws Exception {
if(smsService.sendAliCommonCode(phone)){ if(smsService.sendTencentCommonCode(phone)){
return CommonResult.success("发送成功"); return CommonResult.success("发送成功");
}else{ }else{
return CommonResult.failed("发送失败"); return CommonResult.failed("发送失败");

View File

@ -59,10 +59,11 @@ swagger:
username: #访问swagger的账号 username: #访问swagger的账号
password: #访问swagger的密码 password: #访问swagger的密码
#阿里云配置 # 腾讯云配置
ali: tencent:
sms: sms:
access-key-id: LTAI5tRJzMoNC2uF17u6Wx15 sign-name: 厦门六本木传媒
access-key-secret: gZA90P9d1peFfuAaqROf4yXFLT34KY app-id: 1400765943
sign-name: 蘑菇童话王国 secret-id: AKIDyoedR2NWYN0QgkigcVcbUFm5JLCrHXZO
template-code: SMS_476680164 secret-key: jIfIrHYebN4qQoIekePbhfbbWJ8qNwZ5
template-id: 2171347

View File

@ -51,14 +51,14 @@ public interface SmsService {
Boolean sendCommonCode(String phone); Boolean sendCommonCode(String phone);
/** /**
* 发送阿里云通用验证码 * 发送腾讯云通用验证码
* *
* @param phone 电话 * @param phone 电话
* @return {@link Boolean } * @return {@link Boolean }
* @author yxz * @author yxz
* @since 2024/12/26 * @since 2024/12/26
*/ */
Boolean sendAliCommonCode(String phone) throws Exception; Boolean sendTencentCommonCode(String phone) throws Exception;
/** /**
* 发送支付成功短信 * 发送支付成功短信

View File

@ -6,14 +6,22 @@ import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import com.aliyun.dysmsapi20170525.Client; import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponseBody; import com.aliyun.dysmsapi20170525.models.SendSmsResponseBody;
import com.aliyun.tea.TeaException; import com.aliyun.tea.TeaException;
import com.aliyun.teaopenapi.models.Config; import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.Common; import com.aliyun.teautil.Common;
import com.aliyun.teautil.models.RuntimeOptions; import com.aliyun.teautil.models.RuntimeOptions;
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectMapper;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.sms.v20210111.SmsClient;
import com.tencentcloudapi.sms.v20210111.models.SendSmsRequest;
import com.tencentcloudapi.sms.v20210111.models.SendSmsResponse;
import com.google.gson.Gson;
import com.zbkj.common.config.AliConfig; import com.zbkj.common.config.AliConfig;
import com.zbkj.common.config.TencentConfig;
import com.zbkj.common.request.SmsApplyTempRequest; import com.zbkj.common.request.SmsApplyTempRequest;
import com.zbkj.common.request.SmsModifySignRequest; import com.zbkj.common.request.SmsModifySignRequest;
import com.zbkj.common.utils.CrmebUtil; import com.zbkj.common.utils.CrmebUtil;
@ -83,7 +91,7 @@ public class SmsServiceImpl implements SmsService {
private OnePassService onePassService; private OnePassService onePassService;
@Autowired @Autowired
private AliConfig aliConfig; private TencentConfig config;
private static final Logger logger = LoggerFactory.getLogger(SmsServiceImpl.class); private static final Logger logger = LoggerFactory.getLogger(SmsServiceImpl.class);
@ -363,7 +371,7 @@ public class SmsServiceImpl implements SmsService {
} }
/** /**
* 发送阿里云通用验证码 * 发送腾讯云通用验证码
* *
* @param phone 电话 * @param phone 电话
* @return {@link Boolean } * @return {@link Boolean }
@ -371,39 +379,51 @@ public class SmsServiceImpl implements SmsService {
* @since 2024/12/26 * @since 2024/12/26
*/ */
@Override @Override
public Boolean sendAliCommonCode(String phone) throws Exception { public Boolean sendTencentCommonCode(String phone) throws Exception {
ValidateFormUtil.isPhone(phone,"手机号码错误"); ValidateFormUtil.isPhone(phone,"手机号码错误");
Integer code = CrmebUtil.randomCount(111111, 999999); Integer code = CrmebUtil.randomCount(111111, 999999);
redisUtil.set(userService.getValidateCodeRedisKey(phone), code, Long.valueOf(1), TimeUnit.MINUTES); redisUtil.set(userService.getValidateCodeRedisKey(phone), code, Long.valueOf(1), TimeUnit.MINUTES);
// 发送短信
Config config = new Config()
// 必填请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_ID
.setAccessKeyId(aliConfig.getAccessKeyId())
// 必填请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_SECRET
.setAccessKeySecret(aliConfig.getAccessKeySecret());
// Endpoint 请参考 https://api.aliyun.com/product/Dysmsapi
config.endpoint = "dysmsapi.aliyuncs.com";
Client client = new Client(config);
SendSmsRequest sendSmsRequest = new SendSmsRequest()
.setPhoneNumbers(phone)
.setSignName(aliConfig.getSignName())
.setTemplateCode(aliConfig.getTemplateCode())
.setTemplateParam("{\"code\":\""+code+"\"}");
try { try {
ObjectMapper objectMapper = new ObjectMapper(); Credential cred = new Credential(config.getSecretId(), config.getSecretKey());
SendSmsResponseBody body = client.sendSmsWithOptions(sendSmsRequest, new RuntimeOptions()).getBody(); // (Optional) Instantiate an HTTP option
log.info("阿里云短信发送结果: " + objectMapper.writeValueAsString(body)); HttpProfile httpProfile = new HttpProfile();
} catch (TeaException error) { httpProfile.setReqMethod("POST");
// 错误 message /* The SDK has a default timeout period. Do not adjust it unless absolutely necessary
Common.assertAsString(error.message); * If needed, check in the code to get the latest default value */
log.info("诊断地址: " + error.getData().get("Recommend")); httpProfile.setConnTimeout(60);
throw new CrmebException(error.getMessage()); httpProfile.setEndpoint("sms.tencentcloudapi.com");
} catch (Exception _error) { /* Optional steps:
TeaException error = new TeaException(_error.getMessage(), _error); * Instantiate a client configuration object. You can specify the timeout period and other configuration items */
Common.assertAsString(error.message); ClientProfile clientProfile = new ClientProfile();
log.info("诊断地址: " + error.getData().get("Recommend")); /* The SDK uses `TC3-HMAC-SHA256` to sign by default
throw new CrmebException(error.getMessage()); * Do not modify this field unless absolutely necessary */
clientProfile.setSignMethod("HmacSHA256");
clientProfile.setHttpProfile(httpProfile);
/* Instantiate the client object of the requested product (with SMS as an example)
* The second parameter is the information on the region you select in Tencent Cloud International. If you select Singapore, you should enter the string `ap-singapore`. Click https://www.tencentcloud.com/document/api/382/40466?lang=en#region-list to view the region list. */
SmsClient client = new SmsClient(cred, "ap-guangzhou",clientProfile);
SendSmsRequest req = new SendSmsRequest();
req.setSmsSdkAppId(config.getAppId());
req.setSignName(config.getSignName());
req.setSenderId("");
req.setSessionContext("");
req.setExtendCode("");
req.setTemplateId(config.getTemplateId());
/* Target mobile number in the E.164 standard (+[country/region code][mobile number])
* Example: +8613711112222, which has a + sign followed by 86 (country/region code) and then by 13711112222 (mobile number). Up to 200 mobile numbers are supported */
String[] phoneArray = {phone};
req.setPhoneNumberSet(phoneArray);
/* Template parameters. If there are no template parameters, leave it empty */
String[] argsArray = {code+""};
req.setTemplateParamSet(argsArray);
SendSmsResponse response = client.SendSms(req);
log.info("{}",new Gson().toJson(response));
} catch (TencentCloudSDKException e) {
e.printStackTrace();
return Boolean.FALSE;
} }
return true; return true;
} }