<?php

require_once APPPATH . '/third_party/aliyun/vendor/autoload.php';

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

class SmsUtil
{

    function __construct()
    {
    }

    /**
     * 发送短信
     *
     * @param string $mobile 	手机号码
     * @param string $sign 	签名
     * @param string $temp_id 	模板id
     * @param string $code 	验证码
     */
    public function sendSMS($mobile, $sign, $temp_id, $code)
    {
        $ci = &get_instance();
        AlibabaCloud::accessKeyClient($ci->config->item("aliyun_sms_AccessKeyId"), $ci->config->item("aliyun_sms_AccessKeySecret"))
            ->regionId('cn-hangzhou') // replace regionId as you need
            ->asGlobalClient();

        try {
            $result = AlibabaCloud::rpcRequest()
                ->product('Dysmsapi')
                // ->scheme('https') // https | http
                ->version('2017-05-25')
                ->action('SendSms')
                ->method('POST')
                ->options([
                    'query' => [
                        'PhoneNumbers'  => $mobile,
                        'SignName'      => $sign,
                        'TemplateCode'  => $temp_id,
                        'TemplateParam' => '{"code":"' . $code . '"}',
                    ],
                ])
                ->request();
            // echo json_encode($result);die;
            $r = $result->toArray();
            return $r;
            // print_r($r);
        } catch (ClientException $e) {
            return array("Message" => $e->getErrorMessage());
            // echo $e->getErrorMessage() . PHP_EOL;
        } catch (ServerException $e) {
            // echo $e->getErrorMessage() . PHP_EOL;
            return array("Message" => $e->getErrorMessage());
        }
    }
}
