腾讯云短信使用

腾讯云短信使用

前言:这里介绍创建签名成功后,如何使用腾讯云发送短信。签名申请没有成功的小伙伴,文章末尾附本人微信,可以借大家使用。

本文章所用示例已上传github:git@github.com:Easesgr/service-sms.git

1. 信息准备

准备五个参数来完成短息发送的短信,分别是secretIdsecretKeysdkAppId signNametemplateId

腾讯云账户密钥对secretIdsecretKey
在这里插入图片描述

在这里插入图片描述

短信应用IDsdkAppId
在这里插入图片描述

短信签名内容(signName),必须填写已审核通过的签名
在这里插入图片描述

模板 ID(templateId ): 必须填写已审核通过的模板 ID
在这里插入图片描述

2.Springboot调用

注:这里只写方法在测试类里面测试,就不使用网络调用啦。

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

写入到配置文件中,方便后期修改

tencent:
  sms:
    secretId: 111
    secretKey: 111
    sdkAppId: 111
    templateId: 111
    signName: 111

注:这里信息来自上面准备的信息

2.3 创建静态实体类加载配置文件

能使这些配置只被加载一次,后面方便修改,降低耦合度

package com.anyi.sms.common;

import lombok.Getter;
import lombok.Setter;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

/**
 * @author 安逸i
 * @version 1.0
 */
@Getter
@Setter
@Component
@ConfigurationProperties(prefix = "tencent.sms")
public class SmsField implements InitializingBean {
    private String sdkAppId;
    private String secretId;
    private String secretKey;
    private String templateId;
    private String signName;

    public static String SDK_ID;
    public static String KEY_ID;
    public static String KEY_SECRET;
    public static String TEMPLATE_CODE;
    public static String SIGN_NAME;

    //当私有成员被赋值后,此方法自动被调用,从而初始化常量
    @Override
    public void afterPropertiesSet() throws Exception {
        SDK_ID = sdkAppId;
        KEY_ID = secretId;
        KEY_SECRET = secretKey;
        TEMPLATE_CODE = templateId;
        SIGN_NAME = signName;
    }
}
2.4 参考官网api调用方法

官网网址:https://cloud.tencent.com/document/product/382/43194

package com.anyi.sms.service.impl;

import com.anyi.sms.common.SmsField;
import com.anyi.sms.service.SmsService;
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;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;	

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * @author 安逸i
 * @version 1.0
 */
@Service
@Slf4j
public class SmsServiceImpl implements SmsService {


    @Override
    public void sendCode(String phone,String code) {
        try {

            /* 必要步骤:
             * 实例化一个认证对象,入参需要传入腾讯云账户密钥对secretId,secretKey。
             * 这里采用的是从环境变量读取的方式,需要在环境变量中先设置这两个值。
             * 你也可以直接在代码中写死密钥对,但是小心不要将代码复制、上传或者分享给他人,
             * 以免泄露密钥对危及你的财产安全。
             * SecretId、SecretKey 查询: https://console.cloud.tencent.com/cam/capi */
            Credential cred = new Credential(SmsField.KEY_ID,SmsField.KEY_SECRET);

            HttpProfile httpProfile = new HttpProfile();
            httpProfile.setReqMethod("POST");
            httpProfile.setConnTimeout(60);
            httpProfile.setEndpoint("sms.tencentcloudapi.com");

            /* 非必要步骤:
             * 实例化一个客户端配置对象,可以指定超时时间等配置
            */
            ClientProfile clientProfile = new ClientProfile();
            clientProfile.setSignMethod("HmacSHA256");
            clientProfile.setHttpProfile(httpProfile);
            SmsClient client = new SmsClient(cred, "ap-guangzhou",clientProfile);
            SendSmsRequest req = new SendSmsRequest();

            // 设置 appid
            String appid = SmsField.SDK_ID;
            req.setSmsSdkAppid(appid);

            // 设置 signName 设置签名
            String signName = SmsField.SIGN_NAME;
            req.setSign(signName);

            // 设置 templateID 模板id
            String templateID = SmsField.TEMPLATE_CODE;
            req.setTemplateID(templateID);

            String[] templateParams = {code};

            phone = "+86" + phone;
            String[] phoneNumbers = {phone};
            req.setPhoneNumberSet(phoneNumbers);
            // 执行发送
            req.setTemplateParamSet(templateParams);
            SendSmsResponse res = client.SendSms(req);
            // 输出一下结果
            log.info(SendSmsResponse.toJsonString(res));
            // 发送成功后,可以在此处将验证码 存入redis里面,方便后面验证
            
            // 没有自己调试的时候,可以暂时在控制塔输出
            log.info(code);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
2.5 最终项目目录

在这里插入图片描述

  • controller
package com.anyi.sms.controller;

import cn.hutool.core.util.RandomUtil;
import com.anyi.sms.service.SmsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

/**
 * @author 安逸i
 * @version 1.0
 */
@RestController
@RequestMapping("/api/sms")
//@CrossOrigin //跨域
@Slf4j
public class SmsController {

    @Resource
    private SmsService smsService;

    @GetMapping("/send/{phone}")
    public String sendCode(@PathVariable String phone){
        // 使用hutool工具类种RandomUtil 生成六位随机验证码
        String code = RandomUtil.randomNumbers(6);
        smsService.sendCode(phone,code);
        return "发送验证码成功";
    }
}
2.6 最终浏览器测试

image-20220828090100641.png在这里插入图片描述

手机收到短信

在这里插入图片描述

  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
您好!对于使用Spring Boot发送短信,您可以考虑使用腾讯云短信服务。下面是一个简单的示例代码,可以帮助您发送短信: 首先,您需要引入腾讯云短信的Java SDK依赖: ```xml <dependency> <groupId>com.github.qcloudsms</groupId> <artifactId>qcloudsms</artifactId> <version>3.1.0</version> </dependency> ``` 然后,您可以创建一个短信发送工具类,并使用腾讯云短信的API进行发送: ```java import com.github.qcloudsms.SmsSingleSender; import com.github.qcloudsms.SmsSingleSenderResult; import com.github.qcloudsms.httpclient.HTTPException; import java.io.IOException; public class TencentSmsUtil { // 替换成您的腾讯云短信 AppIDAppKey private static final int APP_ID = 12345678; private static final String APP_KEY = "your_app_key"; // 发送短信 public static void sendSms(String phoneNumber, String message) { try { SmsSingleSender sender = new SmsSingleSender(APP_ID, APP_KEY); SmsSingleSenderResult result = sender.send(0, "86", phoneNumber, message, "", ""); System.out.println(result); } catch (HTTPException e) { // HTTP响应异常 e.printStackTrace(); } catch (IOException e) { // 网络异常 e.printStackTrace(); } } } ``` 然后在您的Spring Boot应用程序中,您可以使用该工具类发送短信: ```java import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class YourApplication { public static void main(String[] args) { SpringApplication.run(YourApplication.class, args); // 发送短信 TencentSmsUtil.sendSms("手机号码", "短信内容"); } } ``` 请将上述代码中的"your_app_key"替换为您的腾讯云短信AppKey,"手机号码"替换为您要发送短信的手机号码,"短信内容"替换为您要发送的实际短信内容。 希望能对您有所帮助!如果还有其他问题,请随时提问。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值