SpringBoot集成腾讯云短信JDK,实现短信发送!!!

achong
2022-10-27 / 0 评论 / 66 阅读 / 正在检测是否收录...

腾讯云原文地址,原文更详细,我下面的代码略有修改,只保留了与发送短信相关的代码。
https://cloud.tencent.com/document/product/382/43194#.E5.8F.91.E9.80.81.E7.9F.AD.E4.BF.A1

腾讯云短信控制台: https://console.cloud.tencent.com/smsv2

短信签名、模板ID、短信应用ID
腾讯云短信.png


  • 项目pom文件引入腾讯云短信接口的sdk

            <dependency>
                <groupId>com.tencentcloudapi</groupId>
                <artifactId>tencentcloud-sdk-java</artifactId>
                <!-- go to https://search.maven.org/search?q=tencentcloud-sdk-java and get the latest version. -->
                <!-- 请到https://search.maven.org/search?q=tencentcloud-sdk-java查询所有版本,最新版本如下 -->
                <version>3.1.612</version>
            </dependency>
  • 配置tencentCloud.properties文件在resources目录下,用于保存腾讯云的用户API密钥

    tencent.cloud.secretId=AKc6Si**********BtQmvtiMo5me5S
    tencent.cloud.secretKey=NYWIuK**********spdIE1fPW
    tencent.cloud.sdkAppId=短信应用ID
    tencent.cloud.signName=短信签名内容
    tencent.cloud.templateId=模板 ID
  • 创建一个实体类,用于读取密钥与短信相关配置

    @Component
    @Data
    @PropertySource(value = "classpath:tencentCloud.properties", encoding = "UTF-8")
    @ConfigurationProperties(prefix = "tencent.cloud")
    public class TencentCloudProperties {
            // 腾讯云账户密钥对
      private String secretId;
      private String secretKey;
    
      // 短信应用ID
      private String sdkAppId ;
    
      // 短信签名内容
      private String signName ;
    
      // 模板 ID
      private String templateId ;
    }
  • 将发送短信相关代码封装成一个工具类

​ 经过封装后,调用该方法时只需传入手机号码和验证码,事后会返回SDK的一个短信发送结果封装类SendSmsResponse。

package com.achong.utils;

import com.achong.bean.TencentCloudProperties;

import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;

import com.tencentcloudapi.sms.v20210111.SmsClient;

