Thinkphp3.2.3使用阿里云短信服务接口,只是使用短信发送功能,所有选择的轻量版的SDK再封装好方法
使用轻量版SDK支持php>=5.4
使用到的文件:(这是我自己的使用习惯放的目录,下面将贴出全部代码)
App\Common\Org\AliyunSMS.class.php #轻量版SDK文件
App\Api\Controller\AliyunSMSController.class.php #写好的方法,在别的地方直接调用
AliyunSMS.class.php文件代码,这是阿里云的源码,只是修改了名称
<?php namespace Common\Org; /** * 签名助手 2017/11/19 * * Class SignatureHelper */ class AliyunSMS { /** * 生成签名并发起请求 * * @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 * @param $method boolean 使用GET或POST方法请求,VPC仅支持POST * @return bool|\stdClass 返回API接口调用结果,当发生错误时返回false */ public function request($accessKeyId, $accessKeySecret, $domain, $params, $security=false, $method='POST') { $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 = "${method}&%2F&" . $this->encode(substr($sortedQueryStringTmp, 1)); $sign = base64_encode(hash_hmac("sha1", $stringToSign, $accessKeySecret . "&",true)); $signature = $this->encode($sign); $url = ($security ? 'https' : 'http')."://{$domain}/"; try { $content = $this->fetchContent($url, $method, "Signature={$signature}{$sortedQueryStringTmp}"); return json_decode($content); } catch( \Exception $e) { return false; } } private function encode($str) { $res = urlencode($str); $res = preg_replace("/\+/", "%20", $res); $res = preg_replace("/\*/", "%2A", $res); $res = preg_replace("/%7E/", "~", $res); return $res; } private function fetchContent($url, $method, $body) { $ch = curl_init(); if($method == 'POST') { curl_setopt($ch, CURLOPT_POST, 1);//post提交方式 curl_setopt($ch, CURLOPT_POSTFIELDS, $body); } else { $url .= '?'.$body; } 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) { // 大多由设置等原因引起,一般无法保障后续逻辑正常执行, // 所以这里触发的是E_USER_ERROR,会终止脚本执行,无法被try...catch捕获,需要用户排查环境、网络等故障 trigger_error("[CURL_" . curl_errno($ch) . "]: " . curl_error($ch), E_USER_ERROR); } curl_close($ch); return $rtn; } }
AliyunSMSController.class.php 这是我自己写好的方法,放在Api目录的,专门放接口文件的目录,签名模板和KEY别忘了填,
DuanxinLog($desc,$content->Message,$params["PhoneNumbers"],1,1); 这是用于记录日志的方法,要么注释要么自己写这方法
<?php namespace Api\Controller; use Think\Controller; use Common\Org\AliyunSMS; class AliyunSMSController extends Controller{ public function _initialize(){ $this->accessKeyId = "AccessKeyId"; //AccessKeyId $this->accessKeySecret = "AccessKeySecret"; //AccessKeySecret $this->SignName = "小风博客"; //签名 $this->CodeId = "SMS_162195656"; //验证码模板ID } //发送短信消息 public function SendSMS($params=[],$desc){ // fixme 必填:是否启用https $security = false; $params["SignName"] = $this->SignName; if(!empty($params["TemplateParam"]) && is_array($params["TemplateParam"])) { $params["TemplateParam"] = json_encode($params["TemplateParam"], JSON_UNESCAPED_UNICODE); } $helper = new AliyunSMS(); $content = $helper->request( $this->accessKeyId, $this->accessKeySecret, "dysmsapi.aliyuncs.com", array_merge($params, array( "RegionId" => "cn-hangzhou", "Action" => "SendSms", "Version" => "2017-05-25", )), $security ); //不管发送成功还是失败都写入日志 if($content===false){ //$msg = "发送异常"; DuanxinLog($desc,'发送异常',$params["PhoneNumbers"],0,1); return false; }else{ if($content->Code=="OK"){ //$msg = "发送成功"; DuanxinLog($desc,$content->Message,$params["PhoneNumbers"],1,1); return true; }else{ //$msg = "发送失败 ".$data['Message']; DuanxinLog($desc,$content->Message,$params["PhoneNumbers"],0,1); return false; } } } //群发送短信消息 public function SendSMS_S($params=[],$desc){ // fixme 必填:是否启用https $security = false; $params["SignName"] = $this->SignName; // *** 需用户填写部分结束, 以下代码若无必要无需更改 *** $params["TemplateParamJson"] = json_encode($params["TemplateParamJson"], JSON_UNESCAPED_UNICODE); $params["SignNameJson"] = json_encode($params["SignNameJson"], JSON_UNESCAPED_UNICODE); $params["PhoneNumberJson"] = json_encode($params["PhoneNumberJson"], JSON_UNESCAPED_UNICODE); if(!empty($params["SmsUpExtendCodeJson"]) && is_array($params["SmsUpExtendCodeJson"])) { $params["SmsUpExtendCodeJson"] = json_encode($params["SmsUpExtendCodeJson"], JSON_UNESCAPED_UNICODE); } $helper = new AliyunSMS(); $content = $helper->request( $this->accessKeyId, $this->accessKeySecret, "dysmsapi.aliyuncs.com", array_merge($params, array( "RegionId" => "cn-hangzhou", "Action" => "SendBatchSms", "Version" => "2017-05-25", )), $security ); //不管发送成功还是失败都写入日志 if($content===false){ //$msg = "发送异常"; DuanxinLog($desc,'发送异常',$params["PhoneNumberJson"],0,1); return false; }else{ $data = (array)$content; if($content->Code=="OK"){ //$msg = "发送成功"; DuanxinLog($desc,$content->Message,$params["PhoneNumberJson"],1,1); return true; }else{ //$msg = "发送失败 ".$data['Message']; DuanxinLog($desc,$content->Message,$params["PhoneNumberJson"],0,1); return false; } } } }
使用场景代码:
$state = $model->data($data)->add(); if($state>0){ //短信通知 $che = che_desc($s['vehicles']); if(!empty($siji['phone'])){ $params["PhoneNumbers"] = $siji['phone']; //手机号 $params["TemplateCode"] = 'SMS_163438651'; //短信模版 $params['TemplateParam'] =Array ( "desc" => $state, "status" => '正常', "name" => $data['name'], "cost" => $data['cost'], "che" => $che, "s_time" => $data['s_time'], "e_time" => $data['e_time'], "code" => $state ); $dx = A("Api/AliyunSMS"); //调用封装好的方法 $zt = $dx->SendSMS($params,'此处记录日志的标题');//发送信息 if($zt==true){ $z = '发送成功'; }else{ $z = '发送失败'; } } $this->success('提交成功!'.$z,U('Vehicle/adm'));
阿里云短信服务(文档):短信发送API(SendSms)---PHP
阿里云短信服务(SDK及DEMO下载):SDK及DEMO下载
阿里云短信服务(接口调试常见错误码):短信接口调用错误码
本文为 小风原创文章,转载无需和我联系,但请注明来自 小风博客www.hotxf.com
贝如:PHPLAF v.1.0.10 正式发布了!开发文档:https://blog.junphp.com/apiword.jsp
2020-04-24 16:29:44 回复