thinkphp 5.0整合阿里大于验证码短信发送接口,含完整模型验证实例DEMO

为大家分享一个阿里大于短信发送接口:

首先创建一个发送模型(Send.php):

<?php
namespace app\index\model;
use think\Validate;
class Send extends \think\Model
{
	public static $sms_config = [
		'appkey'		=> '',//阿里大于APPKEY
		'secretKey' 	=> '',//阿里大于secretKey
		'FreeSignName' 	=> '安德兔',//短信签名
	];
	public function sms($data=[])
	{
		$validate = new Validate([
			['param','require|array','参数必填|参数必须为数组'],
			['mobile','require|/1[34578]{1}\d{9}$/','手机号错误|手机号错误'],
			['template','require','模板id错误'],
		]);
		if (!$validate->check($data)) {
			return $validate->getError();
		}
		define('TOP_SDK_WORK_DIR', CACHE_PATH.'sms_tmp/');
		define('TOP_SDK_DEV_MODE', false);
		vendor('alidayu.TopClient');
		vendor('alidayu.AlibabaAliqinFcSmsNumSendRequest');
		vendor('alidayu.RequestCheckUtil');
		vendor('alidayu.ResultSet');
		vendor('alidayu.TopLogger');
		$config = self::$sms_config;
		$c = new \TopClient;
		$c->appkey = $config['appkey'];
		$c->secretKey = $config['secretKey'];
		$req = new \AlibabaAliqinFcSmsNumSendRequest;
		$req->setExtend('');
		$req->setSmsType('normal');
		$req->setSmsFreeSignName($config['FreeSignName']);
		$req->setSmsParam(json_encode($data['param']));
		$req->setRecNum($data['mobile']);
		$req->setSmsTemplateCode($data['template']);
		$result = $c->execute($req);
		$result = $this->_simplexml_to_array($result);
		if(isset($result['code'])){
			return $result['sub_code'];
		}
		return true;
	}

	private function _simplexml_to_array($obj)
	{//该函数用于转化阿里大于返回的数据,将simplexml格式转化为数组,方面后续使用
		if(count($obj) >= 1){
			$result = $keys = [];
			foreach($obj as $key=>$value){
				isset($keys[$key]) ? ($keys[$key] += 1) : ($keys[$key] = 1);
				if( $keys[$key] == 1 ){
					$result[$key] = $this->_simplexml_to_array($value);
				}elseif( $keys[$key] == 2 ){
					$result[$key] = [$result[$key], $this->_simplexml_to_array($value)];
				}else if( $keys[$key] > 2 ){
					$result[$key][] = $this->_simplexml_to_array($value);
				}
			}
			return $result;
		}else if(count($obj) == 0){
			return (string)$obj;
		}
	}
}
?>

创建好模型后,可在其他地方调用,下面我们创建一个简单的index控制器,用来测试:

<?php
namespace app\index\controller;
use app\index\model\Send;
error_reporting(0);
class Index extends \think\Controller
{

	public function sms()
	{
		if(request()->isPost()){
			$Send = new Send;
			$result = $Send->sms([
				'param'  => ['code'=>'123456','product'=>'安德兔'],
				'mobile'  => input('post.mobile/s','','trim,strip_tags'),
				'template'  => 'SMS_12940581',
			]);
			if($result !== true){
				return $this->error($result);
			}
			return $this->success('短信下发成功!');
		}
		return $this->fetch();
	}
}

创建简单的模板文件用来测试:

<!doctype html>
<html lang="zh-CN">
<head>
    <meta charset="utf-8">
	<title>阿里大于短信发送测试</title>
    <base href="{:request()->domain()}" />
    <link href="static/css/bootstrap.css" rel="stylesheet">
    <link href="static/css/common.css" rel="stylesheet">
    <link href="static/css/admin.css" rel="stylesheet">
	<script src="static/js/jquery-1.12.0.min.js"></script>
    <script src="static/js/bootstrap.min.js"></script>
    <script src="static/js/jquery.qrcode.min.js"></script>
    <link rel="shortcut icon" href="favicon.ico" type="image/x-icon"/>
</head>
<body>
<div class="container">
	<div class="panel panel-default">
		<div class="panel-heading">
			<strong>阿里大于短信发送测试</strong>
		</div>
		<div class="panel-body">
			<form class="form-horizontal sms-form" method="post" action="{:url('index/index/sms')}">
				<div class="form-group">
					<label class="col-sm-2 control-label">接收手机号</label>
					<div class="col-sm-10">
						<input type="text" class="form-control" name="mobile" value="">
						<p class="help-block">点击发送短信,您将收到:“【安德兔】验证码123456,您正在注册成为安德兔用户,感谢您的支持。”</p>
					</div>
				</div>
				<div class="form-group">
					<div class="col-sm-offset-2 col-sm-10">
						<button type="submit" class="btn btn-success">发送短信</button>
					</div>
				</div>
			</form>
		</div>
		<div class="panel-footer">&nbsp;</div>
	</div>
</div>
<script>
	$(function(){
		$('.sms-form').submit(function(){
			var $this = $(this);
			if(!$this.hasClass('lock-form')){
				$this.addClass('lock-form');//锁定表单
				var formData = new FormData($this[0]);
				$.ajax({
					url:$this.attr("action"),
					type:'POST',
					data:formData,
					dataType:'json',
					cache: false,
					contentType: false,
					processData: false,
					success:function(s){
						$this.removeClass('lock-form');//解锁表单
						var html = (s.code != 1 ? '错误代码:' : '')+s.msg;
						$('.panel-footer').html(html);
						return false;
					}
				});
			}
			return false;
		});
	});
</script>
</body>
</html>
posted @ 2017-01-12 16:11  暖心i  阅读(1839)  评论(0编辑  收藏  举报