2023-01-29 10:26:52 +08:00

104 lines
3.2 KiB
PHP

<?php
class Alisms
{
private $bucket = null;
private $conf = array(
'host' => 'dysmsapi.aliyuncs.com',
'format' => 'JSON',
'version' => '2017-05-25',
'signatureVersion' => '1.0',
'signatureMethod' => 'HMAC-SHA1',
'accessKeyId' => null,
'accessKeySecret' => null,
'signName' => null,
'templateCode' => null,
);
public function __construct($conf)
{
$this->setConf($conf);
}
public function setConf($conf)
{
$this->conf = array_merge($this->conf, $conf);
return true;
}
/**
* 发送验证码
*
* @example shell curl -d 'Action=SingleSendSms
&SignName=阿里云短信服务
&TemplateCode=SMS_1595010
&RecNum=13011112222
&ParamString={"no":"123456"}
&<公共请求参数>' 'https://sms.aliyuncs.com/'
* @return boolean
*/
public function singleSendSms($mobile, $params, $template = null, $sign = null)
{
$data = [
'Action' => 'SendSms',
'SignName' => empty($sign) ? $this->conf['signName'] : $sign,
'TemplateCode' => empty($template) ? $this->conf['templateCode'] : $template,
'PhoneNumbers' => is_array($mobile) ? implode(',', $mobile) : $mobile,
'TemplateParam' => json_encode($params),
];
if (empty($data['SignName']) || empty($data['TemplateCode'])) {
return false;
}
$tmp = $this->mergePublicParams($data);
$tmp['Signature'] = $this->sign('GET', $tmp);
$url = 'https://'.$this->conf['host'].'/?' . http_build_query ( $tmp );
$ch = curl_init ();
curl_setopt ( $ch, CURLOPT_URL, $url );
curl_setopt ( $ch, CURLOPT_SSL_VERIFYPEER, FALSE );
curl_setopt ( $ch, CURLOPT_SSL_VERIFYHOST, FALSE );
curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt ( $ch, CURLOPT_TIMEOUT, 10 );
$result = curl_exec ( $ch );
curl_close ( $ch );
$result = json_decode ( $result, true );
if ($result['Message'] == 'OK') {
return ['code'=>0,'message'=>'发送成功'];
}else{
return ['code'=>1,'message'=>$result['Message']];
}
}
/**
* 合并“公共请求参数”
*
* @link https://help.aliyun.com/document_detail/44362.html
*/
private function mergePublicParams($data)
{
$default = [
'Format' => $this->conf['format'],
'Version' => $this->conf['version'],
'SignatureVersion' => $this->conf['signatureVersion'],
'SignatureMethod' => $this->conf['signatureMethod'],
'AccessKeyId' => $this->conf['accessKeyId'],
'Timestamp' => gmDate("Y-m-d\TH:i:s\Z"),
'SignatureNonce' => uniqid('', true),
];
return array_merge($default,$data);
}
/**
* 签名
*
* @link https://help.aliyun.com/document_detail/44363.html
*/
private function sign($httpMethod, $data)
{
ksort($data);
$q = http_build_query($data);
return base64_encode(hash_hmac('sha1', $httpMethod . '&%2F&' . rawurlencode($q), $this->conf['accessKeySecret'] . '&', true));
}
}
?>