首页把阿里云的接口放在thinkphp根目录创建的Api目录下
\ThinkPHP\Library\Org\Util目录下新增阿里云短信接口类AliSms.class.php。内容如下:
<?php namespace Org\Util; require_once 'Api/api_sdk/vendor/autoload.php'; use Aliyun\Core\Config; use Aliyun\Core\Profile\DefaultProfile; use Aliyun\Core\DefaultAcsClient; use Aliyun\Api\Sms\Request\V20170525\SendSmsRequest; use Aliyun\Api\Sms\Request\V20170525\QuerySendDetailsRequest; // 加载区域结点配置 Config::load(); class AliSms { static $acsClient = null; /** * 取得AcsClient * * @return DefaultAcsClient */ public static function getAcsClient() { //产品名称:云通信流量服务API产品,开发者无需替换 $product = "Dysmsapi"; //产品域名,开发者无需替换 $domain = "dysmsapi.aliyuncs.com"; // TODO 此处需要替换成开发者自己的AK (https://ak-console.aliyun.com/) $accessKeyId = "填写自己的"; // AccessKeyId $accessKeySecret = "填写自己的"; // AccessKeySecret // 暂时不支持多Region $region = "cn-hangzhou"; // 服务结点 $endPointName = "cn-hangzhou"; if(static::$acsClient == null) { //初始化acsClient,暂不支持region化 $profile = DefaultProfile::getProfile($region, $accessKeyId, $accessKeySecret); // 增加服务结点 DefaultProfile::addEndpoint($endPointName, $region, $product, $domain); // 初始化AcsClient用于发起请求 static::$acsClient = new DefaultAcsClient($profile); } return static::$acsClient; } /** * 发送短信 * @return stdClass */ public static function sendSms($phone, $code) { // 初始化SendSmsRequest实例用于设置发送短信的参数 $request = new SendSmsRequest(); // 必填,设置短信接收号码 $request->setPhoneNumbers($phone); // 必填,设置签名名称,应严格按"签名名称"填写,请参考: https://dysms.console.aliyun.com/dysms.htm#/develop/sign $request->setSignName("自己的"); // 必填,设置模板CODE,应严格按"模板CODE"填写, 请参考: https://dysms.console.aliyun.com/dysms.htm#/develop/template $request->setTemplateCode("自己的模版名"); // 可选,设置模板参数, 假如模板中存在变量需要替换则为必填项 $request->setTemplateParam(json_encode(Array( // 短信模板中字段的值 "code"=>$code ))); // 可选,设置流水号 $request->setOutId(""); // 选填,上行短信扩展码(扩展码字段控制在7位或以下,无特殊需求用户请忽略此字段) $request->setSmsUpExtendCode(""); // 发起访问请求 $acsResponse = static::getAcsClient()->getAcsResponse($request); return $acsResponse; } /** * 短信发送记录查询 * @return stdClass */ public static function querySendDetails($phone, $posttime, $pagesize, $page) { // 初始化QuerySendDetailsRequest实例用于设置短信查询的参数 $request = new QuerySendDetailsRequest(); // 必填,短信接收号码 $request->setPhoneNumber($phone); // 必填,短信发送日期,格式Ymd,支持近30天记录查询 $request->setSendDate($posttime); // 必填,分页大小 $request->setPageSize($pagesize); // 必填,当前页码 $request->setCurrentPage($page); // 选填,短信发送流水号 $request->setBizId(""); // 发起访问请求 $acsResponse = self::getAcsClient()->getAcsResponse($request); return $acsResponse; } }
然后我的控制器代码:
<?php namespace Home\Controller; use Think\Controller; class SmsController extends Controller { public function index(){ $this->display(); } public function sendCode(){ $phone = $_GET['phone']; $code = $this->generateCode(); session('code', $code); session('phone', $phone); //$response = \Org\Util\AliSms::sendSms($phone, $code); $sms = new \Org\Util\AliSms(); $response = $sms->sendSms($phone, $code); $status = $response->Code; if($status == "OK"){ echo "短信发送成功,请注意查收!"; }else{ echo "短信发送失败,请稍后重试!"; } } //生成验证码 public function generateCode(){ for ($i=0; $i < 4; $i++) { $msgcode .= rand(0, 9); } return $msgcode; } //验证手机验证码 public function checkCode(){ $phone = $_POST['phone']; $code = intval($_POST['codemsg']); if(session('code') == $code && session('phone') == $phone){ echo "验证通过!,你的手机号是".$phone.",您提交的验证码为".$code."生成的验证码为".session('code'); }else{ echo "有没有搞错,验证码手机号不一致!"; } } public function smsList(){ header('Content-Type: text/plain; charset=utf-8'); $phone = $_GET['phone']; $posttime = $_GET['posttime']; $pagesize = isset($_GET['pagesize']) ? $_GET['pagesize'] : 10; $page = isset($_GET['page']) ? intval($_GET['page']) : 1; $sms = new \Org\Util\AliSms(); //$result = \Org\Util\AliSms::querySendDetails($phone, $posttime, $pagesize, $page); $result = $sms->querySendDetails($phone, $posttime, $pagesize, $page); $data = json_decode(json_encode($result), true); //stdClass >> array $totalcount = $data['TotalCount']; $list = $data['SmsSendDetailDTOs']['SmsSendDetailDTO']; //print_r($data); $this->assign("totalcount", $totalcount); $this->assign("list", $list); $this->display(); } }
前端使用layui的前端框架,代码参考:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"> <title>短信接口测试文档</title> <link rel="stylesheet" href="__PUBLIC__/css/style.css"> <link rel="stylesheet" href="__PUBLIC__/css/layui.css"> <script src="__PUBLIC__/layui.js"></script> <script src="__PUBLIC__/js/jquery.min.js"></script> </head> <body class="layui-layout-body"> <div class="layui-warp"> <fieldset class="layui-elem-field layui-field-title" style="margin-top: 30px;"> <legend>发送短信</legend> <fieldset class="layui-elem-field" style="padding:10px;margin-top:10px;"> <form class="layui-form" method="post" action="{:U('Sms/checkCode')}"> <!-- 提示:如果你不想用form,你可以换成div等任何一个普通元素 --> <div class="layui-form-item"> <label class="layui-form-label">手机号</label> <div class="layui-input-inline"> <input type="text" name="phone" id="phone" placeholder="请输入手机号" autocomplete="off" class="layui-input" lay-verify="required|phone"> </div> <input type="text" class="layui-btn" id="sendbtn" value="获取验证码" /> </div> <div class="layui-form-item"> <label class="layui-form-label">验证码</label> <div class="layui-input-block"> <input type="text" name="codemsg" placeholder="" autocomplete="off" class="layui-input"> </div> </div> <div class="layui-form-item"> <div class="layui-input-block"> <button class="layui-btn" lay-submit lay-filter="*">提交验证</button> </div> </div> </form> </fieldset> </div> </fieldset> </div> <div class="layui-warp"> <fieldset class="layui-elem-field layui-field-title" style="margin-top: 30px;"> <legend>查询短信</legend> <fieldset class="layui-elem-field" style="padding:10px;margin-top:10px;"> <form class="layui-form" method="get" action="{:U('Sms/smsList')}" target="_blank"> <div class="layui-form-item"> <label class="layui-form-label">手机号</label> <div class="layui-input-inline"> <input type="text" name="phone" id="phone" placeholder="请输入手机号" autocomplete="off" class="layui-input" lay-verify="required|phone"> </div> </div> <div class="layui-form-item"> <label class="layui-form-label">选择时间</label> <div class="layui-input-inline"> <input type="text" name="posttime" class="layui-input" id="posttime" lay-verify="required"> </div> </div> <div class="layui-form-item"> <div class="layui-input-inline"> <input type="hidden" name="pagesize" required lay-verify="required" placeholder="" autocomplete="off" class="layui-input layui-bg-gray" value="10"> </div> </div> <div class="layui-form-item"> <div class="layui-input-block"> <button class="layui-btn" lay-submit lay-filter="*">立即查询</button> </div> </div> </form> </fieldset> </div> </fieldset> </div> <script> </script> <script> layui.use('form', function(){ var form = layui.form; $("#sendbtn").click(function(){ var telnumber = $("#phone").val(); if(!telnumber.match(/^(((13[0-9]{1})|147|(15[0-9]{1})|180|182|185|186|187|188|189)+\d{8})$/)){ //alert("手机号码不正确"); layer.alert("手机号码不正确"); return false; telnumber.focus(); } var setptime = 59; $("#sendbtn").val("60s后重新发送"); var _res = setInterval(function(){ $("#sendbtn").attr("disabled",true); $("#sendbtn").val(setptime+'s后重新发送'); setptime-=1; if(setptime <= 0){ $("#sendbtn").attr("disabled",false); $("#sendbtn").val("获取验证码") clearInterval(_res); } },1000); $.get("{:U('Sms/sendCode')}", {phone:telnumber}, function(data){ //alert(data); layer.alert(data); }); }); //各种基于事件的操作,下面会有进一步介绍 }); layui.use('laydate', function(){ var laydate = layui.laydate; //执行一个laydate实例 laydate.render({ elem: '#posttime' //指定元素 ,format: 'yyyyMMdd' //可任意组合 ,value: new Date() }); }); </script> </body> </html>