SpringBoot2.x 集成腾讯云短信的详细流程

2025-05-29 0 78

一、腾讯云短信简介

腾讯云短信(Short Message Service,SMS)沉淀腾讯十多年短信服务技术和经验,为QQ、微信等亿级平台和10万+客户提供快速灵活接入的高质量的国内短信与国际/港澳台短信服务。

  • 国内短信验证秒级触达,99%到达率。
  • 国际/港澳台短信覆盖全球200+国家/地区,稳定可靠。

单次短信的业务请求流程如下所示:

SpringBoot2.x 集成腾讯云短信的详细流程

短信由签名和正文内容组成,发送短信前需要申请短信签名和正文内容模板。短信签名是位于短信正文前【】中的署名,用于标识公司或业务。短信签名需要审核通过后才可使用。短信模板即具体发送的短信正文内容,短信模板支持验证码模板、通知类短信模板和营销短信模板。短信内容可以通过模板参数实现个性化定制。短信模板申请前需要先申请短信签名,短信模板需要审核通过后才可使用。

二、准备工作

1.开通短信服务

如果没有腾讯云账号,需要注册腾讯云账号,并完成实名认证,可以个人认证和企业认证,不能进行企业认证的话也可以进行个人认证。然后进入腾讯云短信控制台,开通短信服务,开通短信和个人认证之后分别都会赠送包含100条短信的国内套餐包,用来测试足够:

SpringBoot2.x 集成腾讯云短信的详细流程

2.创建签名

这里创建国内短信签名,创建完成后等到状态变为已通过就可以使用了:

SpringBoot2.x 集成腾讯云短信的详细流程

创建签名时签名类型可以选网站、APP、公众号和小程序,可以根据需要创建:

SpringBoot2.x 集成腾讯云短信的详细流程

3.创建正文模板

创建模板,创建完成之后状态变为已通过就可以使用了:

SpringBoot2.x 集成腾讯云短信的详细流程

模板内容可以使用标准模板也可以自定义:

SpringBoot2.x 集成腾讯云短信的详细流程

4.创建短信应用

在应用列表下可以创建短信应用,获取短信应用的SDKAppID:

SpringBoot2.x 集成腾讯云短信的详细流程

点击应用可以查看应用信息:

SpringBoot2.x 集成腾讯云短信的详细流程

5.腾讯云API密钥

在访问管理菜单的访问密钥下的API密钥管理中可以新建和查看API密钥,在请求腾讯云短信服务发送短信时需要传入该密钥:

SpringBoot2.x 集成腾讯云短信的详细流程

三、集成腾讯云短信

通过Maven新建一个名为springboot-tencent-sms的项目。

1.引入依赖

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-web</artifactId>
  4. </dependency>
  5. <!– 腾讯云 Java SDK 依赖 –>
  6. <dependency>
  7. <groupId>com.tencentcloudapi</groupId>
  8. <artifactId>tencentcloud-sdk-java</artifactId>
  9. <version>3.1.297</version>
  10. </dependency>
  11. <!– Spring Data Redis 起步依赖 –>
  12. <dependency>
  13. <groupId>org.springframework.boot</groupId>
  14. <artifactId>spring-boot-starter-data-redis</artifactId>
  15. </dependency>
  16. <!– lombok插件 –>
  17. <dependency>
  18. <groupId>org.projectlombok</groupId>
  19. <artifactId>lombok</artifactId>
  20. <version>1.18.8</version>
  21. </dependency>

2.编写配置类

用于读取配置文件中的自定义腾讯云短信配置的配置类:

  1. package com.rtxtitanv.config;
  2. import lombok.Data;
  3. import org.springframework.boot.context.properties.ConfigurationProperties;
  4. import org.springframework.context.annotation.Configuration;
  5. /**
  6. * @author rtxtitanv
  7. * @version 1.0.0
  8. * @name com.rtxtitanv.config.SmsConfig
  9. * @description 腾讯云短信配置类
  10. * @date 2021/6/25 16:21
  11. */
  12. @ConfigurationProperties(prefix = "tencent.sms")
  13. @Configuration
  14. @Data
  15. public class SmsConfig {
  16. /**
  17. * 腾讯云API密钥的SecretId
  18. */
  19. private String secretId;
  20. /**
  21. * 腾讯云API密钥的SecretKey
  22. */
  23. private String secretKey;
  24. /**
  25. * 短信应用的SDKAppID
  26. */
  27. private String appId;
  28. /**
  29. * 签名内容
  30. */
  31. private String sign;
  32. /**
  33. * 模板ID
  34. */
  35. private String templateId;
  36. /**
  37. * 过期时间
  38. */
  39. private String expireTime;
  40. /**
  41. * redis存储的key的前缀
  42. */
  43. private String phonePrefix;
  44. }

