单文件PHP实现阿里云短信发送功能

今日在review代码时,忽见某高手为了实现发送短信,竟然引入了完整的aliyunsdk,SDK代码行数比所有业务代码都要多出数倍,搞的我整个人都不好了……

仔细查阅阿里云官方文档后,分享一个单文件调用阿里云接口发送短信的PHP实现吧。

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

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

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

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

    public function __construct($config)
    {
        $this->accessKeyId = $config['sms_appid'];
        $this->accessKeySecret = $config['sms_secret'];

        $this->signName = $config['sms_signame'];
        $this->templateCode = $config['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;
        }
    }
}

附录

180行代码实现全球短信发送功能

文章作者: 若海; 原文链接: https://www.rehiy.com/post/299/; 转载需声明来自技术写真 - 若海

添加新评论