最新消息:文章中包含代码时,请遵守代码高亮规范!

阿里云短信接口的接入(原创)

PHP Alex 935浏览 0评论

写项目时遇见要求接入阿里云短信接口,在框架的基础上开始接入短信接口。

要继承的抽象类

abstract class AbstractSms extends ProjectControl implements InterfaceThirdParty
{

    /**
     * 发送短信抽象方法
     *
     * @param $phone
     * @param $content
     * @return mixed
     */
    abstract function sendSms($phone, $content);

    /**
     * 短信验证码
     *
     * @param $phone
     * @param $sale
     * @param $type
     * @return string
     */
    public function template($phone, $sale, $type)
    {
        $content = '';

        switch ($type){
            case 1:
                $content = '注册验证码为'.$sale.',请不要告诉他人!';
                break;
            case 2:
                $content = '找回密码验证码为'.$sale.',请不要告诉他人!';
                break;
        }

        return $content;
    }

    /**
     * 短信验证码验证
     *
     * @param $phone
     * @param $sale
     * @param $type
     * @return string
     */
    public function is_sale($phone, $sale, $type)
    {
        if(empty($sale)){
            $result = '短信验证码不能为空';
        }else {
            $salt_info = self::$conn->fetchAssoc("SELECT * FROM sms_record WHERE phone = ? AND type = ? AND salt = ?  AND is_used = 0 LIMIT 1", array($phone, $type, $sale));
            $result = '';
            if ($salt_info['times'] >= 5) {
                $result = '该短信验证码验证次数超过限制';
            } else if ($salt_info['is_used'] == 1) {
                $result = '该短信验证码已被验证';
            } else if ($salt_info['salt'] != $sale) {
                //验证次数加1
                self::$conn->update('sms_record', array('times' => $salt_info['times'] + 1), array('id' => $salt_info['id']));
                $result = '短信验证码不正确';
            } else if (time() - $salt_info['happen_time'] > 1800) {
                $result  = '短信验证码失效';
            } else {
                self::$conn->update('sms_record', array('is_used' => 1), array('id' => $salt_info['id']));
            }
        }

        return $result;
    }

    /**
     * 发送短信验证码
     *
     * @param $phone
     * @param $type
     * @param $is_beta
     * @return array
     */
    public function sendPhoneCode($phone, $type, $is_beta)
    {
        //注销以前的验证码
        self::$conn->executeUpdate("UPDATE sms_record SET happen_time = ? WHERE phone = ? and type = ? and happen_time >= ?", array(time() - 1800,
            $phone, $type, time() - 1800));

        $data['salt'] = $this->get('services.strings')->generateNumberRandom(4);

        //发送短信验证码
        $judge = $this->userMessage($phone, $data['salt'], $type);

        if($judge['errorCode'] != 0){
            return $judge;
        }

        $data['phone'] = $phone;
        $data['happen_time'] = time();
        $data['times'] = 0;
        $data['is_used'] = 0;
        $data['ip'] = $_SERVER['REMOTE_ADDR'];
        $data['type'] = $type;
        self::$conn->insert('sms_record', $data);

        if($is_beta == 0){
            $data['salt'] = null;
        }

        return Responses::arrays('发送成功', $this->getParameter('error_code_success'), array('salt' => $data['salt']));
    }

    /**
     * 发送短信验证码
     *
     * @param $phone
     * @param string $sale  验证码
     * @param $type  1:注册  2;找回密码
     * @return array
     */
    public function userMessage($phone, $sale, $type)
    {
        $content = $this->template($phone, $sale, $type);

        return $this->sendSms($phone, $content);
    }
}

class AliYun extends AbstractSms
{
    static $acsClient = null;

