使用腾讯云短信服务实现Spring Boot短信发送

01 注册微信公众号

在百度搜索微信公众平台,并在进入官网后注册。在账号注册过程中,需选择订阅号(个人)。注册成功后,请保存账号详情的截图,以备后续腾讯云短信签名申请之用。

02 注册腾讯云账号

你可以按照以下步骤登录并注册腾讯云,并进行个人实名认证:

  1. 打开腾讯云官网(腾讯云官网 ),点击右上角的“注册”按钮。

  2. 在注册页面中,填写邮箱、密码要什么就填什么

  3. 点击“注册”按钮后,进入填写个人信息的页面。

  4. 填写完毕后,会进入腾讯云的控制台页面。在这里可以购买云产品、管理云服务等。

  5. 为了完成个人实名认证流程,需要先进行手机验证。在控制台页面左侧的菜单中选择“账号中心”,然后点击“安全设置”-“手机验证”进行验证。

  6. 接下来,在账号中心页面的实名认证栏目中点击“去认证”按钮。

  7. 选择个人认证方式,并填写真实姓名、身份证号码等信息。上传身份证正反面照片,然后点击“提交”按钮。

  8. 完成实名认证后,等待审核通过即可。

以上就是登录腾讯云并完成个人实名认证流程的所有步骤。

当你通过审核后,请打开 腾讯云短信服务 ,在该页面上,你会看到免费试用的选项。请点击进入。

在这里插入图片描述

03 创建签名和模板

第一步 创建签名

按要求填写即可

  • 签名内容:你的微信公众号名字+公众号。例如:xxx公众号。
  • 经办人:你自己。
  • 申请说明:填写你的公众号全名。

在这里插入图片描述

第二部 创建模板

  • 模板名称:没有特别的要求,可以自由填写
  • 短信类型:普通短信
  • 短信内容:标准模板或者自己编写
  • 申请说明:短信模板的场景

例如,申请的短信模板为:

亲爱的{1}小朋友,祝你童节快乐!愿你们拥有纯真的笑容和快乐的时光。希望你在成长的路上,始终保持好奇心和勇气,用积极的态度面对一切挑战。祝你健康快乐,未来可期!

申请说明内容可以为:

这个短信模板用于向儿童节受众发送祝福信息,以表达节日的祝福和推崇儿童在成长中保持快乐、积极、勇敢等正向品质的意向。该短信模板为发送对象为儿童节受众而准备

在这里插入图片描述

04 发送短信

以下是使用Spring Boot和腾讯云短信服务SDK实现发送短信的详细步骤

这里是我所使用的正文模板

在这里插入图片描述

  1. 在项目的 maven pom.xml 文件中,添加以下依赖:
<!--        # 版本在maven生效需要时间,如获取不到对应的版本,可以调低版本号-->
<dependency>
    <groupId>com.tencentcloudapi</groupId>
    <artifactId>tencentcloud-sdk-java-sms</artifactId>
    <version>3.1.767</version>
</dependency>
  1. 在 Spring Boot 的 application.properties 或 application.yaml 中,添加腾讯云的 API 密钥和短信模板信息:
tencent:
  sms:
     # 腾讯云账户 secrtId,secretKey
    secretId: A*IDR1Vmob9*TKvlNjqhIdjZ9U**Np1yf8LJ
    keysecret: lHXX*n23pLb**tACzWnpb7NN7c*qZ2GF
    # 短信应用ID:短信SdkAppId在 【短信控制台】添加应用后生成实际的SdkAppId  
    smsSdkAppId: 1400800002
    # 短信签名内容:
    signName: 编程日记公众号
    # 模板ID:必须是已经审核通过的模板ID
    templateId: 1817797

在这里插入图片描述

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.v20190711.SmsClient;
import com.tencentcloudapi.sms.v20190711.models.SendSmsRequest;
import com.tencentcloudapi.sms.v20190711.models.SendSmsResponse;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.Random;

@Component
public class MsmConstantUtils implements InitializingBean {

    /** 腾讯云账户密钥对secretKey(在访问管理中配置) */
    @Value("${tencent.sms.secretId}")
    private String secretID ;
    /** 腾讯云账户密钥对secretKey(在访问管理中配置) */
    @Value("${tencent.sms.keysecret}")
    private String secretKey ;
    @Value("${tencent.sms.smsSdkAppId}")
    private String smsSdkAppID ;
    @Value("${tencent.sms.signName}")
    private String signName ;
    @Value("${tencent.sms.templateId}")
    private String templateID ;

    public static String SECRET_ID;
    public static String SECRET_KEY;
    public static String SMSSDKAPP_ID;
    public static String SIGN_NAME;
    public static String TEMPLATE_ID;


    @Override
    public void afterPropertiesSet() throws Exception {
        SECRET_ID = secretID;
        SECRET_KEY = secretKey;
        SMSSDKAPP_ID = smsSdkAppID;
        SIGN_NAME = signName;
        TEMPLATE_ID = templateID;
    }


