php发送阿里云短信代码
时间: 2023-08-18 20:05:05 浏览: 87
以下是使用 PHP 发送阿里云短信的示例代码:
```php
// 替换成你的 AccessKeyId 和 AccessKeySecret
$accessKeyId = "your_access_key_id";
$accessKeySecret = "your_access_key_secret";
// 签名和模板编号
$signName = "your_sign_name";
$templateCode = "your_template_code";
// 手机号码和验证码
$phoneNumbers = "18888888888";
$verifyCode = "123456";
// 构建请求参数
$params = array (
"code" => $verifyCode
);
// 发起请求
$helper = new SmsHelper($accessKeyId, $accessKeySecret);
$response = $helper->send($phoneNumbers, $signName, $templateCode, $params);
// 处理响应结果
if ($response->Code == 'OK') {
// 发送成功
} else {
// 发送失败
}
// SmsHelper 类定义
class SmsHelper {
private $accessKeyId;
private $accessKeySecret;
private $serverUrl = "http://dysmsapi.aliyuncs.com";
public function __construct($accessKeyId, $accessKeySecret) {
$this->accessKeyId = $accessKeyId;
$this->accessKeySecret = $accessKeySecret;
}
public function send($phoneNumbers, $signName, $templateCode, $params) {
$paramsJson = json_encode($params);
$paramsArray = array (
"PhoneNumbers" => $phoneNumbers,
"SignName" => $signName,
"TemplateCode" => $templateCode,
"TemplateParam" => $paramsJson,
"RegionId" => "cn-hangzhou",
"Action" => "SendSms",
"Version" => "2017-05-25"
);
$paramsString = http_build_query($paramsArray);
$signature = $this->computeSignature($paramsArray);
$url = "{$this->serverUrl}/?Signature={$signature}&{$paramsString}";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($ch);
curl_close($ch);
return json_decode($response);
}
private function computeSignature($params) {
ksort($params);
$canonicalQueryString = http_build_query($params);
$stringToSign = "GET&%2F&" . urlencode($canonicalQueryString);
$signature = base64_encode(hash_hmac("sha1", $stringToSign, $this->accessKeySecret . "&", true));
return urlencode($signature);
}
}
```
在上面的代码中,`SmsHelper` 类封装了发送短信的方法,其中 `send` 方法接受手机号码、签名、模板编号和消息参数作为参数,返回一个响应对象。你只需要将代码中的占位符替换成你自己的参数即可在你的应用程序中使用这个类发送短信。
阅读全文