springboot整合腾讯云短信服务

本来是打算使用阿里云的,但是发现阿里云短信申请签名的时候现在不允许个人申请了,因此改用腾讯云短信服务

首先登录腾讯云官方网站:搜索短信,点击免费试用

个人用户申请开通之后可以看到可以免费使用100条短信(学习来说够用了)

 然后进行短信签名的申请:

 我选择类型是公众号(因为我真的有公众号),大家以个人需求为准

第二步创建正文模板 :

第三步等待审核:

 

过了两个小时,一看签名和短信模板都审核通过了,那就开始搞springboot整合

直接按照腾讯官方文档进行整合,在腾讯云里面搜索短信,点击api,如下图:

看java SDK相关的部分即可:

 

首先是需要准备SecretID 和SecretKey ,调用短信接口需要用到:

 

官方提供的短信接口文档地址:短信 Java SDK - SDK 文档 - 文档中心 - 腾讯云

                                        短信 数据结构 - API 中心 - 腾讯云 

根据官网文档所示添加短信依赖:

<dependency>
     <groupId>com.tencentcloudapi</groupId>
     <artifactId>tencentcloud-sdk-java</artifactId>
     <version>3.1.270</version><!-- 注:这里只是示例版本号(可直接使用),可获取并替换为 最新的版本号,注意不要使用4.0.x版本(非最新版本) -->
</dependency>

controller代码如下:

package com.example.txsmsboot.controller;

import com.example.txsmsboot.service.TxSmsService;
import com.example.txsmsboot.util.RandomUtil;
import com.example.txsmsboot.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/api/sms")
public class TxSmsController {

    @Autowired
    private TxSmsService txSmsService;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @RequestMapping("send/{phone}")
    public Result senTxdCode(@PathVariable String phone) {
        /**
         * 判断手机号是否为空
         */
        if (StringUtils.isEmpty(phone)) {
            Assert.isNull(phone, "手机号不允许为空哦");
        }
        /**
         * 发送短信验证码
         * 首先从redis里面获取,redis里面能够获取到就直接发送给用户
         * 如果redis里面获取不到证明上一条验证码已过期,重新生成验证发给用户
         * 目前叮咚买菜app/支付宝就是按照这样的逻辑做的
         */
        String code = redisTemplate.opsForValue().get(phone);
        if (StringUtils.isEmpty(code)) {
            code = RandomUtil.getSixBitRandom();
        }
        /**
         * 拿到phone、和code进行验证码发送
         */
        boolean isSend = txSmsService.sendSms(phone, code);
        if (isSend) {
            /**
             * 放到redis里面
             */
            redisTemplate.opsForValue().set(phone, code, 2, TimeUnit.MINUTES);
            return Result.ok();
        } else {
            return Result.fail().message("发送短信失败");
        }

    }
}

service代码:

 serviceImpl代码:

package com.example.txsmsboot.service.impl;

import com.example.txsmsboot.service.TxSmsService;
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.SendSmsRequest;
import com.tencentcloudapi.sms.v20210111.models.SendSmsResponse;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

@Service
public class TxSmsServiceImpl implements TxSmsService {

    /**
     * 获取配置文件中腾讯云相关信息(从配置文件获取)
     */
    @Value("${tx.sms.secretID}")
    private String secretID;

    @Value("${tx.sms.secretKey}")
    private String secretKey;

