// +---------------------------------------------------------------------- namespace App\Services\Common; use App\Models\AdModel; use App\Models\ApiModel; use App\Services\BaseService; use App\Services\RedisService; /** * 接口管理-服务类 * Class ApiService * @package App\Services\Common */ class ApiService extends BaseService { // 静态对象 protected static $instance = null; /** * 构造函数 * ApiService constructor. */ public function __construct() { $this->model = new ApiModel(); } /** * 静态入口 * @return static|null */ public static function make() { if (!self::$instance) { self::$instance = (new static()); } return self::$instance; } /** * 添加或编辑 * @return array */ public function saveData($adminId, $data) { $data['admin_id'] = $adminId; // 权限 if ($data['user_limits']) { $data['user_limits'] = array_filter($data['user_limits']); $data['user_limits'] = $data['user_limits']? implode(',', $data['user_limits']) : ''; } // 结束时间 $id = isset($data['id'])? $data['id'] : 0; if (!$id) { $data['api_key'] = getCode('Ti', 12); } if($data['expired_at'] <= date('Y-m-d')){ return returnJson(2028, false); } if($this->model->where(['username'=> $data['username']])->whereNotIn('id',[$id])->value('id')){ return returnJson(2005, false); } return parent::edit($data); // TODO: Change the autogenerated stub } /** * 验证接口 * @param $apiKey * @return false */ public function checkApi($apiKey) { if(empty($apiKey)){ $this->error = '6001'; return false; } $cachekey = "apis:apiKeys:{$apiKey}"; $info = RedisService::get($cachekey); if(empty($info)){ $info = ApiModel::where(['api_key'=> $apiKey,'status'=> 1,'mark'=>1]) ->select(['id','username','user_limits','expired_at']) ->first(); if(empty($info)){ $this->error = '6002'; return false; } // 接口是否已到期 $expiredAt = isset($info['expired_at']) && $info['expired_at']? strtotime($info['expired_at']) : 0; if($expiredAt && $expiredAt<= time()){ $this->error = '6003'; return false; } } return $info; } /** * 获取详情 * @param $id * @return mixed */ public function getInfo($id, $refresh = false) { $cachekey = "caches:apis:info:{$id}"; $info = RedisService::get($cachekey); if($info && !$refresh){ return $info; } $info = ApiModel::where(['id'=> $id,'status'=> 1,'mark'=>1]) ->select(['id','username','notify_url','user_limits','expired_at']) ->first(); if($info){ $info['user_limits'] = $info['user_limits']? explode(',', $info['user_limits']) : []; RedisService::set($cachekey, $info, 30); } return $info; } }