<?php

class AliyunSms {

    protected $accessKeyId;
    protected $accessKeySecret;
    protected $signName;
    protected $templateCode;

    public function __construct($accessKeyId, $accessKeySecret, $signName, $templateCode) {
        $this->accessKeyId = $accessKeyId;
        $this->accessKeySecret = $accessKeySecret;
        $this->signName = $signName;
        $this->templateCode = $templateCode;
    }

    public function sendSMS($phone, $templateParam) {
        $params = array (
            'PhoneNumbers' => $phone,
            'SignName' => $this->signName,
            'TemplateCode' => $this->templateCode,
            'TemplateParam' => json_encode($templateParam),
        );

        $params['RegionId'] = 'cn-hangzhou';
        $params['Action'] = 'SendSms';
        $params['Version'] = '2017-05-25';
        $params['Format'] = 'JSON';
        $params['SignatureMethod'] = 'HMAC-SHA1';
        $params['SignatureVersion'] = '1.0';
        $params['SignatureNonce'] = uniqid();
        $params['Timestamp'] = gmdate('Y-m-d\TH:i:s\Z');
        $params['AccessKeyId'] = $this->accessKeyId;

        ksort($params);

        $canonicalizedQueryString = '';
        foreach ($params as $key => $value) {
            $canonicalizedQueryString .= '&' . $this->encode($key) . '=' . $this->encode($value);
        }

        $stringToSign = 'GET&%2F&' . $this->encode(substr($canonicalizedQueryString, 1));
        $signature = base64_encode(hash_hmac('sha1', $stringToSign, $this->accessKeySecret . '&', true));

        $requestUrl = 'http://dysmsapi.aliyuncs.com/?Signature=' . $this->encode($signature) . $canonicalizedQueryString;

        // 发送 HTTP 请求并处理响应
        $response = file_get_contents($requestUrl);
        $responseObject = json_decode($response);

        if ($responseObject->Code == 'OK') {
            return true;
        } else {
            return false;
        }
    }

    protected function encode($str) {
        $res = urlencode($str);
        $res = str_replace('+', '%20', $res);
        $res = str_replace('*', '%2A', $res);
        $res = str_replace('%7E', '~', $res);
        return $res;
    }
}