2018阿里云短信发送DEMO接入简单实例
以下更新2018-04-2309:57:54 后续不再更新,
基本类:
app/SignatureHelper.php
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<?php namespace aliyun_mns; /** * 签名助手 2017/11/19 * * Class SignatureHelper */ class SignatureHelper { /** * SignatureHelper constructor. */ public function __construct() { //.... } /** * 生成签名并发起请求 * * @param $accessKeyId string AccessKeyId (https://ak-console.aliyun.com/) * @param $accessKeySecret string AccessKeySecret * @param $domain string API接口所在域名 * @param $params array API具体参数 * @param $security boolean 使用https * @return bool|\stdClass 返回API接口调用结果,当发生错误时返回false */ public function request($accessKeyId, $accessKeySecret, $domain, $params, $security=false) { $apiParams = array_merge(array ( "SignatureMethod" => "HMAC-SHA1", "SignatureNonce" => uniqid(mt_rand(0,0xffff), true), "SignatureVersion" => "1.0", "AccessKeyId" => $accessKeyId, "Timestamp" => gmdate("Y-m-d\TH:i:s\Z"), "Format" => "JSON", ), $params); ksort($apiParams); ; $sortedQueryStringTmp = ""; foreach ($apiParams as $key => $value) {; $sortedQueryStringTmp .= "&" . $this->encode($key) . "=" . $this->encode($value); } $stringToSign = "GET&%2F&" . $this->encode(substr($sortedQueryStringTmp, 1)); $sign = base64_encode(hash_hmac("sha1", $stringToSign, $accessKeySecret . "&",true)); $signature = $this->encode($sign); $url = ($security ? 'https' : 'http')."://{$domain}/?Signature={$signature}{$sortedQueryStringTmp}"; try { $content = $this->fetchContent($url); return json_decode($content); } catch( \Exception $e) { return false; } } /** * @param $str * @return mixed|string */ private function encode($str) { $res = urlencode($str); $res = preg_replace("/\+/", "%20", $res); $res = preg_replace("/\*/", "%2A", $res); $res = preg_replace("/%7E/", "~", $res); return $res; } /** * @param $url * @return mixed */ private function fetchContent($url) { $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_TIMEOUT, 5); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_HTTPHEADER, array( "x-sdk-client" => "php/2.0.0" )); if(substr($url, 0,5) == 'https') { curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); } $rtn = curl_exec($ch); if($rtn === false) { trigger_error("[CURL_" . curl_errno($ch) . "]: " . curl_error($ch), E_USER_ERROR); } curl_close($ch); return $rtn; } }
app/querySendDetails.php
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<?php /* * 此文件用于验证短信服务API接口,供开发时参考 * 执行验证前请确保文件为utf-8编码,并替换相应参数为您自己的信息,并取消相关调用的注释 * 建议验证前先执行Test.php验证PHP环境 * * 2017/11/30 */ namespace aliyun_mns\app; use aliyun_mns\SignatureHelper; /** * Class querySendDetails * @package aliyun_mns\app */ class querySendDetails { public function __construct() { //.. } /** * @var array */ protected $config = []; /** * @param $name * @return mixed */ public function __get($name) { return $this->config[$name]; } protected $accessKeyId; protected $accessKeySecret; } /** * 短信发送记录查询 */ function querySendDetails() { $params = array (); // *** 需用户填写部分 *** // fixme 必填: 请参阅 https://ak-console.aliyun.com/ 取得您的AK信息 $accessKeyId = "LTAIFtsByAFF5ovd"; $accessKeySecret = "wGFc0xlA14cYgz1MtDVkSSOQ6japUH"; $test=[ 'PhoneNumber'=>'', // fixme 必填: 短信接收号码 'SendDate'=>'', // fixme 必填: 短信发送日期,格式Ymd,支持近30天记录查询 'PageSize'=>10, // fixme 必填: 分页大小 'CurrentPage'=>1, // fixme 必填: 当前页码 'BizId'=>'' // fixme 可选: 设置发送短信流水号 ]; $helper = new SignatureHelper(); // 此处可能会抛出异常,注意catch $content = $helper->request( $accessKeyId, $accessKeySecret, "dysmsapi.aliyuncs.com", array_merge($params, array( "RegionId" => "cn-hangzhou", "Action" => "QuerySendDetails", "Version" => "2017-05-25", )) ); return $content; } ini_set("display_errors", "on"); // 显示错误提示,仅用于测试时排查问题 set_time_limit(0); // 防止脚本超时,仅用于测试使用,生产环境请按实际情况设置 header("Content-Type: text/plain; charset=utf-8"); // 输出为utf-8的文本格式,仅用于测试 // 验证查询短信发送情况(QuerySendDetails)接口 print_r(querySendDetails());
config.php配置类:
<?php /** * Created by 徐锅 * User: 徐锅 * Date: 2018/1/19 * Time: 14:49 */ return [ 'captchaNum'=>4, 'accessKeyId'=>'填写自己的 accessKeyId', 'accessKeySecret'=>'填写自己的 accessKeySecret', //以上配置了一般签权信息 'sendSms' =>[ "RegionId" => "cn-hangzhou", "Action" => "SendSms", "Version" => "2017-05-25", "SignName" => "短信签名1",// fixme 必填: 短信签名 'PhoneNumbers'=>'',// fixme 必填: 短信接收号码 'TemplateParam'=>[],//fixme 可选: 设置模板参数,idea:['code'=>'SMS_61200089','customer'=>'yadan'] 'TemplateCode'=>'',//fixme 模板 Code 'OutId'=>'12345',// fixme 可选: 设置发送短信流水号 'SmsUpExtendCode'=>'1234567', // fixme 可选: 上行短信扩展码, 扩展码字段控制在7位或以下,无特殊需求用户请忽 'domain'=>'dysmsapi.aliyuncs.com',// fixme API接口所在域名 ], 'drawPrizeSendSms' =>[ "RegionId" => "cn-hangzhou", "Action" => "SendSms", "Version" => "2017-05-25", "SignName" => "短信签名2",// fixme 必填: 短信签名 'PhoneNumbers'=>'',// fixme 必填: 短信接收号码 'TemplateParam'=>[],//fixme 可选: 设置模板参数,idea:['code'=>'SMS_61200089','customer'=>'yadan'] 'TemplateCode'=>'',//fixme 模板 Code 'OutId'=>'12345',// fixme 可选: 设置发送短信流水号 'SmsUpExtendCode'=>'1234567', // fixme 可选: 上行短信扩展码, 扩展码字段控制在7位或以下,无特殊需求用户请忽 'domain'=>'dysmsapi.aliyuncs.com',// fixme API接口所在域名 ], //以上应用了两个短信签名,具体应用多少个自己在阿里云配置。主要用于发送短信的主体名称 'querySendDetails'=>[ 'PhoneNumber'=>'', // fixme 必填: 短信接收号码 'SendDate'=>'', // fixme 必填: 短信发送日期,格式Ymd,支持近30天记录查询 'PageSize'=>10, // fixme 必填: 分页大小 'CurrentPage'=>1, // fixme 必填: 当前页码 'BizId'=>'' // fixme 可选: 设置发送短信流水号 ], //以上是配置接受短信的信息与短信长度的配置 'sms'=>[ 'validate_ip'=>true, 'customer_verify_true'=>[ 'code'=>'SMS_132090198', 'customer_name'=>'', 'activity_name'=>'', 'draw_prize_number'=>'', ], 'customer_verify_true_to_distr'=>[ 'code'=>'SMS_132095195', 'distr_name'=>'', 'customer_name'=>'', 'customer_phone'=>'', 'activity_name'=>'' ], 'customer_award_true_to_distr'=>[ 'code'=>'SMS_132090445', 'distr_name'=>'', 'customer_name'=>'', 'customer_phone'=>'', 'date'=>'', ], 'customer_award_true'=>[ 'code'=>'SMS_132100332', 'customer_name'=>'', 'date'=>'', ] ],//以上是对于短信模板的配置。具体可以在阿里创建设置,code为模板代码,其他为模板变量 ];
app/sendSms.php调用类:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<?php /* * 此文件用于验证短信服务API接口,供开发时参考 * 执行验证前请确保文件为utf-8编码,并替换相应参数为您自己的信息,并取消相关调用的注释 * 建议验证前先执行Test.php验证PHP环境 * * 2017/11/30 */ namespace aliyun_mns\app; use aliyun_mns\SignatureHelper; class sendSmsDrawPrize extends SignatureHelper{ /** *助手类 * @var SignatureHelper */ protected $signatureHelper; /** * key * @var */ protected $accessKeyId; protected $accessKeySecret; protected $options; /** * @var array */ protected $config = []; /** * sendSms constructor. */ public function __construct($config= []) { $this->options = require_once dirname(dirname(__FILE__)).DIRECTORY_SEPARATOR . 'config.php'; $this->accessKeyId = $this->options['accessKeyId']; $this->accessKeySecret =$this->options['accessKeySecret']; $this->signatureHelper = new SignatureHelper(); $this->config = count($config)?array_merge($this->options['drawPrizeSendSms'],[]):$this->options['drawPrizeSendSms']; //.. } /** * @param $name * @return mixed */ public function __get($name) { return $this->config[$name]; } /** * @param string $type string 模板名称 * @param int $mobileNum float 手机号 * @return array */ public function index($type='',$mobileNum = 0,$msg_captcha = false,$temp_body = []) {; if(!is_numeric($mobileNum)){ exit('Phone Number Error or Undefined'); } ini_set("display_errors", "on"); // 显示错误提示,仅用于测试时排查问题 set_time_limit(0); // 防止脚本超时,仅用于测试使用,生产环境请按实际情况设置 header("Content-Type: text/plain; charset=utf-8"); // 输出为utf-8的文本格式,仅用于测试 $sms_captcha = $msg_captcha?:$this->register_captcha($this->options['captchaNum']); // 验证发送短信(SendSms)接口 $sms_return = $this->sendSms($type,$mobileNum,$sms_captcha,$temp_body);//$temp_body 短信发送的内容数组,细节请参考短信模板填写 $sms_arr = $this->objectToArray($sms_return); return array_merge($sms_arr,['captcha'=>$sms_captcha]); } /** * @param int $captcha_num int 验证码长度 * @return int */ private function register_captcha($captcha_num = 4) { $count=[]; for($i =0;$i<$captcha_num; $i++){ $count[] =rand(1, 9); } $captcha = (int) implode("",$count); return $captcha; } /** fixme 成功返回 array(5) { ["Message"] => string(2) "OK" ["RequestId"] => string(36) "DFFD5D4A-304E-4F39-9744-72FA6099C076" ["BizId"] => string(20) "224507516603473690^0" ["Code"] => string(2) "OK" ["captcha"] => int(4833) } */ /** * fixme actine sms event * @return bool|\stdClass */ private function sendSms($type,$mobileNum,$captcha,$temp_body) { (!empty($type)) or exit('sms type empty error'); $params = $this->getSmsConfig($type,$mobileNum,$captcha,$temp_body); // *** 需用户填写部分结束, 以下代码若无必要无需更改 *** if(!empty($params["TemplateParam"]) && is_array($params["TemplateParam"])) { $params["TemplateParam"] = json_encode($params["TemplateParam"], JSON_UNESCAPED_UNICODE); } // 此处可能会抛出异常,注意catch $content = $this->signatureHelper->request( $this->accessKeyId, $this->accessKeySecret, $this->domain, $params ); return $content; } /** * 添加 * 获取短信配置 $temp_body 数组 * @param string $sms_type fixme: repasswd/login/register/dev * @return array */ public function getSmsConfig($sms_type='',$mobileNum,$captcha = '0000',$temp_body) { $arr = $this->options['sms'];$sms_con=[]; foreach ($arr as $key=>$value) { if($sms_type === $key){ $sms_con = $arr[$key];break; }else{ continue; } } $parmas = []; $parmas['PhoneNumbers']= $mobileNum; $parmas['TemplateCode']= $sms_con['code'];//模板code $sms_con['code']= $captcha;//模板验证码 $parmas['TemplateParam']= array_merge($sms_con,$temp_body); return array_merge($this->config,$parmas); } /** * 对象转换数组 * @param $object * @return mixed */ function objectToArray(&$object) { $object = json_decode(json_encode($object),true); return $object; } }
使用实例:
$sms_msg = $sendSms->index($type,$moblie,$msg_captcha,$temp_body);
type :模板名称,即是配置config.php里的短信模板的键名,由此得到code
moblie:要发送用户的手机号
msg_captcha:发送验证码时,发送几位数
temp_body:模板变量
以上是非常简易的短信发送demo,也可以直接使用官网demo接入;
以上只是发送短信,更多时间频率的控制需要开发者自行设计;