阿里大于短信发送简洁封装
<?php
namespace app\common\lib;
use think\Config;
use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;
class AliSms
{
//API协议版本
private $version = "2017-05-25";
//API 秘钥id
private $accessKeyId;
//API 秘钥
private $accessSecret;
public function __construct()
{
$this->accessKeyId(Config::get("sms.appkey"));
$this->accessSecret(Config::get("sms.secretKey"));
$this->version("2017-05-25");
AlibabaCloud::accessKeyClient($this->accessKeyId, $this->accessSecret)
->regionId('cn-hangzhou')
->asDefaultClient();
}
//发短信
public function sendSms($phone, $signName, $templateCode, $templateParam = array())
{
//模板参数
if (!empty($templateParam)) {
$templateParam = json_encode($templateParam, 256);
}
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' => $phone,
'SignName' => $signName,
'TemplateCode' => $templateCode,
'TemplateParam' => $templateParam,
],
])
->request();
return $result->toArray();
} catch (ClientException $e) {
echo $e->getErrorMessage() . PHP_EOL;
} catch (ServerException $e) {
echo $e->getErrorMessage() . PHP_EOL;
}
}
//批量多条短信
public function sendBatchSms($phoneNumberJson = array(), $signNameJson = array(), $templateCode = array())
{
//手机号
if (!empty($phoneNumberJson)) {
$phoneNumberJson = json_encode($phoneNumberJson);
}
//必须是已添加、并通过审核的短信签名;且短信签名的个数必须与手机号码的个数相同、内容一一对应
if (!empty($signNameJson)) {
$signNameJson = json_encode($signNameJson);
}
//短信模板变量对应的实际值,JSON格式
if (!empty($templateCode)) {
$templateCode = json_encode($templateCode);
}
try {
$result = AlibabaCloud::rpc()
->product('Dysmsapi')
// ->scheme('https') // https | http
->version($this->version)
->action('SendBatchSms')
->method('POST')
->host('dysmsapi.aliyuncs.com')
->options([
'query' => [
'RegionId' => "cn-hangzhou",
'PhoneNumberJson' => $phoneNumberJson,
'SignNameJson' => $signNameJson,
'TemplateCode' => $templateCode,
],
])
->request();
return $result->toArray();
} catch (ClientException $e) {
echo $e->getErrorMessage() . PHP_EOL;
} catch (ServerException $e) {
echo $e->getErrorMessage() . PHP_EOL;
}
}
//版本
public function version($version = "")
{
if ($version) $this->version = $version;
return $this;
}
//秘钥id
public function accessKeyId($accessKeyId = "")
{
if ($accessKeyId) $this->accessKeyId = $accessKeyId;
return $this;
}
//秘钥
public function accessSecret($accessSecret = "")
{
if ($accessSecret) $this->accessSecret = $accessSecret;
return $this;
}
}
阿里大于短信发送简洁封装
最新推荐文章于 2022-08-22 20:06:08 发布