<?php
date_default_timezone_set('GMT');
$phone = $_POST['phone'];//手机号
$code = rand(100000,999999);//六位随机数验证码
$signName = 'XXXX'; //短信签名(注意不是工单号)
$appid = ''; //AccessKeyId
$secret = ''; //AccessKeySecret
$tplid = 'SMS_XXXXXXXXX'; //模板id
$tplParam = json_encode(['code' => $code]);
$params = [
'AccessKeyId' => $appid, // appid
'Timestamp' => date('Y-m-d\TH:i:s\Z'), //时间
'SignatureMethod'=>'HMAC-SHA1', //固定值
'SignatureVersion'=> '1.0', //固定值
'SignatureNonce' => uniqid(), //随机码(这是PHP函数基于以微秒计的当前时间,生成一个唯一的ID)
//'Signature' => ''
'Format' => 'JSON', //返回的数据类型(如果不传官方说默认JSON经测试是XML)
//业务参数
'Action' => 'SendSms', //固定值不要更改
'Version' => '2017-05-25', //API的版本(固定值)
'RegionId' => 'cn-hangzhou', //API支持的RegionID(固定值)
'PhoneNumbers' => $phone, //接收号码
'SignName' => $signName, //签名
'TemplateCode' => $tplid, //模板id
'TemplateParam' => $tplParam, //短信模板变量替换JSON串,如$code
];
//排序
ksort($params);
//http_build_query($params)这个函数是只把值urlencode
//拼接字符串(键和值都需要urlencode)
$str = '';
foreach($params as $k => $v){
$str .= urlencode($k) . '=' . urlencode($v) . '&';
}
$str = substr($str,0,-1);//把最后一个'&'符号截取下去
$str = str_replace(['+','*','%7E'],['%20','%2A','~'],$str );//替换字符
$new_str = 'GET&' . urlencode('/') . '&' . urlencode($str);//拼接新字符串
$sign = base64_encode(hash_hmac('sha1', $new_str, $secret . '&',true));
$sign = urlencode($sign);//生成签名
$url = 'http://dysmsapi.aliyuncs.com/?Signature=' . $sign . '&'. $str;
//初始化
$ch = curl_init();
//设置选项,包括URL
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
//执行并获取HTML文档内容
$output = curl_exec($ch);
//释放curl句柄
curl_close($ch);
$ret = json_decode($output);
if($ret->Message == 'OK'){
//短信发送成功的逻辑
}
//打印获得的数据
echo $output;
?>