    @Override
    public boolean sendSms(String phone, String code) {
        try {


            // 整合腾讯云短信服务发送
            Credential cred = new Credential(secretID, secretKey);
            // 实例化一个http选项,可选,没有特殊需求可以跳过
            HttpProfile httpProfile = new HttpProfile();
            httpProfile.setReqMethod("POST");
            /* SDK有默认的超时时间,非必要请不要进行调整
             * 如有需要请在代码中查阅以获取最新的默认值 */
            httpProfile.setConnTimeout(60);
            /* 指定接入地域域名,默认就近地域接入域名为 sms.tencentcloudapi.com ,也支持指定地域域名访问,例如广州地域的域名为 sms.ap-guangzhou.tencentcloudapi.com */
            httpProfile.setEndpoint("sms.tencentcloudapi.com");

            /* 非必要步骤:
             * 实例化一个客户端配置对象,可以指定超时时间等配置 */
            ClientProfile clientProfile = new ClientProfile();
            /* SDK默认用TC3-HMAC-SHA256进行签名
             * 非必要请不要修改这个字段 */
            clientProfile.setSignMethod("HmacSHA256");
            clientProfile.setHttpProfile(httpProfile);

            SmsClient client = new SmsClient(cred, "ap-guangzhou", clientProfile);
            /* 实例化一个请求对象,根据调用的接口和实际情况,可以进一步设置请求参数
             * 你可以直接查询SDK源码确定接口有哪些属性可以设置
             * 属性可能是基本类型,也可能引用了另一个数据结构
             * 推荐使用IDE进行开发,可以方便的跳转查阅各个接口和数据结构的文档说明 */
            SendSmsRequest req = new SendSmsRequest();

            /* 填充请求参数,这里request对象的成员变量即对应接口的入参
             * 你可以通过官网接口文档或跳转到request对象的定义处查看请求参数的定义
             * 基本类型的设置:
             * 帮助链接:
             * 短信控制台: https://console.cloud.tencent.com/smsv2
             * sms helper: https://cloud.tencent.com/document/product/382/3773 */

            /* 短信应用ID: 短信SdkAppId在 [短信控制台] 添加应用后生成的实际SdkAppId,示例如1400006666 */
            String sdkAppId = "自己sdkAppid";
            req.setSmsSdkAppId(sdkAppId);

            /* 短信签名内容: 使用 UTF-8 编码,必须填写已审核通过的签名,签名信息可登录 [短信控制台] 查看 */
            String signName = "程序员久书";
            req.setSignName(signName);

            /* 国际/港澳台短信 SenderId: 国内短信填空,默认未开通,如需开通请联系 [sms helper] */
            String senderid = "";
            req.setSenderId(senderid);

            /* 用户的 session 内容: 可以携带用户侧 ID 等上下文信息,server 会原样返回 */
            String sessionContext = "xxx";
            req.setSessionContext(sessionContext);

            /* 短信号码扩展号: 默认未开通,如需开通请联系 [sms helper] */
            String extendCode = "";
            req.setExtendCode(extendCode);

            /* 模板 ID: 必须填写已审核通过的模板 ID。模板ID可登录 [短信控制台] 查看 */
            String templateId = "自己模板id";
            req.setTemplateId(templateId);

            /* 下发手机号码,采用 E.164 标准,+[国家或地区码][手机号]
             * 示例如:+8613711112222, 其中前面有一个+号 ,86为国家码,13711112222为手机号,最多不要超过200个手机号 */
            //String[] phoneNumberSet = {"+8618777777777", "+8615888888888","+8618555555555","+8618333333333","+8613566666666"};
            String[] phoneNumberSet = {phone};
            req.setPhoneNumberSet(phoneNumberSet);

            /* 模板参数: 若无模板参数,则设置为空 */
            String[] templateParamSet = {code};
            req.setTemplateParamSet(templateParamSet);

            /* 通过 client 对象调用 SendSms 方法发起请求。注意请求方法名与请求对象是对应的
             * 返回的 res 是一个 SendSmsResponse 类的实例,与请求对象对应 */
            SendSmsResponse res = client.SendSms(req);

            // 输出json格式的字符串回包
            System.out.println(SendSmsResponse.toJsonString(res));

            // 也可以取出单个值,你可以通过官网接口文档或跳转到response对象的定义处查看返回字段的定义
            System.out.println(res.getSendStatusSet()[0].getCode());
            if ("Ok".equals(res.getSendStatusSet()[0].getCode())) {
                return true;
            }
        } catch (TencentCloudSDKException e) {
            e.printStackTrace();
            return false;
        }
        return false;
    }
}

主要用到了下面几个参数:

1、SecretID 和SecretKey的获取上面已经有介绍

2、sdkAppId:在应用列表里面找

3、短信签名内容:在签名管理里面

4、模板id-templateId:就是自己申请的模板id

然后我启动服务访问下发短信接口:

然后我去redis里面看下是否已经放入缓存:

 

可以看到是正常的,我的缓存时间设置的是2s,2s后缓存内容就会失效

演示所用到的代码已经上传到csdn了,有需要的可以关注下公众号联系博主获取哦 

 

  • 2
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 4
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

酒书

你的鼓励是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值