<?php

namespace App\Services;

/**
 * 阿里云短信服务
 * Class AliSmsService
 * @package App\Services
 */
class AliSmsService
{
    public $accessKeyId;

    public $accessKeySecret;

    public $domain = "dysmsapi.aliyuncs.com";

    public $security = true;


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

        $this->accessKeySecret = $accessKeySecret;
    }


    /**
     * 发送短信
     * @param $templateCode
     * @param $signName
     * @param $phone
     * @param $templateParams
     * @return bool|\stdClass
     * @throws \Exception
     */
    public function send($templateCode, $signName, $phone, $templateParams)
    {
        $params = array();

        // 必填：是否启用https
        $security = false;

        // 必填: 请参阅 https://ak-console.aliyun.com/ 取得您的AK信息

        // 必填: 短信接收号码
        $params["PhoneNumbers"] = $phone;

        // 必填: 短信签名，应严格按"签名名称"填写，请参考: https://dysms.console.aliyun.com/dysms.htm#/develop/sign
        $params["SignName"] = $signName;

        // 必填: 短信模板Code，应严格按"模板CODE"填写, 请参考: https://dysms.console.aliyun.com/dysms.htm#/develop/template
        $params["TemplateCode"] = $templateCode;

        // 可选: 设置模板参数, 假如模板中存在变量需要替换则为必填项
        $params['TemplateParam'] = $templateParams;

        // 可选: 设置发送短信流水号
        $params['OutId'] = time() . rand(10000, 99999);

        // 可选: 上行短信扩展码, 扩展码字段控制在7位或以下，无特殊需求用户请忽略此字段
        $params['SmsUpExtendCode'] = "1234567";


        if (!empty($params["TemplateParam"]) && is_array($params["TemplateParam"])) {
            $params["TemplateParam"] = json_encode($params["TemplateParam"], JSON_UNESCAPED_UNICODE);
        }

        $params = array_merge($params, array(
            "RegionId" => "cn-hangzhou",
            "Action" => "SendSms",
            "Version" => "2017-05-25",
        ));

        // 此处可能会抛出异常，注意catch
        try {
            $response = $this->request($params);
        } catch (\Exception $e) {
            throw new \Exception($e->getMessage());
        }
        if ($response->Code != 'OK') {
            throw new \Exception($response->Code);
        }

        return $response;
    }


    /**
     * 批量发送
     * @param $templateCode
     * @param $signName
     * @param  array  $phoneNumbers
     * @param  array  $templateParams
     * @return bool|\stdClass
     * @throws \Exception
     */
    public function sendBatch($templateCode, $signName, array $phoneNumbers, array $templateParams)
    {
        $params = array();

        // 必填：是否启用https
        $security = false;

        // 必填: 待发送手机号。支持JSON格式的批量调用，批量上限为100个手机号码,批量调用相对于单条调用及时性稍有延迟,验证码类型的短信推荐使用单条调用的方式
        $params["PhoneNumberJson"] = $phoneNumbers;

        // 必填: 短信签名，支持不同的号码发送不同的短信签名，每个签名都应严格按"签名名称"填写，请参考: https://dysms.console.aliyun.com/dysms.htm#/develop/sign
        foreach ($phoneNumbers as $key => $value) {
            $params["SignNameJson"][] = $signName;
        }

        // 必填: 短信模板Code，应严格按"模板CODE"填写, 请参考: https://dysms.console.aliyun.com/dysms.htm#/develop/template
        $params["TemplateCode"] = $templateCode;

        // 必填: 模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为
        // 友情提示:如果JSON中需要带换行符,请参照标准的JSON协议对换行符的要求,比如短信内容中包含\r\n的情况在JSON中需要表示成\\r\\n,否则会导致JSON在服务端解析失败
        $params["TemplateParamJson"] = $templateParams;

        // 可选: 上行短信扩展码, 扩展码字段控制在7位或以下，无特殊需求用户请忽略此字段
        // $params["SmsUpExtendCodeJson"] = json_encode(array("90997","90998"));


        // *** 需用户填写部分结束, 以下代码若无必要无需更改 ***
        $params["TemplateParamJson"] = json_encode($params["TemplateParamJson"], JSON_UNESCAPED_UNICODE);
        $params["SignNameJson"] = json_encode($params["SignNameJson"], JSON_UNESCAPED_UNICODE);
        $params["PhoneNumberJson"] = json_encode($params["PhoneNumberJson"], JSON_UNESCAPED_UNICODE);

        if (!empty($params["SmsUpExtendCodeJson"]) && is_array($params["SmsUpExtendCodeJson"])) {
            $params["SmsUpExtendCodeJson"] = json_encode($params["SmsUpExtendCodeJson"], JSON_UNESCAPED_UNICODE);
        }

        $params = array_merge($params, array(
            "RegionId" => "cn-hangzhou",
            "Action" => "SendBatchSms",
            "Version" => "2017-05-25",
        ));

        // 初始化SignatureHelper实例用于设置参数，签名以及发送请求

        // 此处可能会抛出异常，注意catch
        try {
            $response = $this->request($params);
        } catch (\Exception $e) {
            throw new \Exception($e->getMessage());
        }
        if ($response->Code != 'OK') {
            throw new \Exception($response->Code);
        }

        return $response;
    }


    /**
     * 短信发送记录查询
     * @param $phoneNumber
     * @param $sendDate
     * @param  null  $bizId
     * @param  int  $currentPage
     * @param  int  $pageSize
     * @return bool|\stdClass
     * @throws \Exception
     */
    public function querySendDetails($phoneNumber, $sendDate, $bizId = null, $currentPage = 1, $pageSize = 10)
    {
        $params = array();

        // 必填: 短信接收号码
        $params["PhoneNumber"] = $phoneNumber;

        // 必填: 短信发送日期，格式Ymd，支持近30天记录查询
        $params["SendDate"] = $sendDate;

        // 必填: 分页大小
        $params["PageSize"] = $pageSize;

        // 必填: 当前页码
        $params["CurrentPage"] = $currentPage;

        // 可选: 设置发送短信流水号
        if ($bizId) {
            $params["BizId"] = $bizId;
        }

        $params = array_merge($params, array(
            "RegionId" => "cn-hangzhou",
            "Action" => "QuerySendDetails",
            "Version" => "2017-05-25",
        ));
        // *** 需用户填写部分结束, 以下代码若无必要无需更改 ***

        // 初始化SignatureHelper实例用于设置参数，签名以及发送请求
        // 此处可能会抛出异常，注意catch

        try {
            $response = $this->request($params);
        } catch (\Exception $e) {
            throw new \Exception($e->getMessage());
        }
        if ($response->Code != 'OK') {
            throw new \Exception($response->Code);
        }

        return $response;
    }


    /**
     * 生成签名并发起请求
     *
     * @param  array  $params  API具体参数
     * @param  string  $method  boolean 使用GET或POST方法请求，VPC仅支持POST
     * @return bool|\stdClass 返回API接口调用结果，当发生错误时返回false
     */
    private function request($params, $method = 'POST')
    {
        $apiParams = array_merge(array(
            "SignatureMethod" => "HMAC-SHA1",
            "SignatureNonce" => uniqid(mt_rand(0, 0xffff), true),
            "SignatureVersion" => "1.0",
            "AccessKeyId" => $this->accessKeyId,
            "Timestamp" => gmdate("Y-m-d\TH:i:s\Z"),
            "Format" => "JSON",
        ), $params);
        ksort($apiParams);

        $sortedQueryStringTmp = "";
        foreach ($apiParams as $key => $value) {
            $sortedQueryStringTmp .= "&" . $this->encode($key) . "=" . $this->encode($value);
        }

        $stringToSign = "${method}&%2F&" . $this->encode(substr($sortedQueryStringTmp, 1));

        $sign = base64_encode(hash_hmac("sha1", $stringToSign, $this->accessKeySecret . "&", true));

        $signature = $this->encode($sign);

        $url = ($this->security ? 'https' : 'http') . "://{$this->domain}/";

        try {
            $content = $this->fetchContent($url, $method, "Signature={$signature}{$sortedQueryStringTmp}");

            return json_decode($content);
        } catch (\Exception $e) {
            return false;
        }
    }

    private function encode($str)
    {
        $res = urlencode($str);
        $res = preg_replace("/\+/", "%20", $res);
        $res = preg_replace("/\*/", "%2A", $res);
        $res = preg_replace("/%7E/", "~", $res);

        return $res;
    }

    private function fetchContent($url, $method, $body)
    {
        $ch = curl_init();

        if ($method == 'POST') {
            curl_setopt($ch, CURLOPT_POST, 1);//post提交方式
            curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
        } else {
            $url .= '?' . $body;
        }

        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_TIMEOUT, 5);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            "x-sdk-client" => "php/2.0.0",
        ));

        if (substr($url, 0, 5) == 'https') {
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        }

        $rtn = curl_exec($ch);

        if ($rtn === false) {
            // 大多由设置等原因引起，一般无法保障后续逻辑正常执行，
            // 所以这里触发的是E_USER_ERROR，会终止脚本执行，无法被try...catch捕获，需要用户排查环境、网络等故障
            trigger_error("[CURL_" . curl_errno($ch) . "]: " . curl_error($ch), E_USER_ERROR);
        }
        curl_close($ch);

        return $rtn;
    }
}