Redis配置类:

  1. package com.rtxtitanv.config;
  2. import org.springframework.context.annotation.Bean;
  3. import org.springframework.context.annotation.Configuration;
  4. import org.springframework.data.redis.connection.RedisConnectionFactory;
  5. import org.springframework.data.redis.core.RedisTemplate;
  6. import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
  7. import org.springframework.data.redis.serializer.StringRedisSerializer;
  8. import javax.annotation.Resource;
  9. /**
  10. * @author rtxtitanv
  11. * @version 1.0.0
  12. * @name com.rtxtitanv.config.RedisConfig
  13. * @description Redis配置类
  14. * @date 2021/6/26 12:24
  15. */
  16. @Configuration
  17. public class RedisConfig {
  18. @Resource
  19. private RedisConnectionFactory redisConnectionFactory;
  20. /**
  21. * RedisTemplate实例
  22. *
  23. * @return RedisTemplate实例
  24. */
  25. @Bean
  26. public RedisTemplate<String, Object> redisTemplate() {
  27. RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
  28. initRedisTemplate(redisTemplate, redisConnectionFactory);
  29. return redisTemplate;
  30. }
  31. /**
  32. * 设置数据存入redis的序列化方式
  33. *
  34. * @param redisTemplate RedisTemplate对象
  35. * @param factory RedisConnectionFactory对象
  36. */
  37. private void initRedisTemplate(RedisTemplate<String, Object> redisTemplate, RedisConnectionFactory factory) {
  38. redisTemplate.setKeySerializer(new StringRedisSerializer());
  39. redisTemplate.setValueSerializer(new StringRedisSerializer());
  40. redisTemplate.setHashKeySerializer(new GenericJackson2JsonRedisSerializer());
  41. redisTemplate.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
  42. redisTemplate.setConnectionFactory(factory);
  43. }
  44. }

3.编写配置文件

  1. spring:
  2. redis:
  3. host: 127.0.0.1
  4. port: 6379
  5. # 自定义腾讯云短信配置
  6. tencent:
  7. sms:
  8. # 配置腾讯云API密钥的SecretId
  9. secretId: 这里填腾讯云API密钥的SecretId
  10. # 配置腾讯云API密钥的SecretKey
  11. secretKey: 这里填腾讯云API密钥的SecretKey
  12. # 配置短信应用的SDKAppID
  13. appId: 这里填短信应用的SDKAppID
  14. # 配置签名内容
  15. sign: "这里填签名内容"
  16. # 配置模板ID
  17. templateId: 这里填模板ID
  18. # 配置过期时间
  19. expireTime: 5
  20. # 配置redis存储的key的前缀
  21. phonePrefix: REGIST

4.编写工具类

