腾讯云短信核心概念
在开始前,需要了解几个核心概念:
| 概念 | 说明 | 备注 |
|---|---|---|
| 短信签名 | 附加在短信内容前的标识,用于标识发送方身份,如公司或产品名称。 | 发送国内短信必须使用已审核通过的签名。 |
| 短信模板 | 预设的短信内容,包含可变参数的占位符(如{1})。 | 模板需审核。发送时将占位符替换为具体值。 |
| sdkappid & appkey | 代表短信应用的唯一凭证,用于鉴权。 | 在短信控制台 > 应用管理中查看。 |
| secretid & secretkey | 腾讯云api访问密钥,代表你的云账户权限,部分sdk或api方式会用到。 | 在访问管理[cam]控制台创建和管理。 |
实施前准备
- 开通服务与创建应用
- 在腾讯云短信控制台开通服务。
- 在“应用管理”中创建一个应用,获得 sdkappid,并生成对应的 appkey(如果使用旧版sdk)。
- 创建签名与模板
- 在控制台根据用途(自用/他用)和类型(app、网站等)申请短信签名。
- 根据短信类型(验证码、通知、营销)创建正文模板,使用
{数字}格式定义变量,例如:您的验证码是{1},有效期{2}分钟。。 - 等待审核通过后,记录签名内容和模板id。
spring boot集成步骤
1. 引入官方sdk依赖
腾讯云为java提供了tencentcloud-sdk-java。在pom.xml中添加依赖(请检查maven仓库使用最新版本):
<dependency>
<groupid>com.tencentcloudapi</groupid>
<artifactid>tencentcloud-sdk-java</artifactid>
<version>3.1.xxx</version> <!-- 请替换为最新版本 -->
<scope>compile</scope>
</dependency>
该sdk封装了所有短信api,推荐使用。
2. 配置安全凭证
将凭证配置在application.yml中,切勿提交至代码仓库。
tencent:
sms:
secret-id: your-secret-id # 替换为你的secretid
secret-key: your-secret-key # 替换为你的secretkey
sdk-app-id: 1400000000 # 替换为你的sdkappid
sign-name: 你的签名内容 # 替换为审核通过的签名内容
template-id: 1234567 # 替换为你常用的默认模板id
在配置类中读取这些值:
import lombok.data;
import org.springframework.boot.context.properties.configurationproperties;
import org.springframework.context.annotation.configuration;
@configuration
@configurationproperties(prefix = "tencent.sms")
@data
public class tencentsmsproperties {
private string secretid;
private string secretkey;
private string sdkappid;
private string signname;
private string templateid;
}
3. 创建短信发送服务
创建一个服务类来封装发送逻辑。
import com.tencentcloudapi.common.credential;
import com.tencentcloudapi.common.exception.tencentcloudsdkexception;
import com.tencentcloudapi.common.profile.clientprofile;
import com.tencentcloudapi.common.profile.httpprofile;
import com.tencentcloudapi.sms.v20210111.smsclient;
import com.tencentcloudapi.sms.v20210111.models.*;
import lombok.requiredargsconstructor;
import lombok.extern.slf4j.slf4j;
import org.springframework.stereotype.service;
@service
@slf4j
@requiredargsconstructor
public class tencentsmsservice {
private final tencentsmsproperties smsproperties;
/**
* 发送短信验证码
*
* @param phonenumber 目标手机号(带区号,如"+8613712345678")
* @param templateid 模板id(可选,不填则使用配置的默认模板id)
* @param templateparams 模板参数列表,按顺序替换模板中的变量{citation:6}
* @return 发送是否成功
*/
public boolean sendsms(string phonenumber, string templateid, string[] templateparams) {
try {
// 1. 实例化认证对象,传入secretid和secretkey[citation:10]
credential cred = new credential(smsproperties.getsecretid(), smsproperties.getsecretkey());
// 2. 配置http和客户端profile
httpprofile httpprofile = new httpprofile();
httpprofile.setendpoint("sms.tencentcloudapi.com"); // 短信api端点
clientprofile clientprofile = new clientprofile();
clientprofile.sethttpprofile(httpprofile);
// 3. 实例化smsclient
smsclient client = new smsclient(cred, "ap-guangzhou", clientprofile); // 地域根据控制台指引选择
// 4. 构造请求对象并填充参数
sendsmsrequest req = new sendsmsrequest();
req.setsmssdkappid(smsproperties.getsdkappid()); // 设置应用id[citation:2]
req.setsignname(smsproperties.getsignname()); // 设置签名[citation:2]
req.settemplateid(templateid != null ? templateid : smsproperties.gettemplateid()); // 设置模板id
req.setphonenumberset(new string[]{phonenumber}); // 设置手机号,支持批量
req.settemplateparamset(templateparams); // 设置模板参数
// 5. 发起请求并处理响应
sendsmsresponse resp = client.sendsms(req);
sendstatus status = resp.getsendstatusset()[0]; // 取第一个号码的发送状态
log.info("短信发送请求id:{},状态:{},状态码:{}", resp.getrequestid(), status.getmessage(), status.getcode());
// 6. 判断发送结果(通常以"ok"表示成功,请根据实际响应判断)
return "ok".equalsignorecase(status.getcode());
} catch (tencentcloudsdkexception e) {
log.error("腾讯云短信sdk调用失败,错误信息:{}", e.tostring(), e);
return false;
}
}
/**
* 简化方法:发送固定模板的短信(如验证码)
*
* @param phonenumber 目标手机号
* @param code 验证码
* @return 发送是否成功
*/
public boolean sendverificationcode(string phonenumber, string code) {
// 假设你的验证码模板内容为:您的验证码是{1},有效期{2}分钟。
string[] templateparams = {code, "5"}; // 验证码和有效期
return sendsms(phonenumber, null, templateparams); // 使用配置中的默认模板id
}
}
核心说明:
- 凭证安全:
secretid和secretkey代表账户所有权,务必保密。 - 地域选择:实例化
smsclient时的地域参数(如ap-guangzhou)需与短信控制台应用所在地域一致。 - 错误处理:生产环境需更完善的错误处理(如重试、熔断)和状态监控。
4. 创建控制器提供api接口
创建一个简单的rest api接口,供前端或其他服务调用。
import lombok.requiredargsconstructor;
import org.springframework.web.bind.annotation.*;
@restcontroller
@requestmapping("/api/sms")
@requiredargsconstructor
public class smscontroller {
private final tencentsmsservice smsservice;
@postmapping("/send-code")
public apiresponse sendverificationcode(@requestparam string phonenumber) {
// 1. 生成随机验证码(示例)
string code = string.valueof((int)((math.random() * 9 + 1) * 100000));
// 2. 发送短信
boolean issuccess = smsservice.sendverificationcode(phonenumber, code);
// 3. 此处应将验证码与手机号关联存储到redis或session,并设置过期时间,用于后续校验[citation:6]
// redistemplate.opsforvalue().set("sms_code:" + phonenumber, code, 5, timeunit.minutes);
if (issuccess) {
return apiresponse.success("短信发送成功");
} else {
return apiresponse.fail("短信发送失败,请稍后重试");
}
}
// 简单的响应封装类
@data
public static class apiresponse {
private boolean success;
private string message;
private object data;
public static apiresponse success(string message) {
apiresponse response = new apiresponse();
response.setsuccess(true);
response.setmessage(message);
return response;
}
public static apiresponse fail(string message) {
apiresponse response = new apiresponse();
response.setsuccess(false);
response.setmessage(message);
return response;
}
}
}
核心流程与最佳实践
将上面的步骤整合后,完整的短信发送流程如下:
为了确保服务安全和稳定,请遵循以下实践:
- 频率限制:在控制台或代码中,对同一手机号设置发送频率和数量限制(如30秒1条、1天10条),防止短信轰炸。
- 安全存储:使用redis等缓存验证码,并设置合理的过期时间(如5分钟),切勿返回给前端。
- 监控与告警:关注发送成功率,配置云监控告警,对于发送失败或频率异常及时处理。
- 事务与幂等:关键业务(如支付)的短信发送,应考虑与业务逻辑的事务一致性,并对发送请求做幂等处理。
总结
在spring boot中集成腾讯云短信服务,核心是安全配置、服务封装和流程管控。
| 环节 | 关键点 | 常见问题 |
|---|---|---|
| 前期准备 | 企业认证、签名/模板审核、获取凭证 | 个人用户无法使用营销短信;模板变量格式错误。 |
| 开发集成 | 使用官方java sdk、保护secretkey、合理封装服务类。 | 地域配置错误;sdk版本过旧。 |
| 生产保障 | 设置发送频率限制、验证码安全存储与校验、监控告警。 | 短信被刷;验证码被爆破;服务不可用无感知。 |
以上就是springboot集成腾讯云短信服务全攻略的详细内容,更多关于springboot集成腾讯云短信的资料请关注代码网其它相关文章!
发表评论