Java calls Tencent Cloud to send SMS

This article is a process article from 0 to 1, using Java to connect Tencent SMS sending function. The 44 Dayang in the title is used to purchase SMS packages. Of course, if you are using Tencent Cloud Platform for the first time, you can enjoy the [Free Use] function (I am an old user).

Well, without further ado, let's look down at the docking steps.

1. SMS package

Let's buy the following SMS packages first, here we choose Tencent Cloud

Of course, we have two options for the package:

  1. free trial
  2. Buy

1) Take a look first, try it for free
insert image description here

Click SMS Service in Cloud Communication

insert image description here

2) Look again, buy a package
insert image description here

3) If you have purchased or have a trial package, your package information will be displayed here

insert image description here

Here I bought a package for 44 yuan, but it comes with 100 text messages, so I have a total of 1100 text messages to send.

2. SMS configuration

SMS configuration is mainly divided into three parts:

  1. sign
  2. template
  3. application

Enter the SMS console, and first complete the following parts:
insert image description here

Note: The type selected here is a personal website, so there must be domain name information that has been filed

There is no screenshot here for filling in the information. If you have a registered domain name, just follow the steps given by others and fill it in once. As for the SMS template, it is a piece of Chinese content that you want to send to the user. Of course, placeholders can also be reserved in it to change the content flexibly.

If the information is successfully filled in and approved, the following content will be echoed :
insert image description here

Then it's time to start creating the application:
insert image description here

3. Create your cloud API key
insert image description here

Ok, all our preparations have been done at this moment, then we should have the following resources at this time:

  1. SMS package (that is, how many text messages you can send)
  2. SMS signature
  3. SMS template
  4. application
  5. Cloud API

4. Java coding realizes SMS sending

Now everything is ready, just write the code to implement it. And because Tencent's API authentication is very complicated, Tencent suggested that we use the SDK provided by them for development, so the code writing this time also made some fine-tuning on its SDK.

1) Introduce dependencies:

<!-- 腾讯短信sdk -->
<dependency>
    <groupId>com.tencentcloudapi</groupId>
    <artifactId>tencentcloud-sdk-java</artifactId>
    <version>3.1.270</version>
</dependency>

2) Write SMS sending util

// 注意引入 lombok
@Slf4j
public class SendSmsUtil {
    
    

    public static Boolean sendSms(SendSmsRequest request) {
    
    
        Credential cred = new Credential(request.getSecretId(), request.getSecretKey());

        SmsClient client = new SmsClient(cred, "ap-guangzhou");

        final var req = new com.tencentcloudapi.sms.v20210111.models.SendSmsRequest();
        req.setPhoneNumberSet(new String[]{
    
    "+86" + request.getPhone()});
        req.setSmsSdkAppId(request.getSmsSdkAppId());
        req.setSignName(request.getSignName());
        req.setTemplateId(request.getTemplateId());
        req.setTemplateParamSet(request.getTemplateParamSet());

        SendSmsResponse res = null;
        try {
    
    
            res = client.SendSms(req);
        } catch (TencentCloudSDKException e) {
    
    
            log.error("发送短信出错:", e);
            return Boolean.FALSE;
        }
        log.error("发送短信结果:", SendSmsResponse.toJsonString(res));

        if (Objects.nonNull(res.getSendStatusSet()) && res.getSendStatusSet().length > 0 && "Ok".equals(res.getSendStatusSet()[0].getCode())){
    
    
            return Boolean.TRUE;
        }
        return Boolean.FALSE;
    }
    
    /**
     * 参数对象
     */
    @Data
    public static class SendSmsRequest {
    
    
        /**
         * 电话
         */
        private String phone;

        /**
         * 短信签名内容,必须填写已审核通过的签名
         */
        private String signName;

        /**
         * 模板 ID: 必须填写已审核通过的模板 ID
         */
        private String templateId;

        /**
         * 模板参数: 模板参数的个数需要与 TemplateId 对应模板的变量个数保持一致,若无模板参数,则设置为空
         */
        private String[] templateParamSet;

        /**
         * 应用id
         */
        private String smsSdkAppId;
        /**
         * 云api密钥中的 secretId
         */
        private String secretId;

        /**
         * 云api密钥中的 secretKey
         */
        private String secretKey;
    }
}

3) test

public class SendSmsUtil {
    
    
    public static void main(String[] args) {
    
    
        SendSmsRequest request = new SendSmsRequest();
        request.setPhone("电话");

        request.setSmsSdkAppId("应用id");

        request.setSecretId("API的SecretId");
        request.setSecretKey("API的SecretKey");

        request.setSignName("签名内容");
        request.setTemplateId("模板id");
        // 这个值,要看你的模板中是否预留了占位符,如果没有则不需要设置
        request.setTemplateParamSet(new String[]{
    
    "模板中的参数值,如果没有则为空"});
        SendSmsUtil.sendSms(request);
    }
}

At this point, the phone will receive a text message:
insert image description here

So far, we have achieved the function of connecting to Tencent SMS, but this is only a part of the development. We just encapsulated a small tool class for sending SMS. I have not used this SMS sending function in combination with specific businesses. I plan to use this function to realize a user registration in the future, and optimize it considering factors such as performance and security.

Guess you like

Origin blog.csdn.net/weixin_45444807/article/details/131571466