<?php
namespace App\Helper;
use App\Model\SmsSetting;
class Dysms
{
const URL = 'http://dysmsapi.aliyuncs.com/?';
const REGION_ID = 'cn-hangzhou';
public function send(SmsSetting $setting, string $phone, int $code)
{
$accessKeyId = $setting->aliyun_access_key_id;
$accessKeySecret = $setting->aliyun_access_secret;
$signName = $setting->aliyun_sign_name;
$templateCode = $setting->aliyun_template_id;
$params = array(
'Version' => '2017-05-25',
'Timestamp' => gmdate('Y-m-d\TH:i:s\Z'),
'SignatureVersion' => '1.0',
'SignatureNonce' => uniqid(),
'SignatureMethod' => 'HMAC-SHA1',
'Format' => 'JSON',
'RegionId' => self::REGION_ID,
'Action' => 'SendSms',
'AccessKeyId' => $accessKeyId,
'SignName' => $signName,
'TemplateCode' => $templateCode,
'PhoneNumbers' => $phone,
'TemplateParam' => sprintf('{"code":%s}', $code),
);
$params = $this->getSign($accessKeySecret, $params);
return $this->request($params);
}
public function request(array $params)
{
$url = self::URL . http_build_query($params);
$options = [
'headers' => [
'Content-type' => 'application/x-www-form-urlencoded',
],
];
try {
$result = make(Client::class)->request('GET', $url, [], $options)->getResult();
$code = $result['Code'] ?? null;
$message = $result['Message'] ?? null;
if ($code !== 'OK') {
Log::error(sprintf('阿里云短信发送失败[%s]:%s', $params['PhoneNumbers'], $message));
return false;
}
} catch (\Exception $exception) {
Log::error(sprintf('阿里云短信发送失败[%s]:%s', $params['PhoneNumbers'], $exception->getMessage()));
return false;
}
return true;
}
private function getSign(string $accessKeySecret, array $params)
{
ksort($params);
$canonicalizedQueryString = '';
foreach ($params as $key => $value) {
$canonicalizedQueryString .= '&' . $this->percentEncode($key) . '=' . $this->percentEncode($value);
}
$stringToSign = 'GET&%2F&' . $this->percentencode(substr($canonicalizedQueryString, 1));
$signature = base64_encode(hash_hmac('sha1', $stringToSign, $accessKeySecret . '&', true));
$params['Signature'] = $signature;
return $params;
}
private function percentEncode($string)
{
$string = urlencode($string);
$string = preg_replace('/\+/', '%20', $string);
$string = preg_replace('/\*/', '%2A', $string);
$string = preg_replace('/%7E/', '~', $string);
return $string;
}
}
Hyperf 阿里云短信
最新推荐文章于 2023-05-10 17:57:10 发布