Pārlūkot izejas kodu

日志,常用方法,配置

lizhen_gitee 11 mēneši atpakaļ
vecāks
revīzija
a1fd404f8a

+ 19 - 3
application/api/library/ExceptionHandle.php

@@ -14,9 +14,9 @@ class ExceptionHandle extends Handle
     public function render(Exception $e)
     {
         // 在生产环境下返回code信息
-        if (!\think\Config::get('app_debug')) {
+        if (!\think\Config::get('api_exception')) {
             $statuscode = $code = 500;
-            $msg = 'An error occurred';
+            $msg = $e->getMessage();
             // 验证异常
             if ($e instanceof \think\exception\ValidateException) {
                 $code = 0;
@@ -26,8 +26,24 @@ class ExceptionHandle extends Handle
             // Http异常
             if ($e instanceof \think\exception\HttpException) {
                 $statuscode = $code = $e->getStatusCode();
+                $msg = $e->getMessage();
             }
-            return json(['code' => $code, 'msg' => $msg, 'time' => time(), 'data' => null], $statuscode);
+
+            $msg = '网络开小差了';
+            $result = ['code' => $code, 'msg' => $msg, 'time' => time(), 'data' => null];
+
+            if (defined('API_REQUEST_LOG_TYPE') && defined('API_REQUEST_LOG_TYPE') == 1){
+                LogUtil::error('result','Api-Middleware-Log','request_log',$result);
+                LogUtil::error('ExceptionMsg','Api-Middleware-Log','request_log',$e->getMessage());
+                LogUtil::error('Exception','Api-Middleware-Log','request_log',$e);
+            }else{
+                //记录app异常返回结果
+                if(defined('API_REQUEST_ID')) { //记录app正常返回结果
+                    db('api_request_log')->where('id',API_REQUEST_ID)->update(['result'=>json_encode($result)]);
+                }
+            }
+
+            return json($result, $statuscode);
         }
 
         //其它此交由系统处理

Failā izmaiņas netiks attēlotas, jo tās ir par lielu
+ 153 - 0
application/common.php


+ 231 - 2
application/common/controller/Api.php

@@ -65,6 +65,11 @@ class Api
     protected $responseType = 'json';
 
     /**
+     * @var int 日志类型 1 文件;2sql
+     */
+    public $logType = 1;
+
+    /**
      * 构造方法
      * @access public
      * @param Request $request Request 对象
@@ -73,8 +78,22 @@ class Api
     {
         $this->request = is_null($request) ? Request::instance() : $request;
 
+        if(config('site.apisite_switch') == 0){
+            $controllername = $this->request->controller();
+            $controllername = strtolower($controllername);
+
+            if(!in_array($controllername,['notify','easemob','payios'])){
+                $notice = config('site.apisite_notice') ?: '全站维护中';
+                $this->error($notice);
+            }
+        }
+
         // 控制器初始化
         $this->_initialize();
+        //日志
+        $this->request_log();
+        //用户活跃
+        $this->user_active();
 
         // 前置操作方法
         if ($this->beforeActionList) {
@@ -122,16 +141,20 @@ class Api
                 $this->error(__('Please login first'), null, 401);
             }
             // 判断是否需要验证权限
-            if (!$this->auth->match($this->noNeedRight)) {
+            /*if (!$this->auth->match($this->noNeedRight)) {
                 // 判断控制器和方法判断是否有对应权限
                 if (!$this->auth->check($path)) {
                     $this->error(__('You have no permission'), null, 403);
                 }
-            }
+            }*/
         } else {
             // 如果有传递token才验证是否登录状态
             if ($token) {
                 $this->auth->init($token);
+                //传就必须传对
+                if (!$this->auth->isLogin()) {
+                    $this->error(__('Please login first'), null, 401);
+                }
             }
         }
 
@@ -169,6 +192,12 @@ class Api
      */
     protected function success($msg = '', $data = null, $code = 1, $type = null, array $header = [])
     {
+        if($msg == 1){
+            $msg = 'success';
+        }
+        if(empty($msg)){
+            $msg = '操作成功';
+        }
         $this->result($msg, $data, $code, $type, $header);
     }
 
@@ -182,6 +211,9 @@ class Api
      */
     protected function error($msg = '', $data = null, $code = 0, $type = null, array $header = [])
     {
+        if(empty($msg)){
+            $msg = __('Invalid parameters');
+        }
         $this->result($msg, $data, $code, $type, $header);
     }
 
@@ -204,6 +236,10 @@ class Api
             'time' => Request::instance()->server('REQUEST_TIME'),
             'data' => $data,
         ];
+
+        //日志
+        $this->request_log_update($result);
+
         // 如果未设置类型则使用默认类型判断
         $type = $type ? : $this->responseType;
 
@@ -327,4 +363,197 @@ class Api
         //刷新Token
         $this->request->token();
     }
