20,359
社区成员
发帖
与我相关
我的任务
分享
<?php
include_once 'aliyun-php-sdk-core/Config.php';
use Sms\Request\V20160927 as Sms;
class SendSms
{
/**
*这个类可以通过阿里云发送短信,然后返回验证码
*/
public static function sendVerSmsByPhone($phone)
{
// 注册验证
$iClientProfile = DefaultProfile::getProfile("cn-hangzhou", "L***********tcY", "vfFo*************e6y");
$client = new DefaultAcsClient($iClientProfile);
$request = new Sms\SingleSendSmsRequest();
$request->setSignName("华予");/*签名名称*/
$request->setTemplateCode("SMS_1*****5723"); /*模板code*/
$request->setRecNum($phone);/*目标手机号*/
$vernumber = rand(100000,999999);
$request->setParamString("{\"number\":\"$vernumber\"}");/*模板变量,数字一定要转换为字符串*/
try {
$response = $client->getAcsResponse($request);
return $vernumber;
}
catch (ClientException $e) {
throw new \Exception($e->getErrorMessage());
return array('ClientErrorCode' => $e->getErrorCode(),'ClientErrorMes' => $e->getErrorMessage());
}
catch (ServerException $e) {
throw new \Exception($e->getErrorMessage());
return array('ServerErrorCode' => $e->getErrorCode(),'ServerErrorMes' => $e->getErrorMessage());
}
}
}
?>
发送时使用方式
$number = \SendSms::sendVerSmsByPhone($phone);
if(!is_int($number)){
throw new \root\logic\exception\AppException('验证码发送错误');
}
"<?xml version="1.0" encoding="utf-8"?>
<Message xmlns="http://mns.aliyuncs.com/doc/v1/">
<MessageBody>content</MessageBody>
<MessageAttributes>
<DirectSMS>
{"FreeSignName":"绍兴楼市网","TemplateCode":"SMS_71350099","Type":"singleContent","Receiver":"13754398382","SmsParams":"{\"code\":\"12312\",\"product\":\"普通会员\"}"}
</DirectSMS>
</MessageAttributes>
</Message>
我收到正确的反馈,但是我真的收不到短信。
<%@LANGUAGE="JAVASCRIPT" CODEPAGE="65001"%>
<script language="javascript" type="text/javascript" runat="server">
Response.Buffer=true;
Response.Charset="utf-8";
///这段是我网上找来的base64_hmac_sha1函数
function b64_hmac_sha1(key,data){return binb2b64(core_hmac_sha1(key,data));}
function core_sha1(x,len){x[len>>5]|=0x80<<(24-len%32);x[((len+64>>9)<<4)+15]=len;var w=Array(80);var a= 1732584193;var b=-271733879;var c=-1732584194;var d= 271733878;var e=-1009589776;for(var i=0;i<x.length;i += 16){var olda=a;var oldb=b;var oldc=c;var oldd=d;var olde=e;for(var j=0;j<80;j++){if(j<16)w[j]=x[i+j];else w[j]=rol(w[j-3]^w[j-8]^w[j-14]^w[j-16],1);var t=safe_add(safe_add(rol(a,5),sha1_ft(j,b,c,d)),safe_add(safe_add(e,w[j]),sha1_kt(j)));e=d;d=c;c=rol(b,30);b=a;a=t;}a=safe_add(a,olda);b=safe_add(b,oldb);c=safe_add(c,oldc);d=safe_add(d,oldd);e=safe_add(e,olde);}return Array(a,b,c,d,e);}
function sha1_ft(t,b,c,d){if(t<20)return (b&c)|((~b)&d);if(t<40)return b^c^d;if(t<60)return (b&c)|(b&d)|(c&d);return b^c^d;}
function sha1_kt(t){return (t<20)?1518500249:(t<40)?1859775393:(t<60)?-1894007588:-899497514;}
function core_hmac_sha1(key,data){var bkey=str2binb(key);if(bkey.length>16)bkey=core_sha1(bkey,key.length*8);var ipad=Array(16),opad=Array(16);for(var i=0;i<16;i++){ipad[i]=bkey[i]^0x36363636;opad[i]=bkey[i]^0x5C5C5C5C;}var hash=core_sha1(ipad.concat(str2binb(data)),512+data.length*8);return core_sha1(opad.concat(hash),512+160);}
function safe_add(x,y){var lsw=(x&0xFFFF)+(y&0xFFFF);var msw=(x>>16)+(y>>16)+(lsw>>16);return(msw<<16)|(lsw&0xFFFF);}
function rol(num,cnt){return(num<<cnt)|(num>>>(32-cnt));}
function str2binb(str){var bin=Array();var mask=(1<<8)-1;for(var i=0;i<str.length*8;i+=8)bin[i>>5]|=(str.charCodeAt(i/8)&mask)<<(32-8-i%32);return bin;}
function binb2b64(binarray){var tab="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";var str="";for(var i=0;i<binarray.length*4;i+=3){var triplet=(((binarray[i>>2]>>8*(3-i%4))&0xFF)<<16)|(((binarray[i+1>>2]>>8*(3-(i+1)%4))&0xFF)<<8)|((binarray[i+2>>2]>>8*(3-(i+2)%4))&0xFF);for(var j=0;j<4;j++){if(i*8+j*6>binarray.length*32)str+="=";else str+=tab.charAt((triplet>>6*(3-j))&0x3F);}}return str;}
///base64_hmac_sha1函数到此为止。
function DateTimetoGMT(){var sDate=new Date().toGMTString();return sDate.replace(/(\b)(\d)/g,'$10$2').replace(/(\b)0(\d\d)/g,'$1$2').replace('UTC','GMT');}
// 上面是GMT日期格式化函数。我发现API要求月、日、时、分、秒都用两位数字,但是new Date().toGMTString()生成的格式是以UTC为后缀的,而且有时候月、日、时、分、秒是一位数字,于是我用正则表达式替换,把缺少的0补足。
var AccessKeyId="LTAIkhHjZA2PjHk4";
var AccessKey="CHOHRocxig0gbiUEc4e38sMAchhtfU";
//var HostUrl="http:\/\/1700197362735697.mns.cn-hangzhou.aliyuncs.com";
var HostUrl="http:\/\/1700197362735697.mns.cn-hangzhou-internal-vpc.aliyuncs.com";
var PathUrl="\/topics\/sms.topic-cn-hangzhou\/messages";
var nowtime=DateTimetoGMT();
//Response.write(nowtime);
//Response.write("<br>");
var signature="POST\n\ntext/xml\n"+nowtime+"\nx-mns-version:2015-06-06\n"+PathUrl;
//Response.write(signature+"<br />");
signature=b64_hmac_sha1(AccessKey,signature);
//Response.write(signature);
//Response.end();
var myhttp=Server.CreateObject("Msxml2.XMLHTTP.6.0")
myhttp.open("POST",HostUrl+PathUrl);
myhttp.setRequestHeader("Authorization","MNS "+AccessKeyId+":"+signature);
myhttp.setRequestHeader("Content-Type","text/xml");
myhttp.setRequestHeader("Date",nowtime);
myhttp.setRequestHeader("Host",HostUrl);
myhttp.setRequestHeader("x-mns-version","2015-06-06");
var mydata=Server.CreateObject("Msxml2.DOMDocument.6.0");
var data="\"FreeSignName\":\"绍兴楼市网\",\"TemplateCode\":\"SMS_71350095\",";
data+="\"Type\":\"singleContent\",\"Receiver\":\"13754398382\",";
data+="\"SmsParams\":\"{\\\"code\\\":\\\"12312\\\",\\\"product\\\":\\\"普通会员\\\"}\"";
mydata.loadXML("<?xml version=\"1.0\" encoding=\"utf-8\"?><Message xmlns=\"http:\/\/mns.aliyuncs.com\/doc\/v1\/\"><MessageBody>content<\/MessageBody><MessageAttributes><DirectSMS>{"+data+"}<\/DirectSMS><\/MessageAttributes><\/Message>");
Response.contentType="text/xml";
//Response.write("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
//Response.write(mydata.documentElement.xml);
//Response.End();
myhttp.send(mydata);
mydata=null;
Response.write(myhttp.responseXML.xml);
myhttp=null;
</script>
我收到了这样的反馈:
<?xml version="1.0"?>
<Message xmlns="http://mns.aliyuncs.com/doc/v1">
<MessageBodyMD5>9A0364B9E99BB480DD25E1F0284C8555</MessageBodyMD5>
<MessageId>D977997CABB26596-2-15DB1A96D0B-200000005</MessageId>
</Message>
看起来是不错的反馈,但是我真的没收到什么短信啊。
求懂的行家帮我看看到底问题出在哪里啊。
SMS_71350095短信模板的内容如下:
模板名称:用户注册验证码
模板CODE:SMS_71350095
短信内容:验证码${code},您正在注册成为${product}用户,感谢您的支持!/**
* 阿里云 短信验证
* @param $phone 手机号码
* @param null $mobile_code 验证码
* @param null $template_code 短信模版
*/
public function phoneCode($phone,$mobile_code=null,$template_code=null){
if (!$mobile_code){$mobile_code = $this->random(6,1);}
if(!$template_code){$template_code='SMS_37650042';}
$target = "https://sms.aliyuncs.com/?";
// 注意使用GMT时间
date_default_timezone_set("GMT");
$dateTimeFormat = 'Y-m-d\TH:i:s\Z'; // ISO8601规范
$accessKeyId = 'LTAIGsgBVt8MDTyf'; // 这里填写您的Access Key ID
$accessKeySecret = '5koNqwSpKi0SfjfyHUWqF0lCLIwuoS'; // 这里填写您的Access Key Secret
$ParamString="{\"code\":\"".strval($mobile_code)."\",\"time\":\"15\"}";
$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' => $template_code,
'RecNum' => $phone,
'ParamString' => $ParamString
);
// 计算签名并把签名结果加入请求参数
//echo $data['Version']."<br>";
//echo $data['Timestamp']."<br>";
$data['Signature'] = $this->computeSignature($data, $accessKeySecret);
// 发送请求
$result = $this->xml_to_array($this->https_request($target.http_build_query($data)));
print_r($result);
}
public function https_request($url)
{
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$data = curl_exec($curl);
if (curl_errno($curl)) {return 'ERROR '.curl_error($curl);}
curl_close($curl);
return $data;
}
public function xml_to_array($xml){
$reg = "/<(\w+)[^>]*>([\\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] = $this->xml_to_array( $subxml );
}else{
$arr[$key] = $subxml;
}
}
}
return @$arr;
}
public 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';*/
$chars = '0123456789';
$max = strlen($chars) - 1;
for($i = 0; $i < $length; $i++) {
$hash .= $chars[mt_rand(0, $max)];
}
}
return $hash;
}
public 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;
}
public function computeSignature($parameters, $accessKeySecret)
{
// 将参数Key按字典顺序排序
ksort($parameters);
// 生成规范化请求字符串
$canonicalizedQueryString = '';
foreach($parameters as $key => $value)
{
$canonicalizedQueryString .= '&' . $this->percentEncode($key)
. '=' . $this->percentEncode($value);
}
// 生成用于计算签名的字符串 stringToSign
$stringToSign = 'GET&%2F&' . $this->percentencode(substr($canonicalizedQueryString, 1));
//echo "<br>".$stringToSign."<br>";
// 计算签名,注意accessKeySecret后面要加上字符'&'
$signature = base64_encode(hash_hmac('sha1', $stringToSign, $accessKeySecret . '&', true));
return $signature;
}
[/quote
短信模板内容对应好久OK了,谢谢分享/**
* 阿里云 短信验证
* @param $phone 手机号码
* @param null $mobile_code 验证码
* @param null $template_code 短信模版
*/
public function phoneCode($phone,$mobile_code=null,$template_code=null){
if (!$mobile_code){$mobile_code = $this->random(6,1);}
if(!$template_code){$template_code='SMS_37650042';}
$target = "https://sms.aliyuncs.com/?";
// 注意使用GMT时间
date_default_timezone_set("GMT");
$dateTimeFormat = 'Y-m-d\TH:i:s\Z'; // ISO8601规范
$accessKeyId = 'LTAIGsgBVt8MDTyf'; // 这里填写您的Access Key ID
$accessKeySecret = '5koNqwSpKi0SfjfyHUWqF0lCLIwuoS'; // 这里填写您的Access Key Secret
$ParamString="{\"code\":\"".strval($mobile_code)."\",\"time\":\"15\"}";
$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' => $template_code,
'RecNum' => $phone,
'ParamString' => $ParamString
);
// 计算签名并把签名结果加入请求参数
//echo $data['Version']."<br>";
//echo $data['Timestamp']."<br>";
$data['Signature'] = $this->computeSignature($data, $accessKeySecret);
// 发送请求
$result = $this->xml_to_array($this->https_request($target.http_build_query($data)));
print_r($result);
}
public function https_request($url)
{
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$data = curl_exec($curl);
if (curl_errno($curl)) {return 'ERROR '.curl_error($curl);}
curl_close($curl);
return $data;
}
public function xml_to_array($xml){
$reg = "/<(\w+)[^>]*>([\\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] = $this->xml_to_array( $subxml );
}else{
$arr[$key] = $subxml;
}
}
}
return @$arr;
}
public 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';*/
$chars = '0123456789';
$max = strlen($chars) - 1;
for($i = 0; $i < $length; $i++) {
$hash .= $chars[mt_rand(0, $max)];
}
}
return $hash;
}
public 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;
}
public function computeSignature($parameters, $accessKeySecret)
{
// 将参数Key按字典顺序排序
ksort($parameters);
// 生成规范化请求字符串
$canonicalizedQueryString = '';
foreach($parameters as $key => $value)
{
$canonicalizedQueryString .= '&' . $this->percentEncode($key)
. '=' . $this->percentEncode($value);
}
// 生成用于计算签名的字符串 stringToSign
$stringToSign = 'GET&%2F&' . $this->percentencode(substr($canonicalizedQueryString, 1));
//echo "<br>".$stringToSign."<br>";
// 计算签名,注意accessKeySecret后面要加上字符'&'
$signature = base64_encode(hash_hmac('sha1', $stringToSign, $accessKeySecret . '&', true));
return $signature;
}
function SendSMS($recNum,$param,$signName,$templateCode,$appkey,$secret)
{//项目长度限制15位
$url='http://gw.api.taobao.com/router/rest?';
$urlparams['app_key']=$appkey;
$urlparams['format']='xml';
$urlparams['method']='alibaba.aliqin.fc.sms.num.send';
$urlparams['sign_method']='md5';
$urlparams['timestamp']=date("Y-m-d H:i:s");
$urlparams['v']='2.0';
foreach ($urlparams as $k => $v) $url.=$k.'='.urlencode($v).'&';
$postparams['rec_num']=$recNum;
$postparams['sms_free_sign_name']=$signName;
$postparams['sms_param']=$param;
$postparams['sms_template_code']=$templateCode;
$postparams['sms_type']='normal';
$params=array_merge($urlparams,$postparams);
ksort($params);
$signstr=$secret;
foreach ($params as $k => $v) $signstr.=$k.$v;
exit($signstr.$secret);####<<<<<<<<-----------------------------
$signstr=strtoupper(md5($signstr.$secret));
$url.='sign='.$signstr;
$HTTP=curl_init($url);
curl_setopt($HTTP, CURLOPT_POST, 1);
curl_setopt($HTTP, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($HTTP, CURLOPT_POSTFIELDS,$postparams);
$result=curl_exec($HTTP);
curl_close($HTTP);
$result=@simplexml_load_string($result);
return !isset($result->code);
}