Linfinity

Never say never.
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

api开发CommonController

Posted on 2020-07-10 16:00  Linfinity  阅读(359)  评论(0编辑  收藏  举报
<?php

namespace app\api\controller;

use think\Controller;
use think\Request;
use think\Validate;

class Common extends Controller
{
    protected $params;

    //每个控制器的方法对应的请求参数验证规则
    protected $rules = [
        "User" => [
            "login" => [
                "username" => "require|max:6",
                "password" => "require|length:32"
            ]
        ]
    ];

    public function initialize()
    {
        $params = input();
        $time = isset($params['time'])?$params['time']:"";
        $token = isset($params['token'])?$params['token']:"";
        $this->check_time($time);
        $this->check_token($token, $time);
        $this->check_params($params);
    }

    /*验证请求接口时间*/
    public function check_time($time)
    {
        if($time == "" || time()-$time>60)
        {
            $this->return_msg(400, "请求时间超时");
        }
    }

    /*验证令牌*/
    public function check_token($token, $time)
    {
        if($token == "" || $token != md5("cain_$time"))
        {
            $this->return_msg(400, "token令牌验证失败");
        }

    }

    /*验证并过滤参数*/
    public function check_params($params)
    {
        unset($params['time']);
        unset($params['token']);
        $validate = Validate::make($this->rules[request()->controller()][request()->action()]);
        if(!$validate->check($params))
        {
            $this->return_msg(400, $validate->getError());

        }
        else
            $this->params = $params;

    }

    /*返回信息*/
    public function return_msg($code, $msg="", $data=[])
    {
        echo json_encode(['code'=>$code, 'msg'=>$msg, "data"=>$data]);die;
    }



}