Spring boot simple access to Ali SMS interface

Preparations are as follows:

  • We need to open SMS service on Alibaba cloud. Here we can buy resource packs or recharge our own;
  • Create SMS verification signature. The signature needs to be reviewed by Alibaba background, usually about 2 hours;
  • Create SMS template;
  • In the menu under the user's Avatar, (create a user in AccessKey management and give him the permission to get the account and key in SMS) create an authorized user of Alibaba cloud;

Data we need:

accessKeyIdCreate user id
accessKeySecretCreate user's secret key
SignNameSMS signature name
TemplateCodeid of SMS template

Import the Alibaba SMS package into the project. Note that I use the upgraded SDK 2017-05-25 Click the reference link to enter
Import the jar package according to the document requirements:


Let's take a look at the official document sample code: Click jump example

This is the official sample code:

package com.aliyun.sample;

import com.aliyun.tea.*;
import com.aliyun.dysmsapi20170525.*;
import com.aliyun.dysmsapi20170525.models.*;
import com.aliyun.teaopenapi.*;
import com.aliyun.teaopenapi.models.*;

public class Sample {

     * Initialize the Client account with AK & sk
     * @param accessKeyId
     * @param accessKeySecret
     * @return Client
     * @throws Exception
    public static com.aliyun.dysmsapi20170525.Client createClient(String accessKeyId, String accessKeySecret) throws Exception {
        Config config = new Config()
                // Your AccessKey ID
                // Your AccessKey Secret
        // Domain name accessed
        config.endpoint = "dysmsapi.aliyuncs.com";
        return new com.aliyun.dysmsapi20170525.Client(config);

    public static void main(String[] args_) throws Exception {
        java.util.List<String> args = java.util.Arrays.asList(args_);
        com.aliyun.dysmsapi20170525.Client client = Sample.createClient("accessKeyId", "accessKeySecret");
        SendSmsRequest sendSmsRequest = new SendSmsRequest()
        // Please print the return value of the API when copying the code

What we need to do is to make some changes to the official code to better fit the actual business development scenario:

  • We first define the fixed parameters for sending SMS in the configuration file, and configure the following in yml;
  accessKeyId: LTAIWjSAN0910892
  accessKeySecret: pYtZUs4CCZ57hww19277637OICJSN
  SignName: Dawei Tianlong  #SMS signature
  TemplateCode: SMS_168581995 #There can be multiple templates, and enumeration can be defined according to project requirements

Note that there may be many SMS templates in the project, which can be configured. In addition, the SMS signature may be in Chinese, and the code may be garbled when using the properties configuration file (this is related to the default loading code of spring). For convenience, it is recommended to use yml file configuration;

  • Let's write a configuration file class and initialize the Client
import com.aliyun.teaopenapi.models.Config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

 * @Auther: MR.rp
 * @Date: 2021/8/3 14:31
 * @Description:

public class DysmsConfig {

    @Value(value = "${dysms.accessKeyId}")
    private  String   accessKeyId;

    @Value(value = "${dysms.accessKeySecret}")
    private  String  accessKeySecret;

    public com.aliyun.dysmsapi20170525.Client careateClient() throws Exception {
        Config config = new Config()
        // Domain name accessed
        config.endpoint = "dysmsapi.aliyuncs.com";
        return new com.aliyun.dysmsapi20170525.Client(config);
  • Write SMS call tool class
import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.*;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Pattern;

 * @Auther: MR.rp
 * @Date: 2021/8/3 14:37
 * @Description:

public  class DysmsUtil {
    private static Client client;
    private static  String  signName; //autograph
    public static  String  templateCode;// SMS verification code template id
    public void setMsgCode(String templateCode) {
        DysmsUtil.templateCode= templateCode;
    public DysmsUtil(Client client){
        this.client = client;

    public void setSIGN(String signName) {
        DysmsUtil.signName= signName;

     * Send a message to a single mobile phone
     * @param phoneNums
     * @param smsModelId
     * @param template
    public static void  sendMsg(String phoneNums, String templateCode, String  template){
       //Here, in order to test whether the verification of only writing a single mobile phone number is legal, if there are multiple mobile phone numbers in development, you can verify them yourself first and then pass them to the reference
            log.warn("============ cell-phone number:"+phoneNums+"wrongful,fail in send ======");
        SendSmsRequest sendSmsRequest = new SendSmsRequest()
                .setSignName(signName)  //SMS signature name
                .setTemplateCode(templateCode) //SMS template ID
                .setTemplateParam(template); //Variable value
        try {
            SendSmsResponse sendSmsResponse = client.sendSms(sendSmsRequest);
            SendSmsResponseBody  sendBody = sendSmsResponse.getBody();

                log.info("========== to:"+phoneNums+"Send SMS["+template+"]success!!! ==========");
            //The following is the result set of query information. Because the SMS itself will have a certain delay, it may not be found during query, or let the thread sleep for a few seconds before query. Here is only the query code posted for your reference
            String datetime = new SimpleDateFormat("yyyyMMdd").format(new Date());
            String bizId = sendBody.bizId;
            QuerySendDetailsRequest querySendDetailsRequest = new QuerySendDetailsRequest()
                    .setPageSize(10L)  //paging
            QuerySendDetailsResponseBody body = client.querySendDetails(querySendDetailsRequest).getBody();
            ObjectMapper objectMapper = new ObjectMapper();
            String msg = objectMapper.writeValueAsString(body);
            log.info("Returned body information:"+msg);
            String message = objectMapper.writeValueAsString(sendBody);
            log.info("Send return message details:"+message);
        } catch (Exception e) {

     * Get SMS verification code
     * @return Verification Code
    public static String getCode() {
        String code = null;
        code = (int) ((Math.random() * 9 + 1) * 100000) + "";
        log.info("Verification code is["+code+"]");
        return code;

We call tests in our business:

    @ApiOperation(value = "Get verification code",notes = "Get verification code")
    public ServerResponseVO  getCode(@RequestParam("userTel")@ApiParam("cell-phone number") String userTel,HttpSession session){
        boolean matches = userTel.matches("^1(3\\d|4[5-9]|5[0-35-9]|6[567]|7[0-8]|8\\d|9[0-35-9])\\d{8}$");
            return  ServerResponseVO.error("Wrong mobile phone number");
        String code = DysmsUtil.getCode();
//        session.setAttribute(userTel,code);
//        session.setMaxInactiveInterval(300);
        redisTemplate.opsForValue().set(userTel,code,300, TimeUnit.SECONDS);// redis storage
        String  jsonCode  = "{'code':'"+code+"'}";
        log.info("cell-phone number:"+userTel +"Successfully obtained verification code:["+code+"]" );
        return  ServerResponseVO.success("Successfully obtained verification code");

Look at the log:

How about it? Is it simple?

  • In the case of multiple SMS signatures, we can configure several more SMS configuration names and inject them into the tool class. You can also define them as enumerations. When the current enumerations or injected attributes are passed in during the call, the corresponding SMS can be sent. Also note that when the placeholder parameters are passed in, the official support is json format. The author stepped here before, Failed to send all the time;

If you are interested, you can test it yourself

Tags: Java Spring Boot Back-end

Posted on Sat, 06 Nov 2021 06:49:32 -0400 by marcs910