Java implements SMS verification code

Preface

I am using the SMS service of Ali, and tried many different third-party SMS service platforms at the beginning, such as Miaodi Technology and Montnets Cloud Communication. Why did I choose these two in the first place? First of all, they gave 10 yuan for registration (#^.^#), but later found that they all need certification. For example, Miaodi is only for enterprises, and enterprise certification must be completed. , there is no way for individuals to achieve it (and the customer service will always call). And Montnets Cloud Communication seems to be okay, but after reading the code on the official website, I don’t understand it… There are relatively few code samples on the Internet. So after some exploration, I finally chose the more formal Ali. Although it will not send the balance, but a text message is less than 5 cents. It can be said that charging 2 yuan is completely enough for testing.

Alibaba Cloud login and SMS service

1. Enter Alibaba Cloud official website (https://www.aliyun.com/), enter “SMS service” in the search item to activate the service. Don’t need to click to buy first, because the package purchased here is a 2-year package, and the price is relatively expensive. For me, it is enough to go in and directly recharge the balance.

2. After entering the console, you need to obtain the AccessKey first. Click the circled place in the figure below to obtain the AccessKey

3. Click Continue to use AccessKey

4. Click Create AccessKey, click Get AccessKey Secret after creation, and then it will be sent to you in the form of SMS. We need to remember the AccessKey ID and Secret, because they will be used later when writing code.

5. Set and review SMS signature and SMS template. The review takes about 1 hour.

Code part(the yellow part needs to be modified to your own data)

Next we can start writing code

StaticParam.java

package util;
 
public class StaticPeram {
    /**
     * Partial configuration of mobile phone verification
     */
    // Set the timeout period - can be adjusted by yourself
    final static String defaultConnectTimeout = "sun.net.client.defaultConnectTimeout";
    final static String defaultReadTimeout = "sun.net.client.defaultReadTimeout";
    final static String Timeout = "10000";
    // Several parameters needed to initialize ascClient
    final static String product = "Dysmsapi";// SMS API product name (SMS product name is fixed and does not need to be modified)
    final static String domain = "dysmsapi.aliyuncs.com";// SMS API product domain name (the interface address is fixed and does not need to be modified)
    // Replace with your AK (product password)
    final static String accessKeyId = "AccessKey";// Your accessKeyId, fill in your own configuration obtained from the above configuration by yourself
    final static String accessKeySecret = "AccessKeySecret";//Your accessKeySecret, fill in your own configuration obtained above to configure by yourself
    // Required: SMS signature - can be found in the SMS console
    final static String SignName = "SMS signature"; // Alibaba Cloud configures your own SMS signature to fill in
    // Required: SMS template - can be found in the SMS console
    final static String TemplateCode = "SMS_185840737"; // Alibaba Cloud configures your own SMS template CODE to fill in
    
}

PhoneCode.java

package 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.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
 
public class PhoneCode {
 
    private static String code;
    
    public static void main(String[] args) {
        String phone = "mobile phone number"; //You can enter your mobile phone number here for testing
        getPhonemsg(phone);
        
    }
    
    /**
     * Alibaba Cloud SMS service configuration
     * @param mobile
     * @return
     */
    public static String getPhonemsg(String mobile) {
 
        /**
         * Perform regular relationship check
         */
        System.out.println(mobile);
        if (mobile == null || mobile == "") {
            System.out.println("The phone number is empty");
            return "";
        }
        /**
         * SMS verification---Alibaba tool
         */
 
        // Set the timeout period - can be adjusted by yourself
        System.setProperty(StaticPeram.defaultConnectTimeout, StaticPeram.Timeout);
        System.setProperty(StaticPeram.defaultReadTimeout, StaticPeram.Timeout);
        // Several parameters needed to initialize ascClient
        final String product = StaticPeram.product;// SMS API product name (SMS product name is fixed and does not need to be modified)
        final String domain = StaticPeram.domain;// SMS API product domain name (the interface address is fixed and does not need to be modified)
        // Replace with your AK
        final String accessKeyId = StaticPeram.accessKeyId;// Your accessKeyId, refer to step 2 of this document
        final String accessKeySecret = StaticPeram.accessKeySecret;// Your accessKeySecret, refer to step 2 of this document
        // Initialize ascClient, temporarily does not support multiple regions
        IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou",
                accessKeyId, accessKeySecret);
        try {
            DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product,
                    domain);
        } catch (ClientException e1) {
            e1.printStackTrace();
        }
        
        //get verification code
        code = vcode();
        
        IAcsClient acsClient = new DefaultAcsClient(profile);
        // assemble the request object
        SendSmsRequest request = new SendSmsRequest();
        // use post to submit
        request.setMethod(MethodType.POST);
        // Mandatory: mobile phone number to be sent. Batch calls separated by commas are supported. The batch limit is 1000 mobile phone numbers. The timeliness of batch calls is slightly delayed compared to a single call. It is recommended to use a single call for verification code type SMS
        request.setPhoneNumbers(mobile);
        // Required: SMS signature - can be found in the SMS console
        request.setSignName(StaticPeram.SignName);
        // Required: SMS template - can be found in the SMS console
        request.setTemplateCode(StaticPeram.TemplateCode);//Friendly reminder: if JSON needs to contain line breaks, please refer to the standard JSON protocol’s requirements for line breaks, for example, the text message contains \r\\
 in JSON It needs to be expressed as \r\\
, otherwise it will cause JSON parsing failure on the server side<br>//My SMS template is Dear user, your dynamic password for registered members is: ${code}, please do not disclose it to others! Where ${code} is the verification code to be generated
 request.setTemplateParam("{ "code":"" + code + ""}");
        // Optional - uplink SMS extension code (please ignore this field for users without special needs)
        // request.setSmsUpExtendCode("90997");
        // Optional: outId is an extension field provided to the business party, and finally this value will be brought back to the caller in the SMS receipt message
        request.setOutId("yourOutId");
        // If the request fails, a ClientException will be thrown here
        SendSmsResponse sendSmsResponse;
        try {
            sendSmsResponse = acsClient. getAcsResponse(request);
            if (sendSmsResponse. getCode() != null
                     & amp; & amp; sendSmsResponse.getCode().equals("OK")) {
                // request succeeded
                System.out.println("Get the verification code successfully!!!");
            } else {
                //If the verification code is wrong, the error code will be output to tell you the specific reason
                System.out.println(sendSmsResponse.getCode());
                System.out.println("Get verification code failed...");
            }
        } catch (ServerException e) {
            e.printStackTrace();
            return "Because of system maintenance, registration is temporarily unavailable!!!";
        } catch (ClientException e) {
            e.printStackTrace();
            return "Because of system maintenance, registration is temporarily unavailable!!!";
        }
        return "true";
    }
    
    /**
     * Generate a 6-digit random number verification code
     * @return
     */
    public static String vcode(){
        String vcode = "";
        for (int i = 0; i < 6; i ++ ) {
            vcode = vcode + (int)(Math. random() * 9);
        }
        return vcode;
    }
}

Test Results

After running, the result will be output on the console, if successful, it will output

If the operation fails, the mobile phone number and error code will be output. Combined with the official error code, the problem can be known. Official SMS interface call error code (https://help.aliyun.com/knowledge_detail/57717.html?spm=5176.7757710.6.580.8BceHC)

Required jar package

aliyun-java-sdk-core-3.3.1.jar and aliyun-java-sdk-dysmsapi-1.0.0.jar

Link: https://pan.baidu.com/s/1Vg6C_JNoZbn_5oTDb6jHbg
Extraction code: kawr

The knowledge points of the article match the official knowledge files, and you can further learn relevant knowledge. Java skill treeHomepageOverview 117733 people are studying systematically