The article directories

  • Writing in the front
  • preparation
    • Account for
    • Open SMS service
    • To apply for the signature
    • To apply for the template
    • To apply for the AccessKey
    • top-up
  • Developing the sample
    • Configuration import
    • The sample code

Writing in the front


Recently completed the course design, ready to sum up, will write a few blog, grain warehouse.

Among them, the registration function is useful to SMS verification code, looking back or a rough history, online SMS platform has a lot of large and small, but most have the lowest recharge, and I also encountered the best customer service (social sinister 🙃), must expose a hazel cloud, finally or Ali cloud success 👍, almost give up.

preparation


Account for

Register an Ali cloud account, or log in directly. Address: www.aliyun.com/

Open SMS service

portal

To apply for the signature

portal

SMS console -> Add a signature

Fill in the signature, select the verification code (I have applied here, failed to intercept the picture), and the reason for application and so on.

To apply for the template

portal

SMS Console -> Add a template

The template name is optional, and the template content can be obtained by referring to common template libraries.



Finally, just wait patiently for the audit, you can view the audit results in the signature management and template management in the national message (below the application international point).

To apply for the AccessKey

Go to Profile picture ->AccessKey Management

Click on the create



Once authenticated, you get the AccessKey ID and Secret. That’s all we need to do.

top-up

Each SMS 4 points 5, the advantage of Ali cloud is no minimum recharge, can first charge a hair to try water.

Developing the sample


portal

You can view the documentation or download the demo for reference. Here Java is used as an example.

Configuration import

Configuration in POM.xml. For those of you who don’t know maven, click here.

<dependency>
	<groupId>com.aliyun</groupId>
    <artifactId>aliyun-java-sdk-core</artifactId>
    <version>4.51.</version>
</dependency>
<dependency>
	<groupId>com.aliyun</groupId>
    <artifactId>aliyun-java-sdk-dysmsapi</artifactId>
    <version>1.1. 0</version>
</dependency>
Copy the code

Or download and import the Aliyu-java-SDK-core JAR file.

The sample code

Several places that need to be replaced have been annotated, that is, the ones that need to be replaced with the ones prepared in advance.

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.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
Note: signature name, template CODE and AccessKeyID and AccessKeySecret in RAM access control are required
public class AliyunSmsUtils {
 
    public AliyunSmsUtils(a) {
		super(a);// TODO Auto-generated constructor stub
	}

	// Product name: Cloud communication SMS API product, developers do not need to replace
    static final String product = "Dysmsapi";
    // Product domain name, developers do not need to replace
    static final String domain = "dysmsapi.aliyuncs.com";
 
    // TODO here needs to be replaced with the developer's own AK(look for it in aliyun access console)
    static final String accessKeyId = "CSDN";  // TODO changes to its accessKeyId
    static final String accessKeySecret = "CSDN";   // TODO changes to accessKeySecret
 
