1.在pom.xml文件中添加依赖
<dependency>
<groupId>com.tencentcloudapi</groupId>
<artifactId>tencentcloud-sdk-java</artifactId>
<version>3.1.270</version>
</dependency>
2.新建SmsConstant常量类保存需要用到的常量
public class SmsConstant {
public static final String SDKAPPID = "";
public static final String SECRETID = "";
public static final String SECRETKEY = "";
public static final String SIGNNAME = "";
public static final String TEMPLATEID = "";
}
下面说明一下以上各个值如何获取
2.1.点击进入腾讯云短信服务官网
2.2.点击进入腾讯云短信控制台
SDKAPPID 就是下图中的SDKAppID,没有就创建
2.3.点击进入 API密钥管理
SECRETID 和SECRETKEY 就是下图中的SecretID 和 SecretKey
2.4.创建签名,等待审核
SIGNNAME 就是下图中的内容
2.5.创建正文模板,等待审核
TEMPLATEID 就是下图中的ID
3.新建SendSmsUtil工具类
import com.admin.common.constant.SmsConstant;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
//导入可选配置类
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
// 导入对应SMS模块的client
import com.tencentcloudapi.sms.v20210111.SmsClient;
// 导入要请求接口对应的request response类
import com.tencentcloudapi.sms.v20210111.models.SendSmsRequest;
import com.tencentcloudapi.sms.v20210111.models.SendSmsResponse;
public class SendSmsUtil {
public static void sendSms(String phoneNumber, String verificationCode) {
try {
Credential cred = new Credential(SmsConstant.SECRETID, SmsConstant.SECRETKEY);
// 实例化一个http选项,可选,没有特殊需求可以跳过
HttpProfile httpProfile = new HttpProfile();
// 设置代理
// httpProfile.setProxyHost("真实代理ip");
// httpProfile.setProxyPort(真实代理端口);
httpProfile.setReqMethod("POST");
httpProfile.setConnTimeout(60);
httpProfile.setEndpoint("sms.tencentcloudapi.com");
ClientProfile clientProfile = new ClientProfile();
clientProfile.setSignMethod("HmacSHA256");
clientProfile.setHttpProfile(httpProfile);
SmsClient client = new SmsClient(cred, "ap-guangzhou", clientProfile);
SendSmsRequest req = new SendSmsRequest();
String sdkAppId = SmsConstant.SDKAPPID;
req.setSmsSdkAppId(sdkAppId);
String signName = SmsConstant.SIGNNAME;
req.setSignName(signName);
String senderid = "";
req.setSenderId(senderid);
String sessionContext = "xxx";
req.setSessionContext(sessionContext);
String extendCode = "";
req.setExtendCode(extendCode);
String templateId = SmsConstant.TEMPLATEID;
req.setTemplateId(templateId);
String[] phoneNumberSet = {"+86" + phoneNumber};
req.setPhoneNumberSet(phoneNumberSet);
String[] templateParamSet = {verificationCode};
req.setTemplateParamSet(templateParamSet);
SendSmsResponse res = client.SendSms(req);
// 输出json格式的字符串回包
System.out.println(SendSmsResponse.toJsonString(res));
// 也可以取出单个值,你可以通过官网接口文档或跳转到response对象的定义处查看返回字段的定义
System.out.println(res.getRequestId());
} catch (TencentCloudSDKException e) {
e.printStackTrace();
}
}
}
到此这篇关于Spring Boot腾讯云短信申请与使用的文章就介绍到这了,更多相关Spring Boot腾讯云短信内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!