今天是对接阿里云短信的案例
先用composer
安装插件包
composer require alibabacloud/client
简单封装一下
<?php
namespace app\tools;
use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;
class Alisms
{
//配置
protected $config = [];
public function __construct($config)
{
$this->config = $config;
}
/**
* 发送
* @param string $phone 接收短信的手机号码
* @param string $content 短信内容(json)
* @return array
* @throws ClientException
*/
public function send($template, $phone = '', $content = '')
{
AlibabaCloud::accessKeyClient($this->config['AccessKeyId'], $this->config['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' => [
'PhoneNumbers' => $phone,
'SignName' => $this->config['SignName'],
'TemplateCode' => $template,
'TemplateParam' => $content,
'RegionId' => $this->config['RegionId'],
],
])
->request();
if ($result['Code'] == 'OK' || $result['Message'] == 'ok') {
return ['code' => 0, 'msg'=>'发送成功'];
} else {
return ['code' => 4003, 'msg'=>$result['Message']];
}
} catch (ClientException $e) {
return ['code' => 500, 'msg'=>$e->getErrorMessage()];
} catch (ServerException $e) {
return ['code' => 500, 'msg'=>$e->getErrorMessage()];
}
}
}
调用
//配置
$config = [
'AccessKeyId' => '',
'accessSecret' => '',
'SignName' => '',
'RegionId' => ''
];
//生成验证码
$auth_code = rand(1000,9999);
//短信模板
$template = '';
//发送内容,要根据实际的模板内容(验证码)
$content = json_encode(['code'=>$auth_code]);
$sms = new Alisms($config);
$result = $sms->send($template, $phone, $content);
if ($result['code'] != 0) {
return api_json_return(500, '发送短信失败,请联系管理员');
}
return api_json_return(0, '发送成功');