SpringBoot集成腾讯云短信服务全攻略
作者:悟空码字
在Spring Boot项目中集成腾讯云短信服务,主要通过官方SDK调用API实现,具有稳定性高、接入便捷的特点,下面是详细介绍如何实现,需要的朋友可以参考下
腾讯云短信核心概念
在开始前,需要了解几个核心概念:
| 概念 | 说明 | 备注 |
|---|---|---|
| 短信签名 | 附加在短信内容前的标识,用于标识发送方身份,如公司或产品名称。 | 发送国内短信必须使用已审核通过的签名。 |
| 短信模板 | 预设的短信内容,包含可变参数的占位符(如{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集成腾讯云短信的资料请关注脚本之家其它相关文章!