    /**
     * 取得AcsClient
     *
     * @return DefaultAcsClient
     */
    public static function getAcsClient() {
        //产品名称:云通信流量服务API产品,开发者无需替换
        $product = "Dysmsapi";

        //产品域名,开发者无需替换
        $domain = "dysmsapi.aliyuncs.com";

        // TODO 此处需要替换成开发者自己的AK (https://ak-console.aliyun.com/)
        $accessKeyId = "***********"; // AccessKeyId

        $accessKeySecret = "***********"; // AccessKeySecret

        // 暂时不支持多Region
        $region = "cn-hangzhou";

        // 服务结点
        $endPointName = "cn-hangzhou";


        if(static::$acsClient == null) {

            //初始化acsClient,暂不支持region化
            $profile = DefaultProfile::getProfile($region, $accessKeyId, $accessKeySecret);

            // 增加服务结点
            DefaultProfile::addEndpoint($endPointName, $region, $product, $domain);

            // 初始化AcsClient用于发起请求
            static::$acsClient = new DefaultAcsClient($profile);
        }
        return static::$acsClient;
    }


    public function sendSms($phone, $content, $templateCode = ''){

        if(empty($content)){
            $content['code']  = '';
        }

        // 初始化SendSmsRequest实例用于设置发送短信的参数
        $request = new SendSmsRequest();

        // 必填,设置短信接收号码
        $request->setPhoneNumbers($phone);

        // 必填,设置签名名称,应严格按"签名名称"填写
        $request->setSignName("德新家");

        // 必填,设置模板CODE,应严格按"模板CODE"填写
        $request->setTemplateCode($templateCode);

        // 可选,设置模板参数, 假如模板中存在变量需要替换则为必填项
        $request->setTemplateParam(json_encode(  // 短信模板中字段的值
             $content , JSON_UNESCAPED_UNICODE));

        // 发起访问请求
        $acsResponse = static::getAcsClient()->getAcsResponse($request);

        return $this->returnRewrite($acsResponse);
    }



    public function returnRewrite($r)
    {
        if ($r->Code == 'OK') {
            return Responses::arrays('发送成功', 0);
        }else{
            switch ($r->Code){
                case 'isv.OUT_OF_SERVICE':
                    $r = '短信业务停机';
                    break;
                case 'isv.SMS_TEMPLATE_ILLEGAL':
                    $r = '短信模板不合法';
                    break;

                case 'isv.SMS_SIGNATURE_ILLEGAL':
                    $r = '短信签名不合法';
                    break;

                case 'isv.MOBILE_NUMBER_ILLEGAL':
                    $r = '手机号码不合法';
                    break;

                case 'isv.AMOUNT_NOT_ENOUGH':
                    $r = '短信业务余额不足';
                    break;

                case 'isv.BUSINESS_LIMIT_CONTROL':
                    $r = '请勿重复操作';
                    break;

                default:
                    $r = "短信次数超过限制";
                    break;
            }
        }
        return Responses::arrays($r);
    }

    /**
     * 重写模板
     * @param $phone
     * @param $sale
     * @param $type
     * @return string
     */
    public function template($phone, $sale, $type)
    {
        $content = $sale;
        return $content;
    }

    /**
     * 发送短信验证码
     *
     * @param $phone
     * @param string $sale  验证码
     * @param $type  1:注册  2;找回密码 3:重置密码
     * @return array
     */
    public function userMessage($phone, $sale, $type)
    {
        switch ($type){
            case 1:
                $templateCode = "*********";
                break;

            case 2:
                $templateCode = "*********";
                break;
            case 3:
                $templateCode = "*********";
                break;
            case 4:
                $templateCode = "*********";
                break;

            default:
                return $this->response('类型溢出');
                break;
        }

        $content = $this->template($phone, $sale, $type);
        return $this->sendSms($phone, ['code' => $content],$templateCode);
    }
}

转载时请注明出处及相应链接,本文永久地址:https://blog.yayuanzi.com/23060.html


pay_weixin
pay_weixin
微信打赏
pay_weixin
支付宝打赏
感谢您对作者Alex的打赏,我们会更加努力!    如果您想成为作者,请点我

发表我的评论
取消评论

表情