java calls alicloud to implement the whole process of SMS verification code

Keywords: Mobile JSON Java SDK

java implementation of mobile phone verification code function

First, enter the preparation work and log in to alicloud https://www.aliyun.com/

Select domestic messages on the left side of the search SMS console

Adding a signature on the right side will have an audit process, as long as it meets the specification, it will pass within two hours generally

Add template is the same as add signature, and then wait for approval~

Then place the mouse cursor on the small head image in the upper right corner to access key management

Here I'm the first one to choose directly. It seems that the second one needs to create a sub user. It's not too troublesome to suggest the second one

Click the right side to create an AccessKey

You can get it after you fill in the verification code

No more beeps, then go straight to the code

To import a jar package with Maven:

    <dependency>
        <groupId>com.aliyun</groupId>
        <artifactId>aliyun-java-sdk-core</artifactId>
        <version>3.2.8</version>
    </dependency>
    <dependency>
        <groupId>com.aliyun</groupId>
        <artifactId>aliyun-java-sdk-dysmsapi</artifactId>
        <version>1.1.0</version>
    </dependency>

Create a package util of SMS tool class

For the convenience of configuration and clarity, I put configuration parameters into this class

public class StaticPeram {
    /**
     * Mobile phone authentication part configuration
     */
    // Set timeout - self adjustable
    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 (fixed SMS product name, no need to modify)
    final static String domain = "dysmsapi.aliyuncs.com";// SMS API product domain name (fixed interface address, no need to modify)
    // Replace with your AK (product key)
    final static String accessKeyId = "accessKeyId";// Your accessKeyId, fill in your own configuration above
    final static String accessKeySecret = "accessKeySecret";// For your accessKeySecret, fill in your own configuration above
    // Required: SMS signature - can be found in SMS console
    final static String SignName = "SignName";// Alicloud configures your own SMS signature to fill in
    // Required: SMS template - can be found in SMS console
    final static String TemplateCode = "TemplateCode"; // Alibaba cloud configures your own SMS template to fill in
}

The tool class can be used directly. The main method is added in it. You can set your mobile phone number to test directly in the main method

public class PhoneCode {

    private static String code ;

    public static void main(String[] args) {
        String phone = "xxxxxxxxxx"; //Here you can enter your mobile number to test
        getPhonemsg(phone);

    }

    /**
     * Alibaba cloud SMS service configuration
     * @param mobile
     * @return
     */
    public static String getPhonemsg(String mobile) {

        /**
         * Check regular relationship
         */
        System.out.println(mobile);
        if (mobile == null || mobile == "") {
            System.out.println("Cell phone number is empty");
            return "";
        }
        /**
         * SMS verification - alicloud tools
         */

        // Set timeout - self adjustable
        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 (fixed SMS product name, no need to modify)
        final String domain = StaticPeram.domain;// SMS API product domain name (fixed interface address, no need to modify)
        // Replace with your AK
        final String accessKeyId = StaticPeram.accessKeyId;// Your accessKeyId, refer to step 2 of this document
        final String accessKeySecret = StaticPeram.accessKeySecret;// For your accessKeySecret, refer to step 2 of this document
        // Initialize ascClient. Multiple region s are not supported temporarily
        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 request object
        SendSmsRequest request = new SendSmsRequest();
        // Submit using post
        request.setMethod(MethodType.POST);
        // Required: mobile number to be sent. Batch call is supported in comma separated form. The maximum batch number is 1000 mobile phone numbers. Batch call is slightly delayed compared with single call. It is recommended to use single call for SMS with verification code type
        request.setPhoneNumbers(mobile);
        // Required: SMS signature - can be found in SMS console
        request.setSignName(StaticPeram.SignName);
        // Required: SMS template - can be found in SMS console
        request.setTemplateCode(StaticPeram.TemplateCode);
        // 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
        // Friendly tip: if a line break is required in JSON, please refer to the standard JSON protocol for line break requirements. For example, if the SMS content contains a line break, it needs to be expressed as \ \ r\n in JSON. Otherwise, it will cause JSON to fail to parse on the server
        request.setTemplateParam("{ \"code\":\""+code+"\"}");
        // Optional - uplink SMS extension code (please ignore this field for users without special requirements)
        // request.setSmsUpExtendCode("90997");
        // Optional: outId is the extension field provided to the business party, which will be brought back to the caller in the SMS receipt message
        request.setOutId("yourOutId");
        // Request failed, ClientException exception will be thrown here
        SendSmsResponse sendSmsResponse;
        try {
            sendSmsResponse = acsClient.getAcsResponse(request);
            if (sendSmsResponse.getCode() != null
                    && 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("Failed to get verification code...");
            }
        } catch (ServerException e) {
            e.printStackTrace();
            return "Due to system maintenance, unable to register for the moment!!!";
        } catch (ClientException e) {
            e.printStackTrace();
            return "Due to system maintenance, unable to register for the moment!!!";
        }
        return "true";
    }

    /**
     * Generate 6-bit 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;
    }
}

Execute main method test


Note: if obtaining the verification code fails: sendSmsResponse.getCode() will return an error code to tell you the reason for the failure, such as: Return isv.AMOUNT_ NOT_ Hour: if the account balance is not enough, just charge one yuan to your alicloud account for testing

**SMS sending API(SendSms) - JAVA:** https://help.aliyun.com/document_detail/101300.html?spm=a2c4g.11186623.6.610.29da2b764w3uZq

Posted by johnbest on Sat, 13 Jun 2020 02:31:10 -0700