美文网首页
laravel整合阿里云短信

laravel整合阿里云短信

作者: BK_90dc | 来源:发表于2021-08-23 16:46 被阅读0次

安装依赖

composer require alibabacloud/sdk

编写服务类

我的服务类文件都是在App\Service 目录下的,其他的需要修改namespace

<?php

namespace App\Service;

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

class AliSmsService
{
    protected $key = '';
    protected $secret = '';
    protected $sign_name = '';
    protected $template_code = '';

    public function   __construct()
    {
        $this->key = '';
        $this->secret = '';
        $this->sign_name = '';
        $this->template_code = '';
    }

    function send_sms($phone, $code)
    {
        AlibabaCloud::accessKeyClient($this->key, $this->secret)
            ->regionId('cn-qingdao')
            ->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' => [
                        'PhoneNumbers' => $phone,
                        'SignName' => $this->sign_name,
                        'TemplateCode' => $this->template_code,
                        'TemplateParam' => json_encode(['code' => $code]),
                    ],
                ])
                ->request();
            $res = $result->toArray();
            if ($res['Code'] == 'OK') {
                return true;
            }
            return false;
        } catch (ClientException $e) {
            echo $e->getErrorMessage() . PHP_EOL;
            return false;
        } catch (ServerException $e) {
            echo $e->getErrorMessage() . PHP_EOL;
            return false;
        }
    }
}

快速体验

  $service = new AliSmsService();
  $service->send_sms('手机号','验证码');

相关文章

网友评论

      本文标题:laravel整合阿里云短信

      本文链接:https://www.haomeiwen.com/subject/lujliltx.html