腾讯云短信工具类:

  1. package com.rtxtitanv.util;
  2. import com.rtxtitanv.config.SmsConfig;
  3. import com.tencentcloudapi.common.Credential;
  4. import com.tencentcloudapi.common.exception.TencentCloudSDKException;
  5. import com.tencentcloudapi.common.profile.ClientProfile;
  6. import com.tencentcloudapi.common.profile.HttpProfile;
  7. import com.tencentcloudapi.sms.v20210111.SmsClient;
  8. import com.tencentcloudapi.sms.v20210111.models.SendSmsRequest;
  9. import com.tencentcloudapi.sms.v20210111.models.SendSmsResponse;
  10. import com.tencentcloudapi.sms.v20210111.models.SendStatus;
  11. import org.slf4j.Logger;
  12. import org.slf4j.LoggerFactory;
  13. /**
  14. * @author rtxtitanv
  15. * @version 1.0.0
  16. * @name com.rtxtitanv.util.SmsUtil
  17. * @description 腾讯云短信工具类
  18. * @date 2021/6/25 16:21
  19. */
  20. public class SmsUtil {
  21. private static final Logger LOGGER = LoggerFactory.getLogger(SmsUtil.class);
  22. /**
  23. * 发送短信
  24. *
  25. * @param smsConfig 腾讯云短信配置对象
  26. * @param templateParams 模板参数
  27. * @param phoneNumbers 手机号数组
  28. * @return SendStatus[],短信发送状态
  29. */
  30. public static SendStatus[] sendSms(SmsConfig smsConfig, String[] templateParams, String[] phoneNumbers) {
  31. try {
  32. // 实例化一个认证对象,入参需要传入腾讯云账户密钥对secretId,secretKey。
  33. Credential cred = new Credential(smsConfig.getSecretId(), smsConfig.getSecretKey());
  34. // 实例化一个http选项,可选,没有特殊需求可以跳过
  35. HttpProfile httpProfile = new HttpProfile();
  36. // SDK默认使用POST方法
  37. httpProfile.setReqMethod("POST");
  38. // SDK有默认的超时时间,非必要请不要进行调整
  39. httpProfile.setConnTimeout(60);
  40. // 非必要步骤:实例化一个客户端配置对象,可以指定超时时间等配置
  41. ClientProfile clientProfile = new ClientProfile();
  42. // SDK默认用TC3-HMAC-SHA256进行签名,非必要请不要修改这个字段
  43. clientProfile.setSignMethod("HmacSHA256");
  44. clientProfile.setHttpProfile(httpProfile);
  45. // 实例化要请求产品(以sms为例)的client对象,第二个参数是地域信息,可以直接填写字符串ap-guangzhou,或者引用预设的常量
  46. SmsClient smsClient = new SmsClient(cred, "ap-guangzhou", clientProfile);
  47. // 实例化一个请求对象
  48. SendSmsRequest req = new SendSmsRequest();
  49. // 设置短信应用ID:短信SdkAppId在[短信控制台]添加应用后生成的实际SdkAppId
  50. req.setSmsSdkAppId(smsConfig.getAppId());
  51. // 设置短信签名内容:使用UTF-8编码,必须填写已审核通过的签名,签名信息可登录[短信控制台]查看
  52. req.setSignName(smsConfig.getSign());
  53. // 设置国际/港澳台短信SenderId:国内短信填空,默认未开通
  54. req.setSenderId("");
  55. // 设置模板ID:必须填写已审核通过的模板ID。模板ID可登录[短信控制台]查看
  56. req.setTemplateId(smsConfig.getTemplateId());
  57. // 设置下发手机号码,采用E.164标准,+[国家或地区码][手机号]
  58. req.setPhoneNumberSet(phoneNumbers);
  59. // 设置模板参数:若无模板参数,则设置为空
  60. req.setTemplateParamSet(templateParams);
  61. // 通过client对象调用SendSms方法发起请求。注意请求方法名与请求对象是对应的,返回的res是一个SendSmsResponse类的实例,与请求对象对应
  62. SendSmsResponse res = smsClient.SendSms(req);
  63. // 控制台打印日志输出json格式的字符串回包
  64. LOGGER.info(SendSmsResponse.toJsonString(res));
  65. return res.getSendStatusSet();
  66. } catch (TencentCloudSDKException e) {
  67. e.printStackTrace();
  68. throw new RuntimeException(e.getMessage());
  69. }
  70. }
  71. }

Redis工具类:

  1. package com.rtxtitanv.util;
  2. import org.springframework.data.redis.core.RedisTemplate;
  3. import org.springframework.stereotype.Component;
  4. import javax.annotation.Resource;
  5. import java.util.concurrent.TimeUnit;
  6. /**
  7. * @author rtxtitanv
  8. * @version 1.0.0
  9. * @name com.rtxtitanv.util.RedisUtil
  10. * @description Redis工具类
  11. * @date 2021/6/26 12:24
  12. */
  13. @Component
  14. public class RedisUtil {
  15. @Resource
  16. private RedisTemplate<String, Object> redisTemplate;
  17. /**
  18. * 缓存基本对象
  19. *
  20. * @param key 键
  21. * @param value 值
  22. * @param expire 键的过期时间
  23. */
  24. public void setCacheObject(String key, Object value, long expire) {
  25. redisTemplate.opsForValue().set(key, value);
  26. if (expire > 0) {
  27. redisTemplate.expire(key, expire, TimeUnit.MINUTES);
  28. }
  29. }
  30. /**
  31. * 获取指定键的缓存对象
  32. *
  33. * @param key 键
  34. * @return 缓存对象
  35. */
  36. public Object getCacheObject(String key) {
  37. return redisTemplate.opsForValue().get(key);
  38. }
  39. /**
  40. * 判断键是否存在并且未过期
  41. *
  42. * @param key 键
  43. * @return true,键存在并且未过期;false,键不存在或存在但过期
  44. */
  45. public boolean hasKey(String key) {
  46. return redisTemplate.hasKey(key) && getExpire(key) > 0 ? true : false;
  47. }
  48. /**
  49. * 获取键的过期时间
  50. *
  51. * @param key 键
  52. * @return 过期时间
  53. */
  54. public long getExpire(String key) {
  55. return redisTemplate.getExpire(key, TimeUnit.MINUTES);
  56. }
  57. /**
  58. * 删除指定键的缓存
  59. *
  60. * @param key 键
  61. */
  62. public void delete(String key) {
  63. redisTemplate.delete(key);
  64. }
  65. /**
  66. * 创建缓存的键
  67. *
  68. * @param prefix 前缀
  69. * @param phoneNumber 手机号
  70. * @return 键
  71. */
  72. public static String createCacheKey(String prefix, String phoneNumber) {
  73. return prefix + phoneNumber;
  74. }
  75. }

