php对接阿里云短信通用类

<?php

/**
 * 阿里云短信验证码发送类
 */
class Util_AliyunSms
{
    // 保存错误信息
    public $error;
    // Access Key ID
    private $accessKeyId = ‘‘;
    // Access Access Key Secret
    private $accessKeySecret = ‘‘;
    // 签名
    private $signName = ‘‘;
    // 模版ID
    private $templateCode = ‘‘;

    public function __construct($config = array())
    {
        //新配置
        $config = array(
            ‘accessKeyId‘ => ‘LTAI5tHwAGgXXXXXXXXXXX‘,
            ‘accessKeySecret‘ => ‘VGdydLxHwfAlH6W4XXXXXXXXXX‘,
            ‘signName‘ => ‘集印猫‘,
            ‘templateCode‘ => ‘SMS_190145146‘    // 身份验证验证码短信模板
        );
        // 配置参数
        $this->accessKeyId = $config [‘accessKeyId‘];
        $this->accessKeySecret = $config [‘accessKeySecret‘];
        $this->signName = $config [‘signName‘];
        $this->templateCode = $config [‘templateCode‘];
    }

    private function percentEncode($string)
    {
        $string = urlencode($string);
        $string = preg_replace(‘/\+/‘, ‘%20‘, $string);
        $string = preg_replace(‘/\*/‘, ‘%2A‘, $string);
        $string = preg_replace(‘/%7E/‘, ‘~‘, $string);
        return $string;
    }

    /**
     * 签名
     *
     * @param unknown $parameters
     * @param unknown $accessKeySecret
     * @return string
     */
    private function computeSignature($parameters, $accessKeySecret)
    {
        ksort($parameters);
        $canonicalizedQueryString = ‘‘;
        foreach ($parameters as $key => $value) {
            $canonicalizedQueryString .= ‘&‘ . $this->percentEncode($key) . ‘=‘ . $this->percentEncode($value);
        }
        $stringToSign = ‘GET&%2F&‘ . $this->percentencode(substr($canonicalizedQueryString, 1));
        $signature = base64_encode(hash_hmac(‘sha1‘, $stringToSign, $accessKeySecret . ‘&‘, true));
        return $signature;
    }

    /**
     * 发送验证码
     * https://help.aliyun.com/document_detail/44362.html?spm=5176.doc44364.2.1.LeeHSH
     * @param unknown $mobile
     * @param unknown $verify_code
     *
     */
    public function sendVerify($mobile, $verify_code)
    {
        $params = array(
            // 公共参数
            ‘SignName‘ => $this->signName,
            ‘Format‘ => ‘JSON‘,
            ‘Version‘ => ‘2017-05-25‘,
            ‘AccessKeyId‘ => $this->accessKeyId,
            ‘SignatureVersion‘ => ‘1.0‘,
            ‘SignatureMethod‘ => ‘HMAC-SHA1‘,
            ‘SignatureNonce‘ => uniqid (),
            ‘Timestamp‘ => gmdate ( ‘Y-m-d\TH:i:s\Z‘ ),
            ‘Action‘ => ‘SendSms‘,
            ‘TemplateCode‘ => $this->templateCode,
            ‘PhoneNumbers‘ => $mobile,
            ‘TemplateParam‘ => ‘{"code":"‘ . $verify_code . ‘"}‘
        );

        // 计算签名并把签名结果加入请求参数
        $params [‘Signature‘] = $this->computeSignature($params, $this->accessKeySecret);
        // 发送请求
        Util_Log::write(Util_Log::LOG_TYPE_INFO,‘======发送短信参数=====‘.json_encode($params));
        //$url = ‘https://sms.aliyuncs.com/?‘ . http_build_query($params);
        $url = ‘https://dysmsapi.aliyuncs.com/?‘ . http_build_query($params);
        Util_Log::write(Util_Log::LOG_TYPE_INFO,‘======发送短信url=====‘.$url);
        $result = Util_Request::request($url);
        Util_Log::write(Util_Log::LOG_TYPE_INFO,‘======发送短信结果=====‘.$result);
        $result = json_decode($result, true);
        if (isset ($result [‘Code‘])) {
            $this->error = $this->getErrorMessage($result [‘Code‘]);
            if($this->error != ‘OK‘){
                return false;
            }
        }
        return true;
    }

    public function send($mobile, $templateCode, $paramString, $signName = ‘‘)
    {
        $params = array(
            // 公共参数
            ‘SignName‘ => $this->signName,
            ‘Format‘ => ‘JSON‘,
            ‘Version‘ => ‘2017-05-25‘,
            ‘AccessKeyId‘ => $this->accessKeyId,
            ‘SignatureVersion‘ => ‘1.0‘,
            ‘SignatureMethod‘ => ‘HMAC-SHA1‘,
            ‘SignatureNonce‘ => uniqid (),
            ‘Timestamp‘ => gmdate ( ‘Y-m-d\TH:i:s\Z‘ ),
            ‘Action‘ => ‘SendSms‘,
            ‘TemplateCode‘ => $templateCode,
            ‘PhoneNumbers‘ => $mobile,
            ‘TemplateParam‘ => $paramString,
        );
        // 计算签名并把签名结果加入请求参数
        $params [‘Signature‘] = $this->computeSignature($params, $this->accessKeySecret);
        // 发送请求
        $url = ‘https://sms.aliyuncs.com/?‘ . http_build_query($params);
        $result = Util_Request::request($url);
        $result = json_decode($result, true);
        Util_Log::write(Util_Log::LOG_TYPE_INFO, $result);
        if (isset ($result [‘Code‘])) {
            $this->error = $this->getErrorMessage($result [‘Code‘]);
            if($this->error != ‘OK‘){
                return false;
            }
        }
        return true;
    }

    /**
     * 获取详细错误信息
     *
     * @param unknown $status
     */
    private function getErrorMessage($status)
    {
        // 阿里云的短信 乱八七糟的(其实是用的阿里大于)
        // https://help.aliyun.com/document_detail/44364.html
        $message = array(
            ‘InvalidDayuStatus.Malformed‘ => ‘账户短信开通状态不正确‘,
            ‘InvalidSignName.Malformed‘ => ‘短信签名不正确或签名状态不正确‘,
            ‘InvalidTemplateCode.MalFormed‘ => ‘短信模板Code不正确或者模板状态不正确‘,
            ‘InvalidRecNum.Malformed‘ => ‘目标手机号不正确,单次发送数量不能超过100‘,
            ‘InvalidParamString.MalFormed‘ => ‘短信模板中变量不是json格式‘,
            ‘InvalidParamStringTemplate.Malformed‘ => ‘短信模板中变量与模板内容不匹配‘,
            ‘InvalidSendSms‘ => ‘触发业务流控‘,
            ‘InvalidDayu.Malformed‘ => ‘变量不能是url,可以将变量固化在模板中‘,
            ‘InvalidAction.NotFound‘ => ‘接口地址不存在,请检查参数或地址‘,
        );
        if (isset ($message [$status])) {
            return $message [$status];
        }
        return $status;
    }
}

  上面是通用接口类,调用方法如如下:

<?php
$verify_code = rand(100000, 999999); //随机生成verify_code
$sms = new Util_AliyunSms(); //新建发送短信对象
$res = $sms->sendVerify($mobile, $verify_code);
if(!$res) return false;    
return true;

  

php对接阿里云短信通用类

上一篇:jsplumb使用(二)


下一篇:用pytorch实现Autoencoder