给初学者的参考:
<?php
/**
*
* @authors dl
* @date 2018-11-24 11:19:59
* @version $Id$
*/
namespace app\api\controller;
use think\Controller;
use think\Request;
use think\Validate;
class Common extends Controller {
protected $request;
protected $validater;
protected $params;
protected $rules = [
'Test' => [
'test1' => [
['email', 'require|email'],
['user_name', 'require|chsDash|max:30', '用户名称必须输入|用户名称格式错误|用户名称最大不能超过30'],
['password', 'require|length:32', '密码不能为空|密码格式错误'],
],
'test2' => [
'user_name' => 'require|chsDash|max:30',
'password' => 'require|length:32',
],
],
];
protected function _initialize() {
$this->request = Request::instance();
$this->check_time($this->request->only(['time'])); //时间验证
$this->check_token($this->request->param()); //token验证
$this->params = $this->check_params($this->request->except(['time'])); //参数验证
}
/**
* 验证请求是否超时
* @param string $arr [包含时间戳的参数数组]
* @return [json] [检测结果]
*/
public function check_time($arr = []) {
$time = intval($arr['time']);
if (!isset($arr['time']) || $time <= 1) {
$this->return_msg(400, '时间戳不存在');
}
if (time() - $time > 60) {
$this->return_msg(400, '请求超时');
}
}
/**
* 验证token(暂时用对称加密简单验证下)
* @param array $arr [description]
* @return [type] [description]
*/
public function check_token($arr = []) {
/***** api传过来的token *****/
if (!isset($arr['token']) || empty($arr['token'])) {
$this->return_msg(400, 'token值不能为空');
}
$api_token = $arr['token'];
unset($arr['token']);
/***** 服务端生成token *****/
$service_token = '';
foreach ($arr as $key => $value) {
$service_token .= md5($value);
}
$service_token = md5('api_' . $service_token . '_api');
/***** 对比token,返回结果 *****/
if ($api_token !== $service_token) {
$this->return_msg(400, 'token值不正确');
}
}
/**
* 验证参数,参数过滤
* @param array $arr [除time之外的所有参赛]
* @return [return] [合格的参数输入]
*/
public function check_params($arr = []) {
/***** 获取验证规则 *****/
$rule = $this->rules[$this->request->controller()][$this->request->action()];
/***** 验证参数并返回错误 *****/
$this->validater = new Validate($rule);
if (!$this->validater->check($arr)) {
$this->return_msg(400, $this->validater->getError());
}
/***** 如果正常,通过验证 *****/
return $arr;
}
/**
* json返回,返回值过滤null
* @param [int] $code [结果码]
* @param [strstring] $msg [错误信息]
* @param array $data [接口要返回的数据]
* @return [json] [最终的json数据]
*/
public function return_msg($code, $msg = '', $data = []) {
$result = [
'code' => $code,
'msg' => $msg,
'data' => $data,
];
// array_walk_recursive($result, function (& $val, $key ) { if ($val === null) $val = ''; });//过滤null值
$result = json_encode($result, JSON_UNESCAPED_UNICODE);
$result = str_replace('null', '""', $result);
die($result);
}
}