+
+    /**
+     * 接口请求限制
+     * @param int $apiLimit
+     * @param int $apiLimitTime
+     * @param string $key
+     * @return bool | true:通过 false:拒绝
+     */
+    public function apiLimit($apiLimit = 1, $apiLimitTime = 1000, $key = '')
+    {
+        $userId = $this->auth->id;
+        $controller = request()->controller();
+        $action = request()->action();
+
+        if (!$key) {
+            $key = strtolower($controller) . '_' . strtolower($action) . '_' . $userId;
+        }
+
+        $redis = new Redis();
+        $redisconfig = config("redis");
+        $redis->connect($redisconfig["host"], $redisconfig["port"]);
+        if ($redisconfig['redis_pwd']) {
+            $redis->auth($redisconfig['redis_pwd']);
+        }
+        if($redisconfig['redis_selectdb'] > 0){
+            $redis->select($redisconfig['redis_selectdb']);
+        }
+
+        //
+        //指定键值新增+1 并获取
+        $count = $redis->incr($key);
+        if ($count > $apiLimit) {
+            return false;
+        }
+
+        //设置过期时间
+        if ($count == 1) {
+            $redis->pExpire($key, $apiLimitTime);
+        }
+
+        return true;
+    }
+
+    /*
+     * api 请求日志
+     * */
+    protected function request_log(){
+
+        //api_request_log
+        $modulename     = $this->request->module();
+        $controllername = $this->request->controller();
+        $actionname     = $this->request->action();
+
+        if(strtolower($actionname) == 'callback'){
+            return true;
+        }
+
+        defined('API_REQUEST_LOG_TYPE') or define('API_REQUEST_LOG_TYPE', $this->logType);
+        $params = $this->request->request();
+        if ($this->logType === 1){
+            //日志统一写入
+            register_shutdown_function([new LogUtil, 'close']);
+            LogUtil::getInstance('Api/'); //设置日志存入通道
+
+            LogUtil::info('uid', 'Api-Middleware-Log', 'request_log', $this->auth->id);
+            LogUtil::info('url', 'Api-Middleware-Log', 'request_log', $modulename . '/' . $controllername . '/' . $actionname);
+            LogUtil::info('params', 'Api-Middleware-Log', 'request_log', $params);
+            LogUtil::info('ip', 'Api-Middleware-Log', 'request_log', request()->ip());
+
+        }else{
+            $data = [
+                'uid'   => $this->auth->id,
+                'api'   => $modulename.'/'.$controllername.'/'.$actionname,
+                'params' => json_encode($params),
+                'addtime'  => time(),
+                'adddatetime'  => date('Y-m-d H:i:s'),
+                'ip'   => request()->ip(),
+            ];
+            $request_id = db('api_request_log')->insertGetId($data);
+            defined('API_REQUEST_ID') or define('API_REQUEST_ID', $request_id);
+        }
+    }
+
+    protected function request_log_update($log_result){
+        $actionname     = $this->request->action();
+        if(strtolower($actionname) == 'givegifttoyou'){
+            //return true;
+        }
+
+        if ($this->logType === 1){
+            if (strlen(json_encode($log_result['data'])) > 1000) {
+                $log_result['data'] = '数据太多,不记录';
+            }
+            LogUtil::info('result', 'Api-Middleware-Log', 'request_log', $log_result);
+        }else{
+            if(defined('API_REQUEST_ID')) { //记录app正常返回结果
+                if(strlen(json_encode($log_result['data'])) > 1000) {
+                    $log_result['data'] = '数据太多,不记录';
+                }
+                db('api_request_log')->where('id',API_REQUEST_ID)->update(['result'=>json_encode($log_result)]);
+            }
+        }
+    }
+
+    //更新用户活跃
+    protected function user_active(){
+        if($this->auth->isLogin()){
+            db('user_active')->where('user_id',$this->auth->id)->update(['requesttime'=>time()]);
+        }
+    }
+
+    //获取用户是否活跃,7200秒,2小时
+    //1活跃,0不活跃
+    protected function user_activeinfo($user_id,$requesttime = 0){
+
+        if(empty($requesttime)){
+            $requesttime = db('user_active')->where('user_id',$user_id)->value('requesttime');
+        }
+
+        $result = [
+            'is_active' => 1,
+            'active_text' => get_last_time($requesttime).'在线',
+        ];
+
+        if(time() - $requesttime > 7200){
+            $result = [
+                'is_active' => 0,
+                'active_text' => '离线',
+            ];
+        }
+
+        return $result;
+    }
+
+    //获取用户是否vip,1是,0否
+    protected function is_vip($user_id){
+        $result = 0;
+
+        $vip_endtime = db('user_wallet')->where('user_id',$user_id)->value('vip_endtime');
+        $result = $vip_endtime > time() ? 1 : 0;
+
+        return $result;
+    }
+
+    //用户是否有某项权限
+    //1有,0没有
+    protected function user_power($user_id,$power = ''){
+        $is_vip = $this->is_vip($user_id);
+        if($is_vip != 1){
+            return 0;
+        }
+        $power = db('user_power')->where('user_id',$user_id)->value($power);
+        return $power;
+
+    }
+
+    //是否关注
+    protected function is_follow($uid,$follow_uid){
+        $where = [
+            'uid' => $uid,
+            'follow_uid' => $follow_uid,
+        ];
+        $check = db('user_follow')->where($where)->find();
+        if($check){
+            return 1;
+        }else{
+            return 0;
+        }
+    }
+
+    //是否拉黑
+    protected function is_black($uid,$black_user_id){
+        $where = [
+            'user_id' => $uid,
+            'black_user_id' => $black_user_id,
+        ];
+        $check = db('user_blacklist')->where($where)->find();
+        if($check){
+            return 1;
+        }else{
+            return 0;
+        }
+    }
+
+    //是否好友
+    protected function is_friend($uid,$follow_uid){
+        $is_follow = $this->is_follow($uid,$follow_uid);
+        $be_follow = $this->is_follow($follow_uid,$uid);
+        if($is_follow && $be_follow){
+            return 1;
+        }
+        return 0;
+    }
 }

+ 5 - 0
application/config.php

@@ -306,4 +306,9 @@ return [
         //API接口地址
         'api_url'               => 'https://api.fastadmin.net',
     ],
+
+    //自定义
+
+    //api显示错误
+    'api_exception'          => true,
 ];

Daži faili netika attēloti, jo izmaiņu fails ir pārāk liels