腾讯云短信申请地址:签名
腾讯云申请相对简单,需要自己备案网站、app,或者已经上线的公众号、小程序。个人建议用小程序,小程序上线较简单。
编写代码
调用腾讯云短信,返回成功将生成的验证码存入redis缓存中
pom.xml
<!-- 腾讯云sdk-->
<dependency>
<groupId>com.github.qcloudsms</groupId>
<artifactId>qcloudsms</artifactId>
<version>1.0.6</version>
</dependency>
application.yml
server:
port: 9090
# Tencent 腾讯云短信
tencent:
#短信应用 SDK AppID
appid: 140xxxxxxxx
#短信应用 SDK AppKey
appkey: 48cxxxxxxx
#短信模板 ID,需要在短信应用中申请
templateId: 9xxxxx
#签名
signname: xxxxxxx
# redis 配置
spring:
redis:
# 地址
host: localhost
# 端口,默认为6379
port: 6379
# 数据库索引
database: 0
# 密码
password: 123456
# 连接超时时间
timeout: 10s
lettuce:
pool:
# 连接池中的最小空闲连接
min-idle: 0
# 连接池中的最大空闲连接
max-idle: 8
# 连接池的最大数据库连接数
max-active: 8
# #连接池最大阻塞等待时间(使用负值表示没有限制)
max-wait: -1ms
TencentSmsUtils.java
package com.zqing.sms.utils;
import com.github.qcloudsms.SmsSingleSender;
import com.github.qcloudsms.SmsSingleSenderResult;
import com.github.qcloudsms.httpclient.HTTPException;
import com.zqing.sms.domain.AjaxResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
/**
* @author zqing
* @description: 腾讯云短信
* @date: 2021-03-24 23:18
*/
@Component
public class TencentSmsUtils {
@Autowired
RedisCacheUtils redis;
@Value("${tencent.appid}")
private Integer APPID;
@Value("${tencent.appkey}")
private String APPKEY;
@Value("${tencent.templateId}")
private Integer TEMPLATEID;
@Value("${tencent.signname}")
private String SIGNNAME;
/**
* 生成6位随机数验证码
*
* @return
*/
public static String vcode() {
String vcode = "";
for (int i = 0; i < 6; i++) {
vcode = vcode + (int) (Math.random() * 9);
}
return vcode;
}
/**
* 发送短信
*
* @param phone
* @return
*/
public AjaxResult sendTencentSMS(String phone) {
try {
if (phone == null || phone == "") {
return AjaxResult.error("手机号不能为空");
}
//生成6位随机验证码
String verifyCode = vcode();
//短信模板中的两个参数变量
String[] params = {verifyCode, "5"};
SmsSingleSender ssender = new SmsSingleSender(APPID, APPKEY);
SmsSingleSenderResult smsResult = ssender.sendWithParam("86", phone, TEMPLATEID, params, SIGNNAME, "", "");
if (smsResult.result == 0) {
redis.setCacheObject("tencent:" + phone, verifyCode, 5, TimeUnit.MINUTES);
return AjaxResult.success("发送短信验证码成功");
} else {
return AjaxResult.error(smsResult.errMsg);
}
} catch (HTTPException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
源码下载(包括阿里云短信源码):腾讯云短信源码