阿里云短信发送代码封装

忽见某一高手为了实现发送短信,竟然引入了整个aliyunsdk,我一阵语塞。。。

在这里分享一个项目中调用阿里云短信发送的PHP实现吧。

注意:下面的类中 namespaceconfig 均为伪代码,请自行替换。

/**
 * 阿里云短信
 * @package rehiy\util
 * @author 若海<https://www.rehiy.com>
 */

namespace rehiy\util;

use rehiy\Config;
use rehiy\Exception;

class AliyunSms
{
    protected $accessKeyId = '';
    protected $accessKeySecret = '';

    protected $signName = '';
    protected $templateCode = '';

    protected $apiUrl = 'http://dysmsapi.aliyuncs.com/';

    public function __construct()
    {
        $this->accessKeyId = Config::get('sms_appid');
        $this->accessKeySecret = Config::get('sms_secret');

        $this->signName = Config::get('sms_signame');
        $this->templateCode = Config::get('sms_template_code');
    }

    public function send(string $phone, array $data)
    {
        $params = [
            'AccessKeyId' => $this->accessKeyId,
            'Action' => 'SendSms',
            'Format' => 'JSON',
            'PhoneNumbers' => $phone,
            'RegionId' => 'cn-hangzhou',
            'SignName' => $this->signName,
            'SignatureMethod' => 'HMAC-SHA1',
            'SignatureNonce' => uniqid(mt_rand(0, 0xffff), true),
            'SignatureVersion' => '1.0',
            'Timestamp' => gmdate('Y-m-d\TH:i:s\Z'),
            'Version' => '2017-05-25',
            'TemplateCode' => $this->templateCode,
            'TemplateParam' => json_encode($data, JSON_UNESCAPED_UNICODE),
        ];

        ksort($params);
        $sortedQuery = http_build_query($params, '', '&', PHP_QUERY_RFC3986);

        $signature = "POST&%2F&" . rawurlencode($sortedQuery);
        $signature = rawurlencode(
            base64_encode(hash_hmac('sha1', $signature, $this->accessKeySecret . '&', true))
        );

        $body = "Signature={$signature}&{$sortedQuery}";
        $header = ['x-sdk-client' => 'php/2.0.0'];

        return $this->httpRequest('POST', $this->apiUrl, $body, $header);
    }

    private function httpRequest(string $method, string $url, $data = null, $header = [])
    {
        $ch = curl_init($url);

        curl_setopt($ch, CURLOPT_TIMEOUT, 25);
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);

        if (!empty($header)) {
            curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        }

        if ($data && is_array($data)) {
            $data = http_build_query($data);
        }
        if ($method == 'POST' && $data) {
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        }

        list($body, $errno, $error) = [
            curl_exec($ch), curl_errno($ch), curl_error($ch), curl_close($ch)
        ];

        if ($errno != 0) {
            throw new Exception('CURL - ' . $error, $errno);
        }

        try {
            return json_decode($body, true);
        } catch (Exception $e) {
            return false;
        }
    }
}
php
最后修改于:2022年04月24日 08:54

添加新评论