package com.ruoyi.admin.utils;
|
|
import com.ruoyi.common.core.exception.GlobalException;
|
import com.tencentcloudapi.common.Credential;
|
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
|
import com.tencentcloudapi.sms.v20210111.SmsClient;
|
import com.tencentcloudapi.sms.v20210111.models.SendSmsResponse;
|
import lombok.Data;
|
import lombok.extern.slf4j.Slf4j;
|
import lombok.var;
|
import org.springframework.beans.factory.annotation.Value;
|
import org.springframework.stereotype.Component;
|
|
import java.util.Objects;
|
|
/**
|
* 腾讯云发送验证码
|
*
|
* @author HJL
|
*/
|
@Slf4j
|
@Component
|
public class SendSmsUtil {
|
|
/**
|
* 短信签名内容,必须填写已审核通过的签名
|
*/
|
@Value("${tencent.signName}")
|
private String singName;
|
|
/**
|
* 短信验证码登录模板id
|
*/
|
@Value("${tencent.template.loginId}")
|
public String loginId;
|
|
/**
|
* 入驻申请验证码模板id
|
*/
|
@Value("${tencent.template.applyId}")
|
public String applyId;
|
|
/**
|
* 预约成功验证码模板id
|
*/
|
@Value("${tencent.template.reservationId}")
|
public String reservationId;
|
|
/**
|
* 应用id
|
*/
|
@Value("${tencent.appId}")
|
public String appId;
|
|
/**
|
* 密钥id
|
*/
|
@Value("${tencent.secretId}")
|
public String secretId;
|
|
/**
|
* 应用的appKey
|
*/
|
@Value("${tencent.secretKey}")
|
public String secretKey;
|
|
public void sendSms(SendSmsRequest request) {
|
Credential cred = new Credential(secretId, secretKey);
|
SmsClient client = new SmsClient(cred, "ap-beijing");
|
final var req = new com.tencentcloudapi.sms.v20210111.models.SendSmsRequest();
|
req.setPhoneNumberSet(new String[]{"+86" + request.getPhone()});
|
req.setSmsSdkAppId(appId);
|
req.setSignName(singName);
|
req.setTemplateId(request.getTemplateId());
|
req.setTemplateParamSet(request.getTemplateParamSet());
|
SendSmsResponse res;
|
try {
|
res = client.SendSms(req);
|
} catch (TencentCloudSDKException e) {
|
log.error("发送短信出错:", e);
|
throw new GlobalException("发送短信验证码错误!");
|
}
|
log.info("发送短信结果:", SendSmsResponse.toJsonString(res));
|
if (!Objects.nonNull(res.getSendStatusSet()) && res.getSendStatusSet().length == 0
|
&& !"Ok".equals(res.getSendStatusSet()[0].getCode())) {
|
throw new GlobalException("发送短信验证码失败!");
|
}
|
}
|
|
/**
|
* 参数对象
|
*/
|
@Data
|
public static class SendSmsRequest {
|
/**
|
* 电话
|
*/
|
private String phone;
|
|
/**
|
* 模板 ID: 必须填写已审核通过的模板 ID
|
*/
|
private String templateId;
|
|
/**
|
* 模板参数: 模板参数的个数需要与 TemplateId 对应模板的变量个数保持一致,若无模板参数,则设置为空
|
*/
|
private String[] templateParamSet;
|
|
public SendSmsRequest(String phone, String templateId, String[] templateParamSet) {
|
this.phone = phone;
|
this.templateId = templateId;
|
this.templateParamSet = templateParamSet;
|
}
|
}
|
|
}
|