用于生成随机验证码的工具类:

  1. package com.rtxtitanv.util;
  2. import java.util.Random;
  3. /**
  4. * @author rtxtitanv
  5. * @version 1.0.0
  6. * @name com.rtxtitanv.util.RandomUtil
  7. * @description Random工具类
  8. * @date 2021/6/26 11:39
  9. */
  10. public class RandomUtil {
  11. private static final Random RANDOM = new Random();
  12. /**
  13. * 生成指定位数的随机数字字符串
  14. *
  15. * @param length 字符串长度
  16. * @return 随机数字字符串
  17. */
  18. public static String randomNumbers(int length) {
  19. StringBuilder randomNumbers = new StringBuilder();
  20. for (int i = 0; i < length; i++) {
  21. randomNumbers.append(RANDOM.nextInt(10));
  22. }
  23. return randomNumbers.toString();
  24. }
  25. }

5.Controller层

  1. package com.rtxtitanv.controller;
  2. import com.rtxtitanv.service.SmsService;
  3. import org.springframework.web.bind.annotation.PostMapping;
  4. import org.springframework.web.bind.annotation.RequestMapping;
  5. import org.springframework.web.bind.annotation.RequestParam;
  6. import org.springframework.web.bind.annotation.RestController;
  7. import javax.annotation.Resource;
  8. /**
  9. * @author rtxtitanv
  10. * @version 1.0.0
  11. * @name com.rtxtitanv.controller.SmsController
  12. * @description SmsController
  13. * @date 2021/6/25 16:20
  14. */
  15. @RequestMapping("/sms")
  16. @RestController
  17. public class SmsController {
  18. @Resource
  19. private SmsService smsService;
  20. @PostMapping("/send")
  21. public String sendSmsCode(@RequestParam(value = "phoneNumber") String phoneNumber) {
  22. return smsService.sendSmsCode(phoneNumber);
  23. }
  24. @PostMapping("/verify")
  25. public String verifySmsCode(@RequestParam(value = "phoneNumber") String phoneNumber,
  26. @RequestParam(value = "smsCode") String smsCode) {
  27. return smsService.verifySmsCode(phoneNumber, smsCode);
  28. }
  29. }

