Tencent cloud SMS sending verification code (super detailed)

In most SMS platforms, the number of free SMS messages is just a few. There are too few, and the tests are not enough. Basically, you have to charge enough to buy them. I have also registered several platforms and found that Tencent cloud gives 200 trial SMS free of charge, which is very good. In terms of our student party project test, it is more than enough.
1. Register Tencent cloud account, and then go to the real name authentication
Tencent cloud's official website: https://cloud.tencent.com/
2. Get free SMS, you can collect 200 SMS in vain (personal project test is enough)

Cloud products - SMS

SMS - overview, you can see the effective margin of SMS here (you can also get it here for free)

SMS - package management - domestic package (personal authentication, free gift)

3. Create signature
Signature verification is generally very strict. As long as the signature verification passes, it will be basically successful. However, Tencent cloud is much more friendly than Alibaba cloud, and the audit is relatively loose. (if you apply for more, one of them will always pass. If you fail, you can look at the reasons for the failure, change it and submit it again. I'm not very good at the beginning. I only applied for one and passed it for several days.)
After the creation is successful, it is like this (the signName signature here will be used later)

Ali cloud can only apply for the project after being launched or filed, and the Tencent public's application for the official account of the official account is provided by the public application of the public signature of the cloud.
Signature types (including company, website, APP, official account, applet), the audit is completed within 2 hours.
I recommend websites or public numbers. Official account is official account. If I prove and entrust, I will use the license to go online.

4. Create template
Template applications are very easy to pass (template templateID and content parameters {1}, {2} will be used below)

5. SMS - Application Management - Application List (SDKAppID, AppKey will be used below)
Both are available by default. If not, create them

6. Create a key (SecreId/SecreKey here will be used later)

Select continue to use

The secret ID is used to identify the identity of the API caller, and the secret key is used to encrypt the signature string and the key of the server-side verification signature string.

The above steps are completed. Here is the code:

See the official Tencent cloud SDK document for the specific code, which contains a very detailed java access guide
(address: https://cloud.tencent.com/document/product/382/43194)

You can find the latest version on Maven warehouse. 4.0.11 shown in Maven warehouse is obsolete
(address: https://search.maven.org/search?q=tencentcloud-sdk-java )

Add maven dependency (configure SDK)
Introduce the jar package of SMS verification, maven's POM XML join

<!--Tencent cloud SMS-->
   		<!-- https://mvnrepository.com/artifact/com.tencentcloudapi/tencentcloud-sdk-java -->
   		<dependency>
   			<groupId>com.tencentcloudapi</groupId>
   			<artifactId>tencentcloud-sdk-java</artifactId>
   			<version>3.1.284</version>
   		</dependency>

Random verification code 4 / 6 digits

//Verification code random number
public  class  ValidateCode {

   public static Integer generateValidateCode(int length){
       Integer code =null;
       if(length == 4){
           code = new Random().nextInt(9999);//Generate random number, up to 9999
           if(code < 1000){
               code = code + 1000;//Ensure that the random number is 4 digits
           }
       }else if(length == 6){
           code = new Random().nextInt(999999);//Generate random number, the maximum is 999999
           if(code < 100000){
               code = code + 100000;//Ensure that the random number is 6 digits
           }
       }else{
           throw new RuntimeException("Only 4-digit or 6-digit verification code can be generated");
       }
       return code;
   }
}

Constant parameter class (encapsulate the above parameters of secretid, secretkey, sdkappid, signname and templateid)

/**
* Constant class
*/
public class Constants {

   //Tencent cloud account secret ID
   public static final String SecretID = "SecretID";
   //Tencent cloud account key pair: secret key
   public static final String SecretKey = "SecretKey";
   //SdkAppid
   public static final String SdkAppid = "SdkAppid";
   //signName: Signature
   public static final String signName = "Sam sir";
   //SMS template id:
   public static final String templateId ="978194";

   public static  String voicode="";
}

Encapsulate a tool class for sending SMS (some are added)

import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
//Import optional configuration classes
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
// Import the client of the corresponding SMS module
import com.tencentcloudapi.sms.v20190711.SmsClient;
// Import the request response class corresponding to the request interface
import com.tencentcloudapi.sms.v20190711.models.SendSmsRequest;
import com.tencentcloudapi.sms.v20190711.models.SendSmsResponse;
import com.tencentcloudapi.sms.v20190711.models.SendStatus;

import javax.servlet.http.HttpSession;

public class SendSmsUtil {

   public static SendStatus[] sendSms(String[] phoneNumber ) {

      SendStatus[] returString= {};

       try {
           /* Necessary steps:
            * To instantiate an authentication object, you need to pass in the secret ID and secret key of Tencent cloud account key pair.
            * The method used here is to read from the environment variable. You need to set these two values in the environment variable first.
            * You can also write dead key pairs directly in the code, but be careful not to copy, upload or share the code with others,
            * So as not to compromise the security of your property.
            * CAM Key query: https://console.cloud.tencent.com/cam/capi*/
           Credential cred = new Credential(Constants.SecretID, Constants.SecretKey);

           // Instantiate an http option. Optional. No special requirements can be skipped
           HttpProfile httpProfile = new HttpProfile();

           // Set agent
//            httpProfile.setProxyHost("host");
//            httpProfile.setProxyPort(port);
           /* SDK The POST method is used by default.
            * If you must use the GET method, you can set it here. The GET method cannot handle some large requests */
           httpProfile.setReqMethod("POST");
           /* SDK There is a default timeout. Please do not adjust it if it is not necessary
            * If necessary, check in the code for the latest default values */
           httpProfile.setConnTimeout(60);
           /* SDK The domain name is automatically specified. Usually, you don't need to specify a domain name, but if you visit the services of the financial district
            * You must specify the domain name manually, for example, the domain name of Shanghai Financial District of sms: sms ap-shanghai-fsi. tencentcloudapi. com */
           httpProfile.setEndpoint("sms.tencentcloudapi.com");

           /* Non essential steps:
            * Instantiate a client configuration object. You can specify timeout and other configurations */
           ClientProfile clientProfile = new ClientProfile();
           /* SDK TC3-HMAC-SHA256 is used for signature by default
            * Do not modify this field unless necessary */
           clientProfile.setSignMethod("HmacSHA256");
           clientProfile.setHttpProfile(httpProfile);
           /* Instantiate the client object to request the product (take sms as an example)
            * The second parameter is the region information. You can directly fill in the string AP Guangzhou or reference the preset constant */
           SmsClient client = new SmsClient(cred, "ap-guangzhou", clientProfile);
           /* Instantiate a request object, and further set the request parameters according to the calling interface and the actual situation
            * You can directly query the SDK source code to determine which attributes of the interface can be set
            * The attribute may be a basic type or it may refer to another data structure
            * It is recommended to use IDE for development. You can easily jump to the document description of each interface and data structure */
           SendSmsRequest req = new SendSmsRequest();

          /* Fill in the request parameters, where the member variable of the request object is the input parameter of the corresponding interface
            * You can view the definition of request parameters through the official website interface document or jump to the definition of request object
            * Basic type settings:
            * Help link:
            * SMS console: https://console.cloud.tencent.com/sms/smslist
            * sms helper: https://cloud.tencent.com/document/product/382/3773 */

           /* SMS application ID: the actual SdkAppid generated after adding an application in [SMS console], such as 1400006666 */
           String sdkappid = Constants.SdkAppid;
           req.setSmsSdkAppid(sdkappid);

           /* SMS signature content: if UTF-8 code is used, the approved signature must be filled in. The signature information can be viewed by logging in to [SMS console] */
           String sign = Constants.signName;
           req.setSign(sign);

           /* International / Hong Kong, Macao and Taiwan SMS senderid: fill in the blank for domestic SMS. It is not opened by default. If you need to open it, please contact [sms helper] */
//            String senderid = "";
//            req.setSenderId(senderid);

           /* User's session content: it can carry context information such as user side ID, and the server will return it as it is */
//            String session = "xxx";
//            req.setSessionContext(session);

           /* SMS code number extension number: it is not opened by default. If you need to open, please contact [sms helper] */
//            String extendcode = "xxx";
//            req.setExtendCode(extendcode);

           /* Template ID: the approved template ID must be filled in. The template ID can be viewed in [SMS console] */
           String templateID = Constants.templateId;
           req.setTemplateID(templateID);

         /* Issue the mobile phone number, using e.164 standard, + [country or region code] [mobile phone number]
            * For example: + 8613711112222, in which there is a + number in front, 86 is the country code, 13711112222 is the mobile phone number, and there should be no more than 200 mobile phone numbers at most*/
           String[] phoneNumbers = {"+86"+phoneNumber};
           req.setPhoneNumberSet(phoneNumber);

//         Random verification code
           int vode=ValidateCode.generateValidateCode(6);
           String code=String.valueOf(vode);       

           /* Template parameter: if there is no template parameter, it is set to null*/
           String[] templateParams = {code};
           req.setTemplateParamSet(templateParams);

           /* The request is initiated by calling the SendSms method through the client object. Note that the request method name corresponds to the request object
            * The returned res is an instance of the SendSmsResponse class, which corresponds to the request object */
           SendSmsResponse res = client.SendSms(req);

           // Output json format string back package
           System.out.println(SendSmsResponse.toJsonString(res));

           // You can also take out a single value. You can view the definition of the returned field through the official website interface document or jump to the definition of the response object
          System.out.println(res.getRequestId());
           returString=res.getSendStatusSet();

       } catch (TencentCloudSDKException e) {
           e.printStackTrace();
       }

       return returString;
   }
}

Template parameters are {parameter 1} and {parameter 2} in the template content. I use the third template, and the parameters are random verification codes

//         Random verification code
           int vode=ValidateCode.generateValidateCode(6);
           String code=String.valueOf(vode);
           Constants.voicode=code;

    /* Template parameter: if there is no template parameter, it is set to null*/
           String[] templateParams = {code};
           req.setTemplateParamSet(templateParams);

Finally, write a controller to test it

//Send mobile verification code
   @RequestMapping(value="/sendCodeAgain")
   @ResponseBody
   public SendStatus[] sendCodeAgain(@RequestParam(value="telephone",required=true)  String Phone){

       String[] Phones = {"+86" + Phone};
       SendStatus[] ret = SendSmsUtil.sendSms(Phones);
      
       return ret;
   }

Sending verification code succeeded!!!

Hope to be useful to you. If the analysis is not appropriate, please give advice

Keywords: Java

Added by DJ Unique on Mon, 31 Jan 2022 06:05:49 +0200