// 注意 SendSmsRequest 和 SendSmsResponse 是在同一个包下
import com.tencentcloudapi.sms.v20210111.models.SendSmsRequest;
import com.tencentcloudapi.sms.v20210111.models.SendSmsResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class SMSUtils {

    @Autowired
    private TencentCloudProperties tencentCloudProperties;

    /**
     * 发送短信 post请求
     */
    public SendSmsResponse sendSMS(String phone, String verCode){

        System.out.println("==========================================");
        System.out.println(tencentCloudProperties.toString());
        System.out.println("==========================================");

        // 实例化一个认证对象,入参需要传入腾讯云账户密钥对secretId,secretKey。
        Credential cred = new Credential(tencentCloudProperties.getSecretId(),
                tencentCloudProperties.getSecretKey());

        /* 实例化要请求产品的client对象
         * 第一个参数是认证对象
         * 第二个参数是地域信息,可以直接填写字符串ap-guangzhou,支持的地域列表参考 https://cloud.tencent.com/document/api/382/52071#.E5.9C.B0.E5.9F.9F.E5.88.97.E8.A1.A8 */
        SmsClient client = new SmsClient(cred, "ap-guangzhou");

        // 实例化一个请求对象,根据调用的接口和实际情况,可以进一步设置请求参数
        SendSmsRequest request = new SendSmsRequest();

        /**
         * 以下是填充请求信息
         */
        /* 短信应用ID: 短信SdkAppId在 [短信控制台] 添加应用后生成的实际SdkAppId,示例如1400006666 */
        // 应用 ID 可前往 [短信控制台](https://console.cloud.tencent.com/smsv2/app-manage) 查看
        request.setSmsSdkAppId(tencentCloudProperties.getSdkAppId());

        /* 短信签名内容: 使用 UTF-8 编码,必须填写已审核通过的签名 */
        // 签名信息可前往 [国内短信](https://console.cloud.tencent.com/smsv2/csms-sign) 或 [国际/港澳台短信](https://console.cloud.tencent.com/smsv2/isms-sign) 的签名管理查看
        request.setSignName(tencentCloudProperties.getSignName());

        /* 模板 ID: 必须填写已审核通过的模板 ID */
        // 模板 ID 可前往 [国内短信](https://console.cloud.tencent.com/smsv2/csms-template) 或 [国际/港澳台短信](https://console.cloud.tencent.com/smsv2/isms-template) 的正文模板管理查看
        request.setTemplateId(tencentCloudProperties.getTemplateId());

        /* 模板参数: 模板参数的个数需要与 TemplateId 对应模板的变量个数保持一致,若无模板参数,则设置为空 */
        String[] templateParamSet = {verCode};
        request.setTemplateParamSet(templateParamSet);

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

        /* 通过 client 对象调用 SendSms 方法发起请求。注意请求方法名与请求对象是对应的
         * 返回的 response 是一个 SendSmsResponse 类的实例,与请求对象对应 */
        SendSmsResponse response = null;
        try {
            response = client.SendSms(request);
        } catch (TencentCloudSDKException e) {
            e.printStackTrace();
        }



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

        //方法将返回 短信发送结果 的对象
        return response;
    }

}
  • 创建Controller

调用上面封装的工具类发送短信进行测试。

package com.achong.controller;

import com.achong.utils.SMSUtils;
import com.tencentcloudapi.sms.v20210111.models.SendSmsResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class SendSMSController {

    @Autowired
    private SMSUtils smsUtils;

    @RequestMapping("/sendSms")
    public void sendSms(String phone){

        if (phone == null || phone == "" || phone.length() != 11) {
            System.out.println("手机号错误");
            return;
        }

        // 本地生成四位数验证码,短信位数可调整 10000 的位数
        String code = (int)((Math.random() * 9 + 1) * 10000) + "";

        // 调用工具类发送短信,参数分别是 手机号码 和 验证码。
        SendSmsResponse response =  smsUtils.sendSMS(phone, code);

        // 格式化打印输出短信发送结果
        System.out.println(SendSmsResponse.toJsonString(response));

        // 拿到 短信发送结果 里的 Code 字段,该字段表示 短信是否发送成功
        String status = response.getSendStatusSet()[0].getCode();

        if ("Ok".equals(status)){
            System.out.println("发送成功,状态码:"+status);
        }else {
            System.out.println("发送失败,状态码:"+status);
        }

    }
}
  • 浏览器测试

访问地址:http://localhost:8080/sendSms?phone=17310101010

发送成功后,页面会返回短信发送结果,格式为 JSON字符串,其中Code字段为短信发送结果,成功则该字段为Ok,否则是其他错误信息。该字段可以作为判断短信发送是否成功的依据。

        {
            "SendStatusSet": [{
            "SerialNo": "3369:76164835516668596094641947",  发送流水号。
            "PhoneNumber": "+8617310101010",                手机号码,E.164标准,+[国家或地区码][手机号] ,示例如:+8613711112222, 其中前面有一个+号 ,86为国家码,13711112222为手机号。
                    "Fee": 1,       计费条数
                    "SessionContext": "",       用户 session 内容。
                    "Code": "Ok",           短信请求错误码
                    "Message": "send success",      短信请求错误码描述。
                    "IsoCode": "CN"         国家码或地区码,例如 CN、US 等,对于未识别出国家码或者地区码,默认返回 DEF
        }],
            "RequestId": "b9a8468f-12bb-4985-bda7-5592d56f98bd"
        }
2

评论 (0)

取消
粤ICP备18061175号-3