6.Service层

  1. package com.rtxtitanv.service;
  2. /**
  3. * @author rtxtitanv
  4. * @version 1.0.0
  5. * @name com.rtxtitanv.service.SmsService
  6. * @description SmsService
  7. * @date 2021/6/25 16:20
  8. */
  9. public interface SmsService {
  10. /**
  11. * 发送短信验证码
  12. *
  13. * @param phoneNumber 手机号
  14. * @return
  15. */
  16. String sendSmsCode(String phoneNumber);
  17. /**
  18. * 验证短信验证码
  19. *
  20. * @param phoneNumber 手机号
  21. * @param smsCode 短信验证码
  22. * @return
  23. */
  24. String verifySmsCode(String phoneNumber, String smsCode);
  25. }
  1. package com.rtxtitanv.service.impl;
  2. import com.rtxtitanv.config.SmsConfig;
  3. import com.rtxtitanv.service.SmsService;
  4. import com.rtxtitanv.util.RandomUtil;
  5. import com.rtxtitanv.util.RedisUtil;
  6. import com.rtxtitanv.util.SmsUtil;
  7. import com.tencentcloudapi.sms.v20210111.models.SendStatus;
  8. import org.springframework.stereotype.Service;
  9. import javax.annotation.Resource;
  10. /**
  11. * @author rtxtitanv
  12. * @version 1.0.0
  13. * @name com.rtxtitanv.service.impl.SmsServiceImpl
  14. * @description SmsService实现类
  15. * @date 2021/6/25 16:20
  16. */
  17. @Service
  18. public class SmsServiceImpl implements SmsService {
  19. @Resource
  20. private SmsConfig smsConfig;
  21. @Resource
  22. private RedisUtil redisUtil;
  23. @Override
  24. public String sendSmsCode(String phoneNumber) {
  25. // 下发手机号码,采用e.164标准,+[国家或地区码][手机号]
  26. String[] phoneNumbers = {"+86" + phoneNumber};
  27. // 生成6位随机数字字符串
  28. String smsCode = RandomUtil.randomNumbers(6);
  29. // 模板参数:若无模板参数,则设置为空(参数1为随机验证码,参数2为有效时间)
  30. String[] templateParams = {smsCode, smsConfig.getExpireTime()};
  31. // 发送短信验证码
  32. SendStatus[] sendStatuses = SmsUtil.sendSms(smsConfig, templateParams, phoneNumbers);
  33. if ("Ok".equals(sendStatuses[0].getCode())) {
  34. // 创建缓存的key
  35. String key = RedisUtil.createCacheKey(smsConfig.getPhonePrefix(), phoneNumber);
  36. // 将验证码缓存到redis并设置过期时间
  37. redisUtil.setCacheObject(key, smsCode, Long.parseLong(smsConfig.getExpireTime()));
  38. return "验证码发送成功";
  39. } else {
  40. return "验证码发送失败:" + sendStatuses[0].getMessage();
  41. }
  42. }
  43. @Override
  44. public String verifySmsCode(String phoneNumber, String smsCode) {
  45. // 创建key
  46. String key = RedisUtil.createCacheKey(smsConfig.getPhonePrefix(), phoneNumber);
  47. // 判断指定key是否存在并且未过期
  48. if (redisUtil.hasKey(key)) {
  49. // 验证输入的验证码是否正确
  50. if (smsCode.equals(redisUtil.getCacheObject(key))) {
  51. // 验证成功后删除验证码缓存
  52. redisUtil.delete(key);
  53. return "验证成功";
  54. } else {
  55. return "验证码错误";
  56. }
  57. } else {
  58. return "验证码已失效";
  59. }
  60. }
  61. }

四、腾讯云短信测试

运行项目,使用Postman进行接口测试。

1.发送短信验证码

发送如下POST请求以请求腾讯云短信服务向指定手机号发送短信验证码,请求地址为http://localhost:8080/sms/send

SpringBoot2.x 集成腾讯云短信的详细流程

Redis客户端查看发现验证码已经存到了Redis中:

SpringBoot2.x 集成腾讯云短信的详细流程

手机上也成功收到了验证码,说明发送短信成功:

SpringBoot2.x 集成腾讯云短信的详细流程

2.验证短信验证码

发送如下POST请求验证短信验证码,请求地址为http://localhost:8080/sms/verify,这里将验证码参数smscode设为不同于之前发送到手机的验证码来模拟验证码输入错误:

SpringBoot2.x 集成腾讯云短信的详细流程

再次发送如下POST请求验证短信验证码,这里输入正确的验证码:

SpringBoot2.x 集成腾讯云短信的详细流程

Redis客户端刷新发现验证码缓存已经删除:

SpringBoot2.x 集成腾讯云短信的详细流程

再次发送如下POST请求验证短信验证码,发现验证码已失效,满足短信验证码验证成功后就失效的业务需求:

SpringBoot2.x 集成腾讯云短信的详细流程

代码示例

Github:https://github.com/RtxTitanV/springboot-learning/tree/master/springboot2.x-learning/springboot-tencent-sms
Gitee:https://gitee.com/RtxTitanV/springboot-learning/tree/master/springboot2.x-learning/springboot-tencent-sms

到此这篇关于SpringBoot2.x 集成腾讯云短信的文章就介绍到这了,更多相关SpringBoot腾讯云短信内容请搜索快网idc以前的文章或继续浏览下面的相关文章希望大家以后多多支持快网idc!

原文链接:https://blog.csdn.net/RtxTitanV/article/details/118275639

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 SpringBoot2.x 集成腾讯云短信的详细流程 https://www.kuaiidc.com/105888.html

相关文章

发表评论
暂无评论