laravel整合阿里云短信
2021-08-23 本文已影响0人
BK_90dc
安装依赖
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('手机号','验证码');