
大家好,我是小悟。
在开始前,需要了解几个核心概念:
概念 | 说明 | 备注 |
|---|---|---|
短信签名 | 附加在短信内容前的标识,用于标识发送方身份,如公司或产品名称。 | 发送国内短信必须使用已审核通过的签名。 |
短信模板 | 预设的短信内容,包含可变参数的占位符(如{1})。 | 模板需审核。发送时将占位符替换为具体值。 |
SDKAppID & AppKey | 代表短信应用的唯一凭证,用于鉴权。 | 在短信控制台 > 应用管理中查看。 |
SecretId & SecretKey | 腾讯云API访问密钥,代表你的云账户权限,部分SDK或API方式会用到。 | 在访问管理[CAM]控制台创建和管理。 |
腾讯云为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,推荐使用。
将凭证配置在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;
}创建一个服务类来封装发送逻辑。
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)需与短信控制台应用所在地域一致。创建一个简单的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;
}
}
}将上面的步骤整合后,完整的短信发送流程如下:
为了确保服务安全和稳定,请遵循以下实践:
在Spring Boot中集成腾讯云短信服务,核心是安全配置、服务封装和流程管控。
环节 | 关键点 | 常见问题 |
|---|---|---|
前期准备 | 企业认证、签名/模板审核、获取凭证 | 个人用户无法使用营销短信;模板变量格式错误。 |
开发集成 | 使用官方Java SDK、保护SecretKey、合理封装服务类。 | 地域配置错误;SDK版本过旧。 |
生产保障 | 设置发送频率限制、验证码安全存储与校验、监控告警。 | 短信被刷;验证码被爆破;服务不可用无感知。 |

谢谢你看我的文章,既然看到这里了,如果觉得不错,随手点个赞、转发、在看三连吧,感谢感谢。那我们,下次再见。
您的一键三连,是我更新的最大动力,谢谢
山水有相逢,来日皆可期,谢谢阅读,我们再会
我手中的金箍棒,上能通天,下能探海
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。