Alibaba cloud SMS out of the box

Keywords: Java JSON github Mobile Spring

brief introduction

Use SpringBoot to automatically assemble and simplify the docking of Alibaba cloud SMS.

A small tool, welcome to use and Star support, if you encounter problems during use, you can raise Issue, I will try my best to improve the Starter.

Version basis

aliyun-java-sdk-core:4.1.0

How to use

Maven

<dependency>
  <groupId>io.github.gcdd1993</groupId>
  <artifactId>ali-sms-spring-boot-starter</artifactId>
  <version>1.0.0.RELEASE</version>
</dependency>

Gradle

compile 'io.github.gcdd1993:ali-sms-spring-boot-starter:1.0.0.RELEASE'

👉 note: Jcenter warehouse needs to be introduced

Parameter configuration

Take application.yml for example

ali:
  sms:
    domain: "dysmsapi.aliyuncs.com" ## Default dysmassapi.aliyuncs.com
    version: "2017-05-25" ## Default May 25, 2017
    action: "SendSms" ## Default SendSms
    access-key:
      id: "${Alibaba cloud SMS AccessKeyId}"
      secret: "${Alibaba cloud SMS AccessKeySecret}"
    region-id: "${Alibaba cloud SMS region}"
    sign-name: "${Alibaba cloud SMS signature}" ## If not, it must be specified in the sending method

Basic use

Send SMS synchronously

For convenience, the interface is overloaded with methods. There are 5 different parameter lists to choose from. You can choose to use them by yourself

/**
 * Send SMS synchronously
 * <p>
 *     Parameter 1: SMS template ID used
 *     Parameter 2: receiver's mobile number, such as "1760252612917602923211"
 *     Parameter 3: Map, key corresponds to the parameter name in the template, and value corresponds to the value (in this case, Jackson is used for serialization)
 * </p>
 */
@Test
public void sendSync() {
    SmsResponse smsResponse = sendService.sendSync(TEMPLATE_ID, PHONE_NUMBER, MAP);
    Assert.assertTrue(smsResponse.isSuccess());
}

/**
 * Send SMS synchronously
 * <p>
 *     Parameter 1: SMS template ID used
 *     Parameter 2: receiver's mobile number, such as "1760252612917602923211"
 *     Parameter 3: to write the value of the SMS to be sent, you can assemble the json by yourself. Note that you want to escape json, for example: "{" code\":\"112233 \ "}"
 * </p>
 */
@Test
public void sendSync1() {
    SmsResponse smsResponse = sendService.sendSync(TEMPLATE_ID, PHONE_NUMBER, "{\"code\":\"112233\"}");
    Assert.assertTrue(smsResponse.isSuccess());
}

/**
 * Send SMS synchronously
 * <p>
 *     Parameter 1: short message signature applies to the same template with different SMS signatures.
 *     Parameter 2: SMS template ID used
 *     Parameter 3: receiver's mobile number, such as "1760252612917602923211"
 *     Parameter 4: Map and key correspond to the parameter name and value in the template (in this case, Jackson is used for serialization)
 * </p>
 */
@Test
public void sendSync2() {
    SmsResponse smsResponse = sendService.sendSync(SIGN_NAME, TEMPLATE_ID, PHONE_NUMBER, MAP);
    Assert.assertTrue(smsResponse.isSuccess());
}

/**
 * Send SMS synchronously
 * <p>
 *     Parameter 1: short message signature applies to the same template with different SMS signatures.
 *     Parameter 2: SMS template ID used
 *     Parameter 3: receiver's mobile number, such as "1760252612917602923211"
 *     Parameter 4: to write the value of the SMS to be sent, you can assemble the json by yourself. Note that you want to escape json, for example: "{" code\":\"112233 \ "}"
 * </p>
 */
@Test
public void sendSync3() {
    SmsResponse smsResponse = sendService.sendSync(SIGN_NAME, TEMPLATE_ID, PHONE_NUMBER, "{\"code\":\"112233\"}");
    Assert.assertTrue(smsResponse.isSuccess());
}

The last one provides a parameter object to define the SMS sending request, which can be used if it is not too troublesome.

/**
 * Alibaba cloud SMS request body
 *
 * @author gaochen
 * @date 2019/6/6
 */
@Data
public class SmsRequest {

    /**
     * The mobile number to receive the message. Separated by commas (,).
     */
    private String phoneNumbers;

    /**
     * SMS signature name. Please check in the signature name column of the console signature management page.
     */
    private String signName;

    /**
     * SMS template ID, prefix is SMS_
     */
    private Integer templateId;

    /**
     * Alibaba cloud SMS content, key: field name in SMS template, value: corresponding value of SMS template field
     * Using this field requires {@ link com.fasterxml.jackson.databind.ObjectMapper}
     */
    private Map<String, String> params;

    /**
     * json str of  {@link #getParams()}
     * Use this field to set params to Null
     */
    private String paramStr;

}

Use:

@Test
public void sendSync4() {
    SmsRequest smsRequest = new SmsRequest();
    smsRequest.setPhoneNumbers(PHONE_NUMBER);
    smsRequest.setTemplateId(TEMPLATE_ID);
    smsRequest.setParams(MAP);
    SmsResponse smsResponse = sendService.sendSync(smsRequest);
    Assert.assertTrue(smsResponse.isSuccess());
}

Send SMS asynchronously

Considering the demand of sending short messages, asynchronous support is generally required. The asynchronous interface sendAsync is provided for the above five methods respectively. The use methods are basically the same. The only difference is that you can handle the return value of sending short messages asynchronously.

CompletableFuture<SmsResponse> smsResponse = sendService.sendAsync(TEMPLATE_ID, PHONE_NUMBER, MAP);
smsResponse.thenAcceptAsync(sr -> {
    if (sr.isSuccess()) {
        System.out.println("SMS successful");
    } else {
        System.out.println("Send to message queue, ready to retry this SMS");
    }
});

Advanced use

In addition to using the above methods to send SMS, you can also use the official IAcsClient to send SMS, such as

package io.github.gcdd1993.demo;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.request;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.gcdd1993.alisms.domain.SmsRequest;
import io.github.gcdd1993.alisms.domain.SmsResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * TODO
 *
 * @author gaochen
 * @date 2019/6/8
 */
@Service
public class SendService {

    @Autowired
    private IAcsClient acsClient;

    public SmsResponse sendSync() {
        try {
            CommonRequest request = new CommonRequest();
            request.setMethod(MethodType.POST);
            request.setDomain("dysmsapi.aliyuncs.com");
            request.setVersion("2017-05-25");
            request.setAction("SendSms");
            request.putQueryParameter("RegionId", "region");
            request.putQueryParameter("PhoneNumbers", "1771636783");
            request.putQueryParameter("SignName", "SignName");
            request.putQueryParameter("TemplateCode", "SMS_12345678");
            request.putQueryParameter("TemplateParam", "{\"code\":\"112233\"}");
            CommonResponse commonResponse = acsClient.getCommonResponse(request);

            return SmsResponse.SmsResponseBuilder.build(commonResponse);

        } catch (ClientException e) {
            log.error("send msg error.", e);
            return SmsResponse.SmsResponseBuilder.buildFail(e.getMessage());
        } catch (JsonProcessingException e) {
            log.error("write json failed.", e);
            return SmsResponse.SmsResponseBuilder.buildFail("SMS parameters in json Error serializing");
        }
    }
}

Licenses

The Apache License, Version 2.0

Issues

Issues Welcome

Support

  • Click Github to star, Thanks!

More reference

Alibaba cloud SMS API reference

Posted by daddymac on Mon, 10 Feb 2020 07:06:34 -0800