How does PHP realize the flexible application of Alibaba Cloud SMS sdk in the project

  • 2021-12-12 03:45:10
  • OfStack

Install first


composer require alibabacloud/sdk

Then look at the alibabacloud official website document

https://packagist.org/packages/alibabacloud/sdk

Example

My_composer_aliyunsms.php


<?php
// use Swoft\Task\Bean\Annotation\Task;
// use AlibabaCloud\Client\AlibabaCloud;
// use AlibabaCloud\Client\Exception\ClientException;
// use AlibabaCloud\Client\Exception\ServerException;

use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;
use AlibabaCloud\Ecs\Ecs;

/**
 *  Ali message sending class 
 * @Task("ali")
 */
class My_composer_aliyunsms
{
  /**
   *  Send SMS verification code 
   */
  public function sendCode($config,$phone,$code)
  {
    $param = [
      'code' => $code
    ];
    AlibabaCloud::accessKeyClient($config['accessKeyId'], $config['accessSecret'])
      ->regionId($config['regionId'])
      ->asGlobalClient();

    try {
      $result = AlibabaCloud::rpcRequest()
        ->product('Dysmsapi')
        ->version('2017-05-25')
        ->action('SendSms')
        ->method('POST')
        ->options([
          'query' => [
            'PhoneNumbers' => $phone,
            'SignName' => $config['SignName'],
            'TemplateCode' => $config['TemplateCode'],
            'TemplateParam' => json_encode($param)
          ],
        ])
        ->request();
      return $result->toArray();
    } catch (ClientException $e) {
      echo $e->getErrorMessage() . PHP_EOL;
    } catch (ServerException $e) {
      echo $e->getErrorMessage() . PHP_EOL;
    }
  }
}

demo


 include 'My_composer_aliyunsms.php';
 $sms = new My_composer_aliyunsms();
 $phone='xxxxxx';
 $code='99999'; 
 $config = [
  'accessKeyId' => 'LTAIMje******hS',
  'accessSecret' => 'fMuQTLUrKQN******Z2m07',
  'SignName' => '****',
  'TemplateCode' => 'SMS_****04',
  'regionId' => 'cn-hangzhou'
 ];
 $re = $sms->sendCode($config,$phone,$code);  
 var_dump($re);

Related articles: