最近公司短信到期了,我看到阿里云里面有个短信验证码服务,价格非常低,每条最高4分半,3秒可到,于是就申请了.
可是后面很难用,找不到例子代码,然后自己摸索,也咨询了阿里云的工作人员,花了2天才搞定,真不容易,记录下来,便于今后自己和其他人查阅.
]*>([\\x00-\\xFF]*)<\\/\\1>/";
if(preg_match_all($reg, $xml, $matches)){
$count = count($matches[0]);
for($i = 0; $i < $count; $i++){
$subxml= $matches[2][$i];
$key = $matches[1][$i];
if(preg_match( $reg, $subxml )){
$arr[$key] = xml_to_array( $subxml );
}else{
$arr[$key] = $subxml;
}
}
}
return @$arr;
}
function random($length = 6 , $numeric = 0) {
PHP_VERSION < '4.2.0' && mt_srand((double)microtime() * 1000000);
if($numeric) {
$hash = sprintf('%0'.$length.'d', mt_rand(0, pow(10, $length) - 1));
} else {
$hash = '';
$chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789abcdefghjkmnpqrstuvwxyz';
$max = strlen($chars) - 1;
for($i = 0; $i < $length; $i++) {
$hash .= $chars[mt_rand(0, $max)];
}
}
return $hash;
}
$target = "https://sms.aliyuncs.com/?";
$mobile_code = random(6,1);
if(empty($mobile)){
//exit('手机号码不能为空');
}
if(empty($_SESSION['send_code']) or $send_code!=$_SESSION['send_code']){
//防用户恶意请求
//exit('请求超时,请刷新页面后重试');
}
function percentEncode($str)
{
// 使用urlencode编码后,将"+","*","%7E"做替换即满足ECS API规定的编码规范
$res = urlencode($str);
$res = preg_replace('/\+/', '%20', $res);
$res = preg_replace('/\*/', '%2A', $res);
$res = preg_replace('/%7E/', '~', $res);
return $res;
}
function computeSignature($parameters, $accessKeySecret)
{
// 将参数Key按字典顺序排序
ksort($parameters);
// 生成规范化请求字符串
$canonicalizedQueryString = '';
foreach($parameters as $key => $value)
{
$canonicalizedQueryString .= '&' . percentEncode($key)
. '=' . percentEncode($value);
}
// 生成用于计算签名的字符串 stringToSign
$stringToSign = 'GET&%2F&' . percentencode(substr($canonicalizedQueryString, 1));
//echo "
".$stringToSign."
";
// 计算签名,注意accessKeySecret后面要加上字符'&'
$signature = base64_encode(hash_hmac('sha1', $stringToSign, $accessKeySecret . '&', true));
return $signature;
}
// 注意使用GMT时间
date_default_timezone_set("GMT");
$dateTimeFormat = 'Y-m-d\TH:i:s\Z'; // ISO8601规范
$accessKeyId = ''; // 这里填写您的Access Key ID
$accessKeySecret = ''; // 这里填写您的Access Key Secret
$ParamString="{\"code\":\"".strval($mobile_code)."\"}";
$data = array(
// 公共参数
'SignName'=>'交易禅',
'Format' => 'XML',
'Version' => '2016-09-27',
'AccessKeyId' => $accessKeyId,
'SignatureVersion' => '1.0',
'SignatureMethod' => 'HMAC-SHA1',
'SignatureNonce'=> uniqid(),
'Timestamp' => date($dateTimeFormat),
// 接口参数
'Action' => 'SingleSendSms',
'TemplateCode' => 'SMS_24805217',
'RecNum' => '13886355784',
'ParamString' => $ParamString
);
// 计算签名并把签名结果加入请求参数
//echo $data['Version']."
";
//echo $data['Timestamp']."
";
$data['Signature'] = computeSignature($data, $accessKeySecret);
// 发送请求
$result = xml_to_array(https_request($target.http_build_query($data)));
echo $result['Error']['Code']."--->".$result['Error']['Message'];
echo "
".$target . http_build_query($data);
?>