#阿里云免sdk发送短信代码
该文本提供了一个使用阿里云短信服务的PHP类示例,包含发送短信的功能。类中定义了构造函数、发送短信方法、生成签名、URL编码、生成随机字符串和发送HTTPGET请求的方法。示例展示了如何使用该类发送短信,并处理可能的异常和错误信息。
<?php
class AliyunSms
{
private $accessKeyId;
private $accessKeySecret;
private $signName;
private $templateCode;
private $endpoint = "https://dysmsapi.aliyuncs.com/";
private $apiVersion = "2017-05-25";
private $regionId = "cn-hangzhou";
/**
* 构造函数
*
* @param string $accessKeyId
* @param string $accessKeySecret
* @param string $signName
* @param string $templateCode
*/
public function __construct($accessKeyId, $accessKeySecret, $signName, $templateCode)
{
$this->accessKeyId = $accessKeyId;
$this->accessKeySecret = $accessKeySecret;
$this->signName = $signName;
$this->templateCode = $templateCode;
}
public static function sendSms2($phoneNumber, $templateParam = [])
{
$sms = new self();
return $sms->sendSms($phoneNumber, $templateParam);
}
/**
* 发送短信
*
* @param string $phoneNumber 接收短信的手机号码
* @param array $templateParam 短信模板变量对应的实际值,JSON格式
* @return array API 返回结果
* @throws Exception
*/
public function sendSms($phoneNumber, $templateParam = [])
{
$params = [
"Action" => "SendSms",
"Version" => $this->apiVersion,
"RegionId" => $this->regionId,
"PhoneNumbers" => $phoneNumber,
"SignName" => $this->signName,
"TemplateCode" => $this->templateCode,
"TemplateParam" => json_encode($templateParam, JSON_UNESCAPED_UNICODE),
"Format" => "JSON",
"AccessKeyId" => $this->accessKeyId,
"SignatureMethod" => "HMAC-SHA1",
"SignatureVersion" => "1.0",
"SignatureNonce" => $this->generateNonce(),
"Timestamp" => gmdate("Y-m-d\TH:i:s\Z"),
];
// 生成签名
$signature = $this->generateSignature($params);
$params["Signature"] = $signature;
// 构建请求 URL
$url = $this->endpoint . "?" . http_build_query($params);
// 发送请求
$response = $this->httpGet($url);
// 解析响应
$result = json_decode($response, true);
if (!$result) {
throw new Exception("无法解析API响应");
}
return $result;
}
/**
* 生成签名
*
* @param array $params
* @return string
*/
private function generateSignature($params)
{
// 步骤 1:按照字典序排序参数
ksort($params);
// 步骤 2:构造规范化的查询字符串
$canonicalizedQueryString = '';
foreach ($params as $key => $value) {
$canonicalizedQueryString .= "&" . $this->percentEncode($key) . "=" . $this->percentEncode($value);
}
$canonicalizedQueryString = ltrim($canonicalizedQueryString, '&');
// 步骤 3:构造字符串待签名
$stringToSign = "GET&%2F&" . $this->percentEncode($canonicalizedQueryString);
// 步骤 4:计算签名
$signingKey = $this->accessKeySecret . "&";
$signature = base64_encode(hash_hmac('sha1', $stringToSign, $signingKey, true));
return $signature;
}
/**
* URL编码(符合RFC 3986)
*
* @param string $str
* @return string
*/
private function percentEncode($str)
{
$res = urlencode($str);
$res = preg_replace('/\+/', '%20', $res);
$res = preg_replace('/\*/', '%2A', $res);
$res = preg_replace('/%7E/', '~', $res);
return $res;
}
/**
* 生成随机字符串(UUID)
*
* @return string
*/
private function generateNonce()
{
return uniqid(mt_rand(0, mt_getrandmax()), true);
}
/**
* 发送 HTTP GET 请求
*
* @param string $url
* @return string
* @throws Exception
*/
private function httpGet($url)
{
$ch = curl_init();
// 设置选项
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
// 执行请求
$response = curl_exec($ch);
// 错误处理
if ($response === false) {
$error = curl_error($ch);
curl_close($ch);
throw new Exception("CURL Error: " . $error);
}
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($httpCode != 200) {
throw new Exception("HTTP Error Code: " . $httpCode);
}
return $response;
}
}
// 使用示例
try {
// 替换为您的实际参数
$accessKeyId = "您的AccessKeyId";
$accessKeySecret = "您的AccessKeySecret";
$signName = "您的短信签名";
$templateCode = "您的模板CODE";
$sms = new AliyunSms($accessKeyId, $accessKeySecret, $signName, $templateCode);
$phoneNumber = "15980037210"; // 接收短信的手机号码
$templateParam = [
"code" => "123456" // 模板中的变量
];
$result = $sms->sendSms($phoneNumber, $templateParam);
if (isset($result['Code']) && $result['Code'] === 'OK') {
echo "短信发送成功!";
} else {
echo "短信发送失败,错误信息:" . $result['Message'];
}
} catch (Exception $e) {
echo "发生异常:" . $e->getMessage();
}