PHP and alicloud SMS interface access operation case analysis

Time:2020-9-13

This article describes the PHP and alicloud SMS interface access operation. For your reference, the details are as follows:

To use alicloud SMS API, you need to obtain the following necessary parameters from the console, which requires their own mobile phone verification + official audit for many times, especially the audit needs to be patient.

1. Accesskeyid is equivalent to your personal account key;

2. Accesskeysecret is paired with upper;

3. Signname personal signature. In the sent SMS, this signature will be displayed at the beginning, similar to [signature] Dear user… In this format, signname needs to be submitted for approval;

4. Templatecode template code: alicloud SMS cannot completely customize SMS messages. You need to pass the audit template, and then replace the variables in the template yourself, such as the template: “your verification code is $[Code]”, Code is a variable. When you use it, you need to set the variable value {“code”: “12345”} (the process of setting the variable value is implemented in the demo). After the SMS is sent out, it will become: “your verification code is 12345”. Each approved template will provide a template code;

The latest alicloud SMS interface is applicable to the situation after Alibaba moves.

Previously, I have been using the SMS interface of Alida. Recently, I found that Alida had quietly moved to alicloud when I was on the project! Alicloud‘s SDK files are so numerous that I can’t understand them! The following code is the latest class that can be applied to alicloud SMS service. The test is successful!

<?php
/**
 *Alicloud SMS verification code sending class
 * @author Administrator
 *
 */
class Sms {

  //Save error message

  public $error;

  // Access Key ID

  private $accessKeyId = '';

  // Access Access Key Secret

  private $accessKeySecret = '';

  //Signature

  private $signName = '';

  //Template ID

  private $templateCode = '';

  public function __construct($cofig = array()) {

    $cofig = array (

        'accessKeyId' => 'xxxxxxxxxxx',

        'accessKeySecret' => 'xxxxxxxxxx',

        'signname '= >'your signature',

        'templateCode' => 'SMS_76510109'

    );

    //Configuration parameters

    $this->accessKeyId = $cofig ['accessKeyId'];

    $this->accessKeySecret = $cofig ['accessKeySecret'];

    $this->signName = $cofig ['signName'];

    $this->templateCode = $cofig ['templateCode'];

  }

  private function percentEncode($string) {

    $string = urlencode ( $string );

    $string = preg_replace ( '/\+/', '%20', $string );

    $string = preg_replace ( '/\*/', '%2A', $string );

    $string = preg_replace ( '/%7E/', '~', $string );

    return $string;

  }

  /**
   *Signature
   *
   * @param unknown $parameters      
   * @param unknown $accessKeySecret      
   * @return string
   */

  private function computeSignature($parameters, $accessKeySecret) {

    ksort ( $parameters );

    $canonicalizedQueryString = '';

    foreach ( $parameters as $key => $value ) {

      $canonicalizedQueryString .= '&' . $this->percentEncode ( $key ) . '=' . $this->percentEncode ( $value );

    }

    $stringToSign = 'GET&%2F&' . $this->percentencode ( substr ( $canonicalizedQueryString, 1 ) );

    $signature = base64_encode ( hash_hmac ( 'sha1', $stringToSign, $accessKeySecret . '&', true ) );

    return $signature;

  }

  /**
   * @param unknown $mobile      
   * @param unknown $verify_code      
   *
   */

  public function send_verify($mobile, $verify_code) {

    $params = array (// modified here)

        'SignName' => $this->signName,

        'Format' => 'JSON',

        'Version' => '2017-05-25',

        'AccessKeyId' => $this->accessKeyId,

        'SignatureVersion' => '1.0',

        'SignatureMethod' => 'HMAC-SHA1',

        'SignatureNonce' => uniqid (),

        'Timestamp' => gmdate ( 'Y-m-d\TH:i:s\Z' ),

        'Action' => 'SendSms',

        'TemplateCode' => $this->templateCode,

        'PhoneNumbers' => $mobile,

        //'TemplateParam' => '{"code":"' . $verify_code . '"}' 

        'templateparam '= >' {time ': "1234"}' // replace with your own actual template

    );

    //var_dump($params);die;

    //The signature is calculated and the signature result is added to the request parameters

    $params ['Signature'] = $this->computeSignature ( $params, $this->accessKeySecret );

    //Send request (modified here)

    //$url = 'https://sms.aliyuncs.com/?' . http_build_query ( $params );

    $url = 'http://dysmsapi.aliyuncs.com/?' . http_build_query ( $params );

    $ch = curl_init ();

    curl_setopt ( $ch, CURLOPT_URL, $url );

    curl_setopt ( $ch, CURLOPT_SSL_VERIFYPEER, FALSE );

    curl_setopt ( $ch, CURLOPT_SSL_VERIFYHOST, FALSE );

    curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );

    curl_setopt ( $ch, CURLOPT_TIMEOUT, 10 );

    $result = curl_exec ( $ch );

    curl_close ( $ch );

    $result = json_decode ( $result, true );

    //var_dump($result);die;

    if (isset ( $result ['Code'] )) {

      $this->error = $this->getErrorMessage ( $result ['Code'] );

      return false;

    }

    return true;

  }

  /**
   *Get detailed error information
   *
   * @param unknown $status      
   */

  public function getErrorMessage($status) {

    //Alibaba cloud's SMS are in a mess (in fact, it's used by Aliyu)

    // https://api.alidayu.com/doc2/apiDetail?spm=a3142.7629140.1.19.SmdYoA&apiId=25450

    $message = array (

        ' InvalidDayuStatus.Malformed '= >' account SMS activation status is incorrect ',

        ' InvalidSignName.Malformed '= >' SMS signature is incorrect or signature status is incorrect ',

        ' InvalidTemplateCode.MalFormed '= >' SMS template code is incorrect or template status is incorrect ',

        ' InvalidRecNum.Malformed '= >' the target mobile phone number is incorrect, the number of messages sent at a time cannot exceed 100 ',

        ' InvalidParamString.MalFormed '=' the format of the message is not 'JSON template',

        'Invali dParamStringTemplate.Malformed '= >' the variables in the SMS template do not match the template content ',

        'invalidsendsms' = >'trigger business flow control',

        ' InvalidDayu.Malformed '= >' the variable cannot be URL, it can be solidified in the template '

    );

    if (isset ( $message [$status] )) {

      return $message [$status];

    }

    return $status;

  }

}

Call method:

//Generate captcha
$mobile = 'xxxxxxx';
$code = rand ( 1000, 9999 );
//Send SMS
$sms = new Sms();

//Test mode
$status = $sms->send_verify($mobile, $code);
if (!$status) {
 echo $sms->error;

}

More interested readers about PHP related content can view the special topics of this website: summary of PHP process and thread operation skills, summary of PHP network programming skills, introduction course of PHP basic syntax, Encyclopedia of PHP array operation skills, summary of PHP string usage, introduction course of PHP + MySQL database operation and common database operation skills of PHP Summary

I hope this article will help you with PHP programming.