SmsMessage.php 2.87 KB
<?php

namespace domain\system;

use Yii;
use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;
use common\helpers\Log as AppLog;

/**
 * 基于阿里大鱼的短信通知
 * Class SmsMessage
 *
 */
class SmsMessage
{
    /**
     * @param string $mobile
     * @param string $signName
     * @param string $templateCode
     * @param array $templateParam
     * @return array
     */
    private function send(string $mobile, string $signName, string $templateCode, array $templateParam)
    {
        try {
            AlibabaCloud::accessKeyClient(Yii::$app->params['sms']["smsKey"], Yii::$app->params['sms']["smsSecret"])->asDefaultClient();

            $query = [
                'PhoneNumbers' => $mobile,
                'SignName' => $signName,
                'TemplateCode' => $templateCode,
            ];
            if ($templateParam) {
                $query['TemplateParam'] = json_encode($templateParam);
            }

            $result = AlibabaCloud::rpc()
                ->regionId("cn-hongkong") // 指定请求的区域,不指定则使用客户端区域、默认区域
                ->product('Dysmsapi') // 指定产品
                ->version('2017-05-25') // 指定产品版本
                ->action('SendSms') // 指定产品接口
                ->method('POST') // 指定请求方式
                ->options([
                    'query' => $query,
                ])
                ->request(); // 发起请求并返回结果对象,请求需要放在设置的最后面

            $result = $result->toArray();

            AppLog::DEBUG('短信发送结果:' . '<pre>' . print_r($result, 1) . '</pre>');

            return $result;

        } catch (ClientException $exception) {
            AppLog::DEBUG('短信发送出错:' . $exception->getErrorMessage());
        } catch (ServerException $exception) {
            AppLog::DEBUG('短信发送出错:' . $exception->getErrorMessage());
        }
    }

    /**
     * 手机验证码
     * 模版内容: 验证码${code},您正在注册成为新用户,感谢您的支持!
     * 申请说明: 用户注册验证码
     * 模版CODE: SMS_179880510
     * @param $phone
     * @param $code
     * @param $signName
     * @return mixed
     */
    public function sendRegCode($phone, $code, $signName = '科技')
    {
        //$this->send($phone, $signName, "SMS_179880510", ["code" => $code]);
        return true;
    }

    /**
     * 登录验证码
     * 模版内容: 模版CODE: SMS_180755775
     * 模版内容: 尊敬的用户,您的登录码为:${code},请勿泄漏于他人!
     * @param $phone
     * @return mixed
     */
    public function sendLoginCode($phone, $code, $signName = '科技')
    {
        //$this->send($phone, $signName, "SMS_180755775", ["code" => $code]);
        return true;
    }
}