Java integrated Alibaba fish platform SMS service sends verification code to mobile phone

Posted by yoost on Wed, 25 Mar 2020 16:10:09 +0100

Click to go to: Alibaba big fish - error code of SMS interface call (error reason and handling method)

Previous: Alibaba big fish SMS service - sending verification code and SMS notice

User registration -- SMS verification code (Java integrated Alibaba big fish SMS service)

1, analysis

2. Back end code

2.1. Alibaba big fish tool class (smutil. Java)

package com.czxy.util;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;

 * Created on 17/6/7.
 * The DEMO program of SMS API product contains a SmsDemo class in the project, which directly passes the
 * Execute the main function to experience the API function of SMS product (just replace AK with AK that has opened the cloud communication SMS product function)
 * The project relies on two jar packages (stored in the libs directory of the project)
 * 1:aliyun-java-sdk-core.jar
 * 2:aliyun-java-sdk-dysmsapi.jar
 * Note: UTF-8 is adopted for Demo project coding
 * Please do not refer to this DEMO for international SMS
public class SmsUtil {

    //Product Name: cloud communication short message API product, developers do not need to replace it
    static final String product = "Dysmsapi";
    //Product domain name, developers do not need to replace
    static final String domain = "";

    //TODO here needs to be replaced by the developer's own AK (found on Alibaba cloud access console)
    static final String accessKeyId = "Own application ak";
    static final String accessKeySecret = "Self applied ak";

    public static SendSmsResponse sendSms(String telephone, String code) throws ClientException {

        //Self adjustable timeout
        System.setProperty("", "10000");      
		System.setProperty("", "10000");

        //Initialization of acsClient, region is not supported temporarily
        IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
        DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
        IAcsClient acsClient = new DefaultAcsClient(profile);

        //Assembly request object - for details, please refer to the console - Documentation section
        SendSmsRequest request = new SendSmsRequest();
        //Required: mobile number to be sent
        //Required: SMS signature - can be found in SMS console
        request.setSignName("SMS signature");
        //Required: SMS template - can be found in SMS console
        request.setTemplateCode("SMS template");
        //Optional: the variables in the template replace the JSON string. For example, when the template content is "Dear ${name}, and your verification code is ${code}", the value here is

        //Optional - uplink SMS extension code (please ignore this field for users without special requirements)

        //Optional: outId is the extension field provided to the business party, which will be brought back to the caller in the SMS receipt message

        //hint an exception may be thrown here. Pay attention to catch
        SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);

        return sendSmsResponse;
     * Random generation of 4-bit verification code
    public static String getNumber() {
        int number;//Define two variables
        Random ne = new Random();//Instantiate a random object ne
        number = ne.nextInt(9999 - 1000 + 1) + 1000;//Assign random values to variables 1000-9999
        System.out.println("The resulting random number is:" + number);//output
        return String.valueOf(number);

AK view

2.2. Java integrated Alibaba big fish SMS service sending verification code

The environment uses: Spring Boot

I wrote one before Use of Jedis It includes the integration of Spring Boot related content

Guide dependency (here, Redis dependency, database dependency, tool class, etc. are imported by themselves)


yml file

#Port number
  port: 8081
    name: cgwebservice   #service name
    allow-bean-definition-overriding: true
  datasource:           #Data source configuration
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://
    username: root
    password: 1234
    druid:              #druid connection pool configuration
      initial-size: 5
      min-idle: 5
      max-active: 20
      max-wait: 1000
      test-on-borrow: true
    database:   0
    port: 6379

#Configure Eureka (Registry)
    prefer-ip-address: true
    instance-id: ${eureka.instance.ip-address}.${server.port}
    lease-renewal-interval-in-seconds: 3
    lease-expiration-duration-in-seconds: 10

Create SmsController, call Alida fish tool class, and send verification code

package com.czxy.controller;

import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.czxy.pojo.User;
import com.czxy.utils.SmsUtil;
import com.czxy.vo.BaseResult;
import org.apache.commons.lang.RandomStringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;
 * @author Cloud before court
 * @Date 2020/3/22 9:03
 * @description
public class SmsController {

    private StringRedisTemplate stringRedisTemplate;

    public BaseResult sendSms(@RequestBody User user) {
        //get SysTime
        long start = System.currentTimeMillis();

        try {
            //1. Generate verification code
            String code = RandomStringUtils.randomNumeric(4);
            //2. Stored in redis, key:"sms_register" + mobile number, values: verification code, 1 hour
            stringRedisTemplate.opsForValue().set("sms_register" + user.getMobile(), code, 1, TimeUnit.HOURS);

            //3. Send SMS
            SendSmsResponse smsResponse = SmsUtil.sendSms(user.getMobile(),code);

            //The equalsIgnoreCase() method is used to compare a string to a specified object, regardless of case.
            if ("OK".equalsIgnoreCase(smsResponse.getCode())) {
                return BaseResult.ok("Send successfully");
            } else {
                return BaseResult.error(smsResponse.getMessage());

        } catch (Exception e) {
            long end = System.currentTimeMillis();
            return BaseResult.error("fail in send");


After the front-end code is added, the mobile phone receives the verification code and completes it

Other people's mistakes can be called stepping on thunder. I can basically say rolling thunder. There are 25 mistakes that can be made by calling Ali big fish's tool class. I've rolled to almost 10.

I read the api document of Alibaba big fish SMS service directly. There are reasons and suggested handling methods in calling the error code directly from the SMS port.

Click to go to: SMS interface call error code

Topics: Operation & Maintenance Java Redis SDK Spring