腾讯云短信平台集成

本文详细描述了如何通过pom.xml引入腾讯云短信SDK,配置SpringBoot应用并实现短信验证码的发送功能。
摘要由CSDN通过智能技术生成

API文档:短信 发送短信-API 文档-文档中心-腾讯云

1.依赖:在pom.xml添加腾讯云短信SDK

     <dependency>
            <groupId>com.tencentcloudapi</groupId>
            <artifactId>tencentcloud-sdk-java</artifactId>
            <version>3.1.789</version>
        </dependency>

2.配置类:创建配置类SmsAutoConfiguration,将参数属性和实现类加入IOC容器管理,相当于注解@Component和@Service,注解@ConditionalOnProperty(prefix = "tencent.sms",name = "templateId")会先将配置文件中的属性加载成功后,在开始Bean初始化,初始化成功之后配置类才会生效。这样做的好处在于启动时能够先查看参数配置是否完整。

假设没有配置参数,那么Bean创建失败,在业务层加载时就会出现Bean不存在的错误。

@Configuration
//当classPath中 配置文件配置了 tencent.sms.templateId key ,然后再加载@Bean到容器中
@ConditionalOnProperty(prefix = "tencent.sms",name = "templateId")
public class SmsAutoConfiguration {
    @Bean
    public TencentSmsServiceImpl tencentSmsService(){
        return new TencentSmsServiceImpl();
    }

    @Bean
    @ConfigurationProperties(prefix = "tencent.sms")
    public SmsProperties properties(){
        return new SmsProperties();
    }
}

3.参数:封装参数类

@Setter
@Getter
//从配置文件获取tencent.sms配置属性绑定到下面的属性中
public class SmsProperties {
    private String secretId;
    private String secretKey;
    private String smsSdkAppId;
    private String signName;
    private String templateId;
}

在配置中心中找到所属的服务并在配置参数的属性,属性均在短信平台中获取

tencent:
  sms:
    secretId: 安全ID
    secretKey: 安全密钥
    smsSdkAppId: 短信平台AppId
    signName: 签名
    templateId: 短信模板ID


4.接口:将参数(验证码,验证码存活时间)封装成List集合

Arrays.asList(code,SystemConstant.VERIFY_CODE_TIME+""),phone
public interface ISmsService {

    //发短信
    void sendSms(List<String> param,String...phones);
}

5.实现类

public class TencentSmsServiceImpl implements ISmsService {


    @Autowired
    private SmsProperties smsProperties;


    @Override
    public void sendSms(List<String> param, String...phones) {
        //3.手机发送短信
        try{
            Credential cred = new Credential(smsProperties.getSecretId(),smsProperties.getSecretKey());
            // 实例化一个http选项,可选的,没有特殊需求可以跳过
            HttpProfile httpProfile = new HttpProfile();
            httpProfile.setEndpoint("sms.tencentcloudapi.com");
            // 实例化一个client选项,可选的,没有特殊需求可以跳过
            ClientProfile clientProfile = new ClientProfile();
            clientProfile.setHttpProfile(httpProfile);
            // 实例化要请求产品的client对象,clientProfile是可选的
            SmsClient client = new SmsClient(cred, "ap-guangzhou", clientProfile);
            // 实例化一个请求对象,每个接口都会对应一个request对象
            SendSmsRequest req = new SendSmsRequest();
            String[] phoneNumberSet1 = phones;
            req.setPhoneNumberSet(phoneNumberSet1);

            req.setSmsSdkAppId(smsProperties.getSmsSdkAppId());//appId
            req.setSignName(smsProperties.getSignName());//签名
            req.setTemplateId(smsProperties.getTemplateId());//模板

            String[] templateParamSet1 = param.toArray(new String[]{});//模板参数
            req.setTemplateParamSet(templateParamSet1);

            // 返回的resp是一个SendSmsResponse的实例,与请求对象对应
            SendSmsResponse resp = client.SendSms(req);
            // 输出json格式的字符串回包
            System.out.println(SendSmsResponse.toJsonString(resp));

            for (int i = 0; i < phones.length; i++) {
                //发短信结果处理
                if (!resp.getSendStatusSet()[i].getCode().equalsIgnoreCase("ok")) {
                    throw new ServiceException("短信发送失败");
                }
            }

        } catch (TencentCloudSDKException e) {
            System.out.println(e.toString());
        }

    }
}

6.接口控制层

@PostMapping("/sendVerifyCode")
    public R<?> sendVerifyCode(String phone){
        pcLoginService.sendVerifyCode(phone);
        return R.ok();
    }

7.逻辑业务层

public void sendVerifyCode(String phone) {
        if (!RegexUtils.isPhoneLegal(phone)) {
            throw new ServiceException("手機格式錯吳");
        }


        //1.创建验证码
        String code = UUID.randomUUID().toString().replaceAll("-", "").substring(0, 4);
        //2.拼接短信
        StringBuilder stringBuilder = new StringBuilder(80);
        stringBuilder.append("【腾讯云平台】你的登录验证码为").append(code)
                .append(",请在").append(SystemConstant.VERIFY_CODE_TIME).append("分钟内完成注册");


        //4.将验证码存到redis
        /*String key = "verify_code:" + phone;*/
        //直接編寫前綴可能会写错

     /*   //方式一: 定義常量
        String key = SystemConstant.VERIFY_CODE_PREFIX + phone;
        redisService.setCacheObject(key,code,SystemConstant.VERIFY_CODE_TIME * 60L, TimeUnit.SECONDS);
*/
        //方式二:定义枚举类
        String key1 = RedisKeys.VERIFY_CODE.join(phone);
        redisService.setCacheObject(key1,code,RedisKeys.VERIFY_CODE.getTime(),TimeUnit.SECONDS);

        //3.手机发送短信
        System.out.println(stringBuilder);
        smsService.sendSms(Arrays.asList(code,SystemConstant.VERIFY_CODE_TIME+""),phone);

    }
}

  • 7
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值