2026/4/17 2:12:24
网站建设
项目流程
台州优化网站,wordpress 网址,网页版微信可以传文件吗,优化系统大家好#xff0c;我是小悟。在Spring Boot项目中集成腾讯云短信服务#xff0c;主要通过官方SDK调用API实现#xff0c;具有稳定性高、接入便捷的特点。下面是详细介绍如何实现。
腾讯云短信核心概念
在开始前#xff0c;需要了解几个核心概念#xff1a;概念说明备注短信…大家好我是小悟。在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 groupIdcom.tencentcloudapi/groupId artifactIdtencentcloud-sdk-java/artifactId version3.1.XXX/version !-- 请替换为最新版本 -- scopecompile/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版本过旧。生产保障设置发送频率限制、验证码安全存储与校验、监控告警。短信被刷验证码被爆破服务不可用无感知。谢谢你看我的文章既然看到这里了如果觉得不错随手点个赞、转发、在看三连吧感谢感谢。那我们下次再见。您的一键三连是我更新的最大动力谢谢山水有相逢来日皆可期谢谢阅读我们再会我手中的金箍棒上能通天下能探海