Realization of Text Message Function in java--Tencent Cloud Short Message

Posted by dzelenika on Sun, 11 Aug 2019 17:40:16 +0200

Catalog

java realizes the function of sending short messages

Preface

Nowadays, the function of sending short messages has become the standard of Internet companies. This article will implement java sending short messages step by step.

Many of the three parties that provide short message service have been investigated. Almost all of them need enterprise certification to be used, which is very inconvenient for personal learning. After many comparisons, Tencent Cloud (not advertising here) was chosen for two reasons:

  1. Support for Wechat Public Number Certification (Low Threshold)
  2. Give away 100 free short messages every month (suitable for personal learning) (this point should be ignored by the children of the miners themselves)

development environment

Please refer to: Building sub-module project based on SpringBook

Tencent Cloud - SMS

  1. Find Short Message Service

  2. After opening, click Add Application

  3. Set up short message signature (take public number as an example), choose public number or small program for signature type, and fill in the rest as required.

  4. When the signature is complete, create the SMS template

  5. After waiting for the above information review to be completed, you can start to use Tencent SMS service needs SDK AppID and AppKey. Here:

Code

  1. pom.xml introduces dependencies

    <properties>
        <java.version>1.8</java.version>
        <!-- Your other dependencies... -->
        <tencent.qcloudsms.version>1.0.6</tencent.qcloudsms.version>
    </properties>
    
    <dependencies>
        <!-- Your other dependencies... -->
        <!-- Tencent Short Message -->
        <dependency>
            <groupId>com.github.qcloudsms</groupId>
            <artifactId>qcloudsms</artifactId>
            <version>${tencent.qcloudsms.version}</version>
        </dependency>
    </dependencies>
  2. Sending SMS Tool Class

    package com.wayne.common.utils;
    
    import com.github.qcloudsms.*;
    import com.github.qcloudsms.httpclient.HTTPException;
    import com.wayne.common.entity.CmsMessageConfig;
    import com.wayne.common.exception.CustomException;
    import com.wayne.common.form.MessageForm;
    import org.json.JSONException;
    
    import java.io.IOException;
    
    /**
     * Sending SMS Tool Class
     * @author Wayne
     * @date 2019/6/26
     */
    public class MessageUtils {
    
        /**
         * Sending SMS by Template Supports Single and Group Sending
         * @param isSingle Whether single true: single, false: group
         * @param form Short Message Content and Receiver's Mobile Phone Number
         * @param config Short Message Configuration
         * @throws CustomException Abnormal information captured when sending failure
         */
        public static void sendMessage(Boolean isSingle, MessageForm form, CmsMessageConfig config) throws CustomException {
            validateMessage(form, config);
            String regex = ";";
            String[] params = {form.getCaptcha()};
            String[] phoneNumbers = form.getMobiles().split(regex);
    
            SmsResultBase result;
    
            try {
                // Is it single?
                if (isSingle) {
                    SmsSingleSender ssender = new SmsSingleSender(config.getAppId(), config.getAppKey());
                    result = ssender.sendWithParam("86", phoneNumbers[0], config.getTemplateId(), params, config.getSmsSign(), "", "");
                } else {
                    SmsMultiSender msender = new SmsMultiSender(config.getAppId(), config.getAppKey());
                    result =  msender.sendWithParam("86", phoneNumbers, config.getTemplateId(), params, config.getSmsSign(), "", "");
                }
                System.out.println(result);
            } catch (HTTPException e) {
                e.printStackTrace();
                throw new CustomException("HTTP Response Code Error");
            } catch (JSONException e) {
                e.printStackTrace();
                throw new CustomException("json Parsing error");
            } catch (IOException e) {
                e.printStackTrace();
                throw new CustomException("network IO error");
            }
        }
    
        /**
         * Calibration parameters
         */
        private static void validateMessage(MessageForm messageForm, CmsMessageConfig messageConfig) throws CustomException {
            ValidatorUtils.validateEntity(messageForm);
            if (null == messageConfig) {
                throw new CustomException("System parameter anomaly");
            }
        }
    }
  3. CmsMessageConfig configuration class

       package com.wayne.common.entity;
    
       import lombok.Data;
    
       import javax.persistence.*;
    
       @Data
       @Table(name = "cms_message_config")
       public class CmsMessageConfig {
           /**
            * Primary key
            */
           @Id
           @Column(name = "ID")
           private Integer id;
    
           /**
            * AppID
            */
           @Column(name = "APP_ID")
           private Integer appId;
    
           /**
            * AppKey
            */
           @Column(name = "APP_KEY")
           private String appKey;
    
           /**
            * Short Message Template ID
            */
           @Column(name = "TEMPLATE_ID")
           private Integer templateId;
    
           /**
            * Signature content
            */
           @Column(name = "SMS_SIGN")
           private String smsSign;
    
           /**
            * Whether to delete, 0:No, 1:Yes
            */
           @Column(name = "IS_DELETE")
           private String isDelete;
    
           /**
            * State, 0: Use, 1: Not use (at most one data should be in use at the same time)
            */
           @Column(name = "IS_USE")
           private String isUse;
    
           /**
            * Creator ID
            */
           @Column(name = "CREATE_ADMIN_ID")
           private Integer createAdminId;
    
           @Column(name = "EXTEND1")
           private String extend1;
    
           @Column(name = "EXTEND2")
           private String extend2;
    
           @Column(name = "EXTEND3")
           private String extend3;
    
           @Column(name = "EXTEND4")
           private String extend4;
    
           @Column(name = "EXTEND5")
           private String extend5;
    
           @Column(name = "EXTEND6")
           private String extend6;
       }
  4. Service

       @Override
       public ResponseBean sendMessage(MessageForm messageForm) {
           ValidatorUtils.validateEntity(messageForm);
    
           // Get the SMS configuration in use: here to query from the database
           CmsMessageConfig messageConfig = getCurrUseMessageConfig();
    
           try {
               // Send short messages
               MessageUtils.sendMessage(Boolean.FALSE, messageForm, messageConfig);
           } catch (CustomException e) {
               e.printStackTrace();
               return ResponseBean.createInstance(Boolean.FALSE, 401, e.getMessage());
           }
    
           return ResponseBean.createInstance();
       }
  5. Controller

       @PostMapping("/message/sendMessage")
       public ResponseBean sendMessage(MessageForm messageForm) {
           return messageService.sendMessage(messageForm);
       }

Effect

  1. No.1 SMS Template

  2. No.2 Short Message Template

  3. Setting Short Message Configuration Information

Concluding remarks

Finally, I have opened the public number. Welcome to the irrigation.

Topics: Java github JSON REST