php and aliyun short message interface access

Using the Aliyun SMS API, we need to obtain the following necessary parameters in the console, which requires our own mobile phone validation + official audits many times, especially the audits need to be patient.

1. accessKeyId is equivalent to your personal account key;

2. accessKeySecret is paired with the above;

3. SignName personal signature. In the text message sent out, the signature will be displayed at the beginning, similar to dear user [signature]... In this format, SignName needs to be submitted for review;

4. Template Code template code, Aliyun SMS can not fully customize SMS, need to pass the audited template, and then replace the variables in the template itself, such as template: "Your verification code is ${code}", code is a variable, when using, you need to set the variable value {"code":"12345"} (the process of setting the variable value is demo. After sending out the short message, it becomes: "Your verification code is 12345", and each approved template will provide a template code;

The latest Aliyun SMS interface is suitable for Aliyun larger than the situation after moving.
Ali Bigger's short message interface has been used before. Recently, when I went to the project, I found that Ali Bigger moved to Ali Yun quietly. Aliyun's SDK files are numerous and confusing! The following code is the latest class that can be applied to Aliyun SMS service, personal test success!

<?php

/**
 * Aliyun Short Message Verification Code Sending Class
 * @author Administrator
 *
 */

class Sms {

    // Save error information

    public $error;

    // Access Key ID

    private $accessKeyId = '';

    // Access Access Key Secret

    private $accessKeySecret = '';

    // autograph

    private $signName = '';

    // Template ID

    private $templateCode = '';

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

        $cofig = array (

                'accessKeyId' => 'xxxxxxxxxxx',

                'accessKeySecret' => 'xxxxxxxxxx',

                'signName' => 'Your signature',

                'templateCode' => 'SMS_76510109'

        );

        // configuration parameter

        $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;

    }

    /**
     * autograph
     *
     * @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 (   //Amendments have been made 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 your actual template

        );

        //var_dump($params);die;

        // Compute the signature and add the signature result to the request parameter

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

        // Send requests (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) {

        // Ali Yun's text messages are messy.(Actually, Ali is bigger than Ali.)

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

        $message = array (

                'InvalidDayuStatus.Malformed' => 'Incorrect status of account short message opening',

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

                'InvalidTemplateCode.MalFormed' => 'Short Message Template Code Incorrect or incorrect template status',

                'InvalidRecNum.Malformed' => 'The number of the target cell phone is incorrect. The number of single sending cannot exceed 100.',

                'InvalidParamString.MalFormed' => 'Variables in SMS templates are not json format',

                'InvalidParamStringTemplate.Malformed' => 'Variables in short message template do not match the content of template',

                'InvalidSendSms' => 'Triggering Business Flow Control',

                'InvalidDayu.Malformed' => 'Variables cannot be url,Variables can be solidified in templates'

        );

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

            return $message [$status];

        }

        return $status;

    }

}

Call method:

//Generating Verification Code
$mobile = 'xxxxxxx';
$code = rand ( 1000, 9999 );
//Send short messages
$sms = new Sms();

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

}

 

PHP and Nine Interfaces Practical Video Course [Section 80]

Link: http://www.mano100.cn/thread-180-1-1.html

Tags: PHP Mobile SHA1 JSON

Posted on Fri, 06 Sep 2019 00:06:12 -0400 by simonb