SpringBoot使用腾讯云实现短信功能

引入依赖

<!-- 腾讯云依赖 -->
<dependency>
    <groupId>com.tencentcloudapi</groupId>
    <artifactId>tencentcloud-sdk-java</artifactId>
    <version>3.1.270</version>
</dependency>

配置文件

# 腾讯云短信配置
sms:
  tencentcloud:
    enabled: true
    region-id: xxx
    app-id: xxx
    secret-id: xxx
    secret-key: xxx
    sign-name: xxx
    template-id: xxx

属性类

package com.qiangesoft.sms.tencentcloud.config;

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;

/**
 * 腾讯云短信属性
 *
 * @author qiangesoft
 * @date 2024-04-30
 */
@Data
@ConfigurationProperties(prefix = "sms.tencentcloud")
public class TencentcloudSmsProperties {

    /**
     * 是否启用
     */
    private boolean enabled = true;

    /**
     * 地域id
     */
    private String regionId;
    
    /**
     * appId
     */
    private String appId;

    /**
     * secretId
     */
    private String secretId;

    /**
     * secretKey
     */
    private String secretKey;

    /**
     * 短信签名
     */
    private String signName;

    /**
     * 模板Id
     */
    private String templateId;

}

配置类

package com.qiangesoft.sms.tencentcloud.config;

import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.sms.v20210111.SmsClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 腾讯云短信配置
 *
 * @author qiangesoft
 * @date 2024-04-30
 */
@Configuration
@EnableConfigurationProperties(TencentcloudSmsProperties.class)
@ConditionalOnProperty(prefix = "sms.tencentcloud", name = "enabled", havingValue = "true")
public class TencentcloudSmsConfiguration {

    private static final String ENDPOINT = "sms.tencentcloudapi.com";

    @Autowired
    private TencentcloudSmsProperties tencentcloudSmsProperties;

    @Bean
    @ConditionalOnMissingBean
    public SmsClient smsClient() {
        // 实例化一个认证对象
        Credential cred = new Credential(tencentcloudSmsProperties.getSecretId(), tencentcloudSmsProperties.getSecretKey());

        // 实例化一个http选项,可选
        HttpProfile httpProfile = new HttpProfile();
        httpProfile.setReqMethod("POST");
        httpProfile.setConnTimeout(60);
        httpProfile.setEndpoint(ENDPOINT);

        // 实例化一个客户端配置对象
        ClientProfile clientProfile = new ClientProfile();
        // SDK默认用TC3-HMAC-SHA256进行签名,非必要请不要修改这个字段
        clientProfile.setSignMethod("HmacSHA256");
        clientProfile.setHttpProfile(httpProfile);
        return new SmsClient(cred, tencentcloudSmsProperties.getRegionId(), clientProfile);
    }

}

短信发送实现

package com.qiangesoft.sms.tencentcloud.handler;

import com.qiangesoft.sms.tencentcloud.config.TencentcloudSmsProperties;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.sms.v20210111.SmsClient;
import com.tencentcloudapi.sms.v20210111.models.SendSmsRequest;
import com.tencentcloudapi.sms.v20210111.models.SendSmsResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * 腾讯云短信处理器
 *
 * @author qiangesoft
 * @date 2023-05-16
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class TencentcloudSendHandler {

    private final SmsClient smsClient;

    private final TencentcloudSmsProperties tencentcloudSmsProperties;

    public boolean send(String[] phones, String[] params) {
        return this.send(phones, tencentcloudSmsProperties.getTemplateId(), params);
    }

    public boolean send(String[] phones, String templateId, String[] params) {
        // 填充请求参数
        SendSmsRequest req = new SendSmsRequest();
        req.setSmsSdkAppId(tencentcloudSmsProperties.getAppId());
        req.setSignName(tencentcloudSmsProperties.getSignName());
        req.setTemplateId(templateId);
        req.setTemplateParamSet(params);
        req.setPhoneNumberSet(phones);

        try {
            // 方法发起请求
            SendSmsResponse res = smsClient.SendSms(req);
        } catch (TencentCloudSDKException e) {
            throw new RuntimeException(e);
        }
        return false;
    }

}

测试

package com.qiangesoft.sms.tencentcloud.controller;

import com.qiangesoft.sms.tencentcloud.handler.TencentcloudSendHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 短信测试
 *
 * @author qiangesoft
 * @date 2024-04-30
 */
@RequestMapping("/tsms")
@RestController
public class TSmsController {

    @Autowired
    private TencentcloudSendHandler tencentcloudSendHandler;

    @GetMapping("/send")
    public Boolean send() {
        String[] params = {"张三", "23"};
        return tencentcloudSendHandler.send(new String[]{"15883968757"}, params);
    }

}

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 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
发出的红包

打赏作者

PG_强哥

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

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

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

打赏作者

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

抵扣说明:

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

余额充值