ThinkPHP使用阿里云短信服务发送验证码

www.jswusn.com PHP 2019-12-12 21:14:26 3047次浏览

  最近苏州网站建设在帮客户在阿里云平台申请短信签名的时候,无意中发现,最近阿里云短信的接口已经更新了,所以,在新的项目中果断使用了官方最新的SDK(阿里云文档地址:https://help.aliyun.com/document_detail/112186.html?spm=a2c4g.11186623.6.649.157c50a43osCqL


  以下是使用方法:

{pboot:pre}

use AlibabaCloudClientAlibabaCloud;
use AlibabaCloudClientExceptionClientException;
use AlibabaCloudClientExceptionServerException;
use ThinkLog;

class sendSms
{
    function sendAliDaYuAuthCode($phoneNumber ='')
    {
        $AccessKeyId=C('AccessKeyId');
        $AccessKeySecret=C('AccessKeySecret');
        $signName=C('signName');  // 短信签名
        $templateCode=C('templateCode');  // 短信模板编号

        //TODO 随机生成一个6位数
        $authCodeMT = mt_rand(100000,999999);
        //TODO 短信模板变量替换JSON串,友情提示:如果JSON中需要带换行符,请参照标准的JSON协议。
        $jsonTemplateParam = json_encode(['code'=>$authCodeMT]);

        AlibabaCloud::accessKeyClient($AccessKeyId, $AccessKeySecret)
            ->regionId('cn-hangzhou')
            ->asDefaultClient();

        try {
            $result = AlibabaCloud::rpc()
                ->product('Dysmsapi')
//                ->scheme('https') // https | http
                ->version('2017-05-25')
                ->action('SendSms')
                ->method('POST')
                ->host('dysmsapi.aliyuncs.com')
                ->options([
                    'query' => [
                        'RegionId' => "cn-hangzhou",
                        'PhoneNumbers' => $phoneNumber,
                        'SignName' => $signName,
                        'TemplateCode' => $templateCode,
                        'TemplateParam' => $jsonTemplateParam,
                    ],
                ])
                ->request();

            if($result->Code=='OK'){
                return array('mobile'=>$phoneNumber,'sms_code'=>$authCodeMT,'sms_time'=>NOW_TIME);
            }else{
                $this->error=$result->Code;
                Log::write($result->Code);    //发送失败记录日志
                return 0;
            }

        } catch (ClientException $e) {
            Log::write($e->getErrorMessage());    //发送失败记录日志
            return 0;
        } catch (ServerException $e) {
            Log::write($e->getErrorMessage());    //发送失败记录日志
            return 0;
        }
    }

{/pboot:pre}


  阿里云Demo:https://api.aliyun.com/?spm=a2c4g.11186623.2.17.300e50a4FsKemz#/?product=Dysmsapi&lang=PHP


技术分享

苏南名片

  • 电话:152-1887-1916
  • 邮箱:message@jswusn.com
  • 地址:江苏省苏州市相城区

热门文章

Copyright © 2018-2024 jswusn.com 版权所有

技术支持:苏州网站建设  苏ICP备18036849号