    /**
     * 发送6位数字验证码到手机
     * @param sixBitRandom 验证码
     * @param phone 手机号
     * @return
     */
    public static boolean sendPhone(String sixBitRandom, String phone) {
        //判断手机号是否为空
        if (StringUtils.isEmpty(phone)) {
            return false;
        }
        try{
            // 实例化一个认证对象,入参需要传入腾讯云账户secretId,secretKey,此处还需注意密钥对的保密
            // 密钥可前往https://console.cloud.tencent.com/cam/capi网站进行获取
            Credential cred = new Credential(MsmConstantUtils.SECRET_ID, MsmConstantUtils.SECRET_KEY);
            // 实例化一个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-nanjing", clientProfile);
            // 实例化一个请求对象,每个接口都会对应一个request对象
            SendSmsRequest req = new SendSmsRequest();

            //设置发送相关的参数
            String[] phoneNumberSet1 = {"86"+phone};
            req.setPhoneNumberSet(phoneNumberSet1);//发送的手机号
            //设置固定的参数
            req.setSmsSdkAppid(MsmConstantUtils.SMSSDKAPP_ID);// 短信应用ID: 短信SdkAppId在 [短信控制台] 添加应用后生成的实际SdkAppId
            req.setSign(MsmConstantUtils.SIGN_NAME);//短信签名内容: 使用 UTF-8 编码,必须填写已审核通过的签名
            req.setTemplateID(MsmConstantUtils.TEMPLATE_ID);//模板 ID: 必须填写已审核通过的模板 ID
            //发送的验证码
            String[] templateParamSet1 = {sixBitRandom};//模板的参数 第一个是验证码,第二个是过期时间
            req.setTemplateParamSet(templateParamSet1);//发送验证码

            //发送短信
            // 返回的resp是一个SendSmsResponse的实例,与请求对象对应
            SendSmsResponse resp = client.SendSms(req);
            System.out.println("resp"+resp);
            // 输出json格式的字符串回包
            System.out.println(SendSmsResponse.toJsonString(resp));
            return true;
        } catch (TencentCloudSDKException e) {
            e.printStackTrace();
            return false;
        }
    }


    /**
     * 随机生成验证码
     * @param length 长度为4位或者6位
     * @return
     */
    public static String generateValidateCode(int length){
        Integer code =null;
        if(length == 4){
            code = new Random().nextInt(9999);//生成随机数,最大为9999
            if(code < 1000){
                code = code + 1000;//保证随机数为4位数字
            }
        }else if(length == 6){
            code = new Random().nextInt(999999);//生成随机数,最大为999999
            if(code < 100000){
                code = code + 100000;//保证随机数为6位数字
            }
        }else{
            throw new RuntimeException("只能生成4位或6位数字验证码");
        }
        return code.toString();
    }


}
  1. 在发送短信的控制器类中,使用 MsmConstantUtils类的sendPhone方法发送短信:
@RestController
@RequestMapping("/tencent")
public class tencentSmsController {


    @GetMapping("/test")
    public String test(String phone){
        boolean b = MsmConstantUtils.sendPhone(MsmConstantUtils.generateValidateCode(6), phone);
        return b ? "success":"fail";
    }

}

以上就是使用 Spring Boot 和腾讯云短信服务 SDK发送短信的详细步骤,希望对你有帮助!

  • 1
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Spring Boot项目中使用腾讯云发送短信,你可以按照以下步骤进行操作: 1. 首先,在腾讯云控制台上申请短信服务并获取相关的密钥信息,包括AppID、AppKey和模板ID等。 2. 在Spring Boot项目的pom.xml文件中添加腾讯云SDK的依赖,例如: ```xml <dependency> <groupId>com.tencentcloudapi</groupId> <artifactId>sms</artifactId> <version>3.1.40</version> </dependency> ``` 3. 创建一个发送短信的工具类,可以使用腾讯云提供的Java SDK,示例代码如下: ```java import com.tencentcloudapi.common.Credential; import com.tencentcloudapi.common.profile.ClientProfile; import com.tencentcloudapi.common.profile.HttpProfile; import com.tencentcloudapi.sms.v20190711.SmsClient; import com.tencentcloudapi.sms.v20190711.models.SendSmsRequest; import com.tencentcloudapi.sms.v20190711.models.SendSmsResponse; public class TencentCloudSmsUtil { private final static String SECRET_ID = "your_secret_id"; private final static String SECRET_KEY = "your_secret_key"; private final static String REGION_ID = "ap-guangzhou"; private final static String SMS_SIGN = "your_sms_sign"; // 短信签名,需要在腾讯云控制台申请 public static void sendSms(String phoneNumber, String templateParam) { try { Credential cred = new Credential(SECRET_ID, SECRET_KEY); HttpProfile httpProfile = new HttpProfile(); httpProfile.setEndpoint("sms.tencentcloudapi.com"); ClientProfile clientProfile = new ClientProfile(); clientProfile.setHttpProfile(httpProfile); SmsClient client = new SmsClient(cred, REGION_ID, clientProfile); SendSmsRequest req = new SendSmsRequest(); req.setSmsSdkAppid("your_appid"); // 在腾讯云控制台申请的短信SDK AppID req.setSign(SMS_SIGN); req.setTemplateID("your_template_id"); // 在腾讯云控制台申请的短信模板ID req.setPhoneNumberSet(new String[]{phoneNumber}); req.setTemplateParamSet(new String[]{templateParam}); SendSmsResponse res = client.SendSms(req); System.out.println(SendSmsResponse.toJsonString(res)); } catch (Exception e) { e.printStackTrace(); } } } ``` 4. 在需要发送短信的地方调用该工具类的`sendSms`方法,传入手机号和短信模板参数即可: ```java TencentCloudSmsUtil.sendSms("your_phone_number", "your_template_param"); ``` 注意替换代码中的`your_secret_id`、`your_secret_key`、`your_sms_sign`、`your_appid`和`your_template_id`为你自己的相关信息。 这样就可以在Spring Boot项目中使用腾讯云发送短信了。希望对你有帮助!

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

bilal-abdurehim

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

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

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

打赏作者

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

抵扣说明:

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

余额充值