    public static SendSmsResponse sendSms(String telephone, String code) throws ClientException {
        // You can adjust the timeout duration by yourself
        System.setProperty("sun.net.client.defaultConnectTimeout"."10000");
        System.setProperty("sun.net.client.defaultReadTimeout"."10000");
        // Initialize acsClient. Regionalization is not supported
        IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
        DefaultProfile.addEndpoint("cn-hangzhou"."cn-hangzhou", product, domain);
        IAcsClient acsClient = new DefaultAcsClient(profile);
        // Assemble the request object - see the console - documentation section for details
        SendSmsRequest request = new SendSmsRequest();
        // Required: Mobile phone number to be sent
        request.setPhoneNumbers(telephone);
        // Required: SMS signature - can be found in SMS console
        request.setSignName("CSDN");    // TODO changes to its own signature
        // Required: SMS template - Available in the SMS console
        request.setTemplateCode("SMS_193235494 CSDN");    // TODO changes to its own template CODE
        // Optional: Replace the JSON string with variables in the template. For example, if the template content is "Dear ${name}, your verification code is ${code}", the value is
// request.setTemplateParam("{\"name\":\"Tom\", \"code\":\"123\"}");
        request.setTemplateParam("{\"code\":\"" + code + "\"}");
        // Optional - Upstream SMS extension code (ignore this field for users without special requirements)
        //request.setSmsUpExtendCode("90997");
        // Optional :outId is provided to the business side to extend the field, and this value is eventually returned to the caller in the SMS acknowledgement message
        request.setOutId("yourOutId");
        //hint may throw an exception
        SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);
        if(sendSmsResponse.getCode()! =null && sendSmsResponse.getCode().equals("OK")){
            System.out.println("SMS sent successfully!");
        }else {
            System.out.println("SMS sending failed!");
        }
        return sendSmsResponse;
    }
  Public static QuerySendDetailsResponse querySendDetails(String bizId) throws ClientException { / / can be self-service System. Adjust the timeout time setProperty (" sun.net.client.defaultConnectTimeout ", "10000"); System.setProperty("sun.net.client.defaultReadTimeout", "10000"); / / initialize acsClient, temporarily does not support region is changed IClientProfile profile = DefaultProfile. GetProfile (" cn - hangzhou ", accessKeyId, accessKeySecret); DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain); IAcsClient acsClient = new DefaultAcsClient(profile); QuerySendDetailsRequest request = new QuerySendDetailsRequest(); // Mandatory - number request.setPhoneNumber("15000000000"); // Optional -serial number request.setBizid (bizId); // Mandatory - Sending date Records can be queried within 30 days. Format yyyyMMdd SimpleDateFormat ft = new SimpleDateFormat("yyyyMMdd"); request.setSendDate(ft.format(new Date())); // Required - page size request.setPagesize (10L); Request. setCurrentPage(1L); QuerySendDetailsResponse QuerySendDetailsResponse = acsclient.getacsResponse (request); return querySendDetailsResponse; } * /
 
    // The following is the test code, randomly generated verification code
    private static int newcode;
    public static int getNewcode(a) {
        return newcode;
    }
    public static void setNewcode(a){
        newcode = (int)(Math.random()*1000000);  // Each call generates a random six-digit number
    }
    public static void main(String[] args) throws ClientException, InterruptedException {
        setNewcode();
        String code = Integer.toString(getNewcode());
        System.out.println("The sent verification code is:"+code);
        / / text
        SendSmsResponse response =sendSms("CSDN",code); // TODO fill in the phone number you need to test
        System.out.println("Data returned by SMS interface ----------------");
        System.out.println("Code=" + response.getCode());
        System.out.println("Message=" + response.getMessage());
        System.out.println("RequestId=" + response.getRequestId());
        System.out.println("BizId=" + response.getBizId());
 
       / * don't delete a later may be useful System. Out. The println (" = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = "); Thread.sleep(3000L); Response.getcode ()! = null && response.getCode().equals("OK")) { QuerySendDetailsResponse querySendDetailsResponse = querySendDetails(response.getBizId()); System. The out. Println (" SMS detailed query interface returned data -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - "); System.out.println("Code=" + querySendDetailsResponse.getCode()); System.out.println("Message=" + querySendDetailsResponse.getMessage()); int i = 0; for(QuerySendDetailsResponse.SmsSendDetailDTO smsSendDetailDTO : querySendDetailsResponse.getSmsSendDetailDTOs()) { System.out.println("SmsSendDetailDTO["+i+"]:"); System.out.println("Content=" + smsSendDetailDTO.getContent()); System.out.println("ErrCode=" + smsSendDetailDTO.getErrCode()); System.out.println("OutId=" + smsSendDetailDTO.getOutId()); System.out.println("PhoneNum=" + smsSendDetailDTO.getPhoneNum()); System.out.println("ReceiveDate=" + smsSendDetailDTO.getReceiveDate()); System.out.println("SendDate=" + smsSendDetailDTO.getSendDate()); System.out.println("SendStatus=" + smsSendDetailDTO.getSendStatus()); System.out.println("Template=" + smsSendDetailDTO.getTemplateCode()); } System.out.println("TotalCount=" + querySendDetailsResponse.getTotalCount()); System.out.println("RequestId=" + querySendDetailsResponse.getRequestId()); } * /}}Copy the code

At this point, the SMS verification code was successfully sent (~ ▽ ~) ~

Original is not easy, please do not reprint (this is not rich visits add insult to injury) blogger home page: blog.csdn.net/qq_45034708 If the article is helpful to you, remember to focus on the likes collection ❤