php 阿里短信接口部署

composer 安装三方类:composer require alibabacloud/client

发送短信类

<?php
namespace app\common\controller;

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

class SendSms extends Controller {

    static private $accessKeyId = "****************";
    static private  $accessSecret = "*****************";
    static private  $signName = "*****服务信息平台";
   // 优先加载
   public function  _initialize() {

   }

    static function  send_sms($mobile,$code,$template){
        $accessKeyId = self::$accessKeyId;
        $accessSecret = self::$accessSecret;
        $signName = self::$signName;
        AlibabaCloud::accessKeyClient($accessKeyId, $accessSecret)
            ->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' => $mobile,
                        'SignName' => $signName,
                        'TemplateCode' => $template,
                        'TemplateParam' => $code,
                    ],
                ])
                ->request();
            print_r($result->toArray());
        } catch (ClientException $e) {
            echo $e->getErrorMessage() . PHP_EOL;
        } catch (ServerException $e) {
            echo $e->getErrorMessage() . PHP_EOL;
        }
    }
}

发送短信函数

    /**
     * 发送 登录 验证码
     * @return [type] [description]
     */
    public function sendLogin(){
        $post = $this->request->param();
        $validate = new \think\Validate([
            ['phone', 'require|/^1[3-8]{1}[0-9]{9}$/', '手机号不能为空|手机号格式不正确'],
        ]);
        if (!$validate->check($post)) {
            return $this->error('发送失败:' . $validate->getError());
        }
        $mobile = $post['phone'];
        $template = "SMS_195580724";

        $code['code']  = mt_rand(000000,999999);
        $aa = $code['code'];
        Session::set("code",$code['code']);
        $return = SendSms::send_sms($mobile,json_encode($code),$template);
        return $return;
    }

测试用例

use app\common\controller\SendSms;
function sendLogin(){
    $mobile = "150888888888";
    $template = "SMS_195580724";

    $code['code']  = mt_rand(000000,999999);
    $return = SendSms::send_sms($mobile,json_encode($code),$template);
    return $return;
}

 

2020-08-08

posted @ 2020-08-08 23:41  孤陌  阅读(298)  评论(0编辑  收藏  举报