目录
1. 预先准备
- 申请签名
- 申请短信模板
- 添加应用
详细操作请参阅 快速入门
2. 添加依赖
<!--腾讯云短信服务-->
<dependency>
<groupId>com.github.qcloudsms</groupId>
<artifactId>qcloudsms</artifactId>
<version>1.0.6</version>
</dependency>
3. 发送短信工具类
/**
* create by 星航指挥官
* create on 2020/11/23
* 不过是大梦一场空
* 不过是孤影照惊鸿
*/
public class SMSUtil {
/***
* 注册验证码
* @param templateId 模板编号
* @param phoneNumber 对象号码
* @param params 模板参数
* @return 返回值,成功或失败
*/
public static String sendSMS(int templateId,String phoneNumber,String[] params) {
String reStr = "error"; //定义返回值
int appid = 1400xxxxxx; // 短信应用SDK AppID
String appkey = "xxxxxxxxxxxxxxx"; // 短信应用SDK AppKey
String smsSign = "xxxxxx"; // 签名内容,不是签名ID
try {
//创建ssender对象
SmsSingleSender ssender = new SmsSingleSender(appid, appkey);
//发送
SmsSingleSenderResult result = ssender.sendWithParam("86", phoneNumber,templateId, params, smsSign, "", "");
// 签名参数未提供或者为空时,会使用默认签名发送短信
System.out.println(result.toString());
if(result.result==0){
reStr = "success";
}else{
reStr = "error";
}
} catch (Exception e) {
// HTTP响应码错误
e.printStackTrace();
}
return reStr;
}
}
4. Controller层调用
@RequestMapping("/sendSMS")
public String sendSMS(){
// 短信模板ID,需要在短信应用中申请
int templateId = 123456 ;
//参数,一定要对应短信模板中的参数顺序和个数,
String[] params = {"123456"};
String result = SMSUtil.sendSMS(templateId,"176xxxxxxxx", params);
if(result.equals("success")){
return "发送成功!";
}else{
return "发送失败!";
}
}
随机验证码的工具类 VerificationCode