Api.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489
  1. <?php
  2. namespace app\common\controller;
  3. use app\common\library\Auth;
  4. use app\utils\RedisUtil;
  5. use think\Config;
  6. use think\exception\HttpResponseException;
  7. use think\exception\ValidateException;
  8. use think\Hook;
  9. use think\Lang;
  10. use think\Loader;
  11. use think\Request;
  12. use think\Response;
  13. use think\Route;
  14. use think\Validate;
  15. use Redis;
  16. /**
  17. * API控制器基类
  18. */
  19. class Api
  20. {
  21. /**
  22. * @var Request Request 实例
  23. */
  24. protected $request;
  25. /**
  26. * @var bool 验证失败是否抛出异常
  27. */
  28. protected $failException = false;
  29. /**
  30. * @var bool 是否批量验证
  31. */
  32. protected $batchValidate = false;
  33. /**
  34. * @var array 前置操作方法列表
  35. */
  36. protected $beforeActionList = [];
  37. /**
  38. * 无需登录的方法,同时也就不需要鉴权了
  39. * @var array
  40. */
  41. protected $noNeedLogin = [];
  42. /**
  43. * 无需鉴权的方法,但需要登录
  44. * @var array
  45. */
  46. protected $noNeedRight = [];
  47. /**
  48. * 权限Auth
  49. * @var Auth
  50. */
  51. protected $auth = null;
  52. /**
  53. * 默认响应输出类型,支持json/xml
  54. * @var string
  55. */
  56. protected $responseType = 'json';
  57. public $page = 1;
  58. public $listrow = 10;
  59. /**
  60. * 构造方法
  61. * @access public
  62. * @param Request $request Request 对象
  63. */
  64. public function __construct(Request $request = null)
  65. {
  66. $this->request = is_null($request) ? Request::instance() : $request;
  67. $this->page = input('page',1);
  68. $this->listrow= input('listrow',10);
  69. // 控制器初始化
  70. $this->_initialize();
  71. //日志
  72. $this->request_log();
  73. //用户活跃
  74. $this->user_active();
  75. // 前置操作方法
  76. if ($this->beforeActionList) {
  77. foreach ($this->beforeActionList as $method => $options) {
  78. is_numeric($method) ?
  79. $this->beforeAction($options) :
  80. $this->beforeAction($method, $options);
  81. }
  82. }
  83. }
  84. /**
  85. * 初始化操作
  86. * @access protected
  87. */
  88. protected function _initialize()
  89. {
  90. //跨域请求检测
  91. check_cors_request();
  92. // 检测IP是否允许
  93. check_ip_allowed();
  94. //移除HTML标签
  95. $this->request->filter('trim,strip_tags,htmlspecialchars');
  96. $this->auth = Auth::instance();
  97. $modulename = $this->request->module();
  98. $controllername = Loader::parseName($this->request->controller());
  99. $actionname = strtolower($this->request->action());
  100. // token
  101. $token = $this->request->server('HTTP_TOKEN', $this->request->request('token', \think\Cookie::get('token')));
  102. $path = str_replace('.', '/', $controllername) . '/' . $actionname;
  103. // 设置当前请求的URI
  104. $this->auth->setRequestUri($path);
  105. // 检测是否需要验证登录
  106. if (!$this->auth->match($this->noNeedLogin)) {
  107. //初始化
  108. $this->auth->init($token);
  109. //检测是否登录
  110. if (!$this->auth->isLogin()) {
  111. $this->error(__('Please login first'), null, 401);
  112. }
  113. // 判断是否需要验证权限
  114. /*if (!$this->auth->match($this->noNeedRight)) {
  115. // 判断控制器和方法判断是否有对应权限
  116. if (!$this->auth->check($path)) {
  117. $this->error(__('You have no permission'), null, 403);
  118. }
  119. }*/
  120. } else {
  121. // 如果有传递token才验证是否登录状态
  122. if ($token) {
  123. $this->auth->init($token);
  124. }
  125. }
  126. $upload = \app\common\model\Config::upload();
  127. // 上传信息配置后
  128. Hook::listen("upload_config_init", $upload);
  129. Config::set('upload', array_merge(Config::get('upload'), $upload));
  130. // 加载当前控制器语言包
  131. $this->loadlang($controllername);
  132. }
  133. /**
  134. * 加载语言文件
  135. * @param string $name
  136. */
  137. protected function loadlang($name)
  138. {
  139. $name = Loader::parseName($name);
  140. Lang::load(APP_PATH . $this->request->module() . '/lang/' . $this->request->langset() . '/' . str_replace('.', '/', $name) . '.php');
  141. }
  142. /**
  143. * 操作成功返回的数据
  144. * @param string $msg 提示信息
  145. * @param mixed $data 要返回的数据
  146. * @param int $code 错误码,默认为1
  147. * @param string $type 输出类型
  148. * @param array $header 发送的 Header 信息
  149. */
  150. protected function success($msg = '', $data = null, $code = 1, $type = null, array $header = [])
  151. {
  152. if($msg == 1){
  153. $msg = 'success';
  154. }
  155. if(empty($msg)){
  156. $msg = '操作成功';
  157. }
  158. $this->result($msg, $data, $code, $type, $header);
  159. }
  160. //find查询出来的结果如果为空数组,强制转换object
  161. protected function success_find($msg = '', $data = null, $code = 1, $type = null, array $header = [])
  162. {
  163. if(empty($msg)){
  164. $msg = '操作成功';
  165. }
  166. if(is_null($data) || $data === []){
  167. $data = (object)[];
  168. }
  169. $this->result($msg, $data, $code, $type, $header);
  170. }
  171. /**
  172. * 操作失败返回的数据
  173. * @param string $msg 提示信息
  174. * @param mixed $data 要返回的数据
  175. * @param int $code 错误码,默认为0
  176. * @param string $type 输出类型
  177. * @param array $header 发送的 Header 信息
  178. */
  179. protected function error($msg = '', $data = null, $code = 0, $type = null, array $header = [])
  180. {
  181. if(empty($msg)){
  182. $msg = __('Invalid parameters');
  183. }
  184. $this->result($msg, $data, $code, $type, $header);
  185. }
  186. /**
  187. * 返回封装后的 API 数据到客户端
  188. * @access protected
  189. * @param mixed $msg 提示信息
  190. * @param mixed $data 要返回的数据
  191. * @param int $code 错误码,默认为0
  192. * @param string $type 输出类型,支持json/xml/jsonp
  193. * @param array $header 发送的 Header 信息
  194. * @return void
  195. * @throws HttpResponseException
  196. */
  197. protected function result($msg, $data = null, $code = 0, $type = null, array $header = [])
  198. {
  199. $result = [
  200. 'code' => $code,
  201. 'msg' => $msg,
  202. 'time' => Request::instance()->server('REQUEST_TIME'),
  203. 'data' => $data,
  204. ];
  205. //日志
  206. $this->request_log_update($result);
  207. // 如果未设置类型则自动判断
  208. $type = $type ? $type : ($this->request->param(config('var_jsonp_handler')) ? 'jsonp' : $this->responseType);
  209. if (isset($header['statuscode'])) {
  210. $code = $header['statuscode'];
  211. unset($header['statuscode']);
  212. } else {
  213. //未设置状态码,根据code值判断
  214. $code = $code >= 1000 || $code < 200 ? 200 : $code;
  215. }
  216. $response = Response::create($result, $type, $code)->header($header);
  217. throw new HttpResponseException($response);
  218. }
  219. /**
  220. * 前置操作
  221. * @access protected
  222. * @param string $method 前置操作方法名
  223. * @param array $options 调用参数 ['only'=>[...]] 或者 ['except'=>[...]]
  224. * @return void
  225. */
  226. protected function beforeAction($method, $options = [])
  227. {
  228. if (isset($options['only'])) {
  229. if (is_string($options['only'])) {
  230. $options['only'] = explode(',', $options['only']);
  231. }
  232. if (!in_array($this->request->action(), $options['only'])) {
  233. return;
  234. }
  235. } elseif (isset($options['except'])) {
  236. if (is_string($options['except'])) {
  237. $options['except'] = explode(',', $options['except']);
  238. }
  239. if (in_array($this->request->action(), $options['except'])) {
  240. return;
  241. }
  242. }
  243. call_user_func([$this, $method]);
  244. }
  245. /**
  246. * 设置验证失败后是否抛出异常
  247. * @access protected
  248. * @param bool $fail 是否抛出异常
  249. * @return $this
  250. */
  251. protected function validateFailException($fail = true)
  252. {
  253. $this->failException = $fail;
  254. return $this;
  255. }
  256. /**
  257. * 验证数据
  258. * @access protected
  259. * @param array $data 数据
  260. * @param string|array $validate 验证器名或者验证规则数组
  261. * @param array $message 提示信息
  262. * @param bool $batch 是否批量验证
  263. * @param mixed $callback 回调方法(闭包)
  264. * @return array|string|true
  265. * @throws ValidateException
  266. */
  267. protected function validate($data, $validate, $message = [], $batch = false, $callback = null)
  268. {
  269. if (is_array($validate)) {
  270. $v = Loader::validate();
  271. $v->rule($validate);
  272. } else {
  273. // 支持场景
  274. if (strpos($validate, '.')) {
  275. list($validate, $scene) = explode('.', $validate);
  276. }
  277. $v = Loader::validate($validate);
  278. !empty($scene) && $v->scene($scene);
  279. }
  280. // 批量验证
  281. if ($batch || $this->batchValidate) {
  282. $v->batch(true);
  283. }
  284. // 设置错误信息
  285. if (is_array($message)) {
  286. $v->message($message);
  287. }
  288. // 使用回调验证
  289. if ($callback && is_callable($callback)) {
  290. call_user_func_array($callback, [$v, &$data]);
  291. }
  292. if (!$v->check($data)) {
  293. if ($this->failException) {
  294. throw new ValidateException($v->getError());
  295. }
  296. return $v->getError();
  297. }
  298. return true;
  299. }
  300. /**
  301. * 刷新Token
  302. */
  303. protected function token()
  304. {
  305. $token = $this->request->param('__token__');
  306. //验证Token
  307. if (!Validate::make()->check(['__token__' => $token], ['__token__' => 'require|token'])) {
  308. $this->error(__('Token verification error'), ['__token__' => $this->request->token()]);
  309. }
  310. //刷新Token
  311. $this->request->token();
  312. }
  313. /*
  314. * api 请求日志
  315. * */
  316. protected function request_log(){
  317. //api_request_log
  318. $modulename = $this->request->module();
  319. $controllername = $this->request->controller();
  320. $actionname = $this->request->action();
  321. $data = [
  322. 'uid' => $this->auth->id,
  323. 'api' => $modulename.'/'.$controllername.'/'.$actionname,
  324. 'params' => json_encode(input()),
  325. 'addtime' => time(),
  326. 'adddatetime' => date('Y-m-d H:i:s'),
  327. 'ip' => request()->ip(),
  328. ];
  329. $request_id = db('api_request_log')->insertGetId($data);
  330. defined('API_REQUEST_ID') or define('API_REQUEST_ID', $request_id);
  331. }
  332. //更新用户活跃
  333. protected function user_active(){
  334. if($this->auth->isLogin()){
  335. db('user_active')->where('user_id',$this->auth->id)->update(['requesttime'=>time()]);
  336. if($this->auth->is_active == 0){
  337. $update['is_active'] = 1;
  338. $update['cityname'] = $this->ip_to_address()['cityname'];
  339. db('user')->where('id',$this->auth->id)->update($update);
  340. $this->auth->setuser('cityname',$update['cityname']);
  341. $this->auth->setuser('is_active',1);
  342. }
  343. }
  344. }
  345. //获取用户是否vip,1是,0否
  346. protected function is_vip($vip_endtime,$vip_level){
  347. $is_vip = 0;
  348. if($vip_endtime > time()){
  349. $is_vip = 1;
  350. if($vip_level == 20){
  351. $is_vip = 2;
  352. }
  353. }
  354. return $is_vip;
  355. }
  356. //ip获取地址
  357. protected function ip_to_address(){
  358. $data = [
  359. 'provincename' => '',
  360. 'cityname' => '',
  361. ];
  362. try{
  363. $ip = request()->ip();
  364. //$ip = '182.37.138.94';
  365. // http协议:http://api.ip138.com/ip/
  366. // https协议:https://api.ip138.com/ip/
  367. $url = 'http://api.ip138.com/ip/?ip='.$ip.'&datatype=jsonp&token=b25bac08734ed80bb3aebffd90dab87a'; //13001877198密码zhang139033
  368. $result = json_decode(curl_get($url),true);
  369. //dump($result);exit;
  370. if(is_array($result) && !empty($result)){
  371. if(isset($result['ret']) && $result['ret'] == 'ok'){
  372. if(isset($result['data']) && is_array($result['data']) && !empty($result['data'])){
  373. if(isset($result['data'][1]) && !empty($result['data'][1])){
  374. $data['provincename'] = $result['data'][1];
  375. }
  376. if(isset($result['data'][2]) && !empty($result['data'][2])){
  377. $data['cityname'] = $result['data'][2];
  378. }
  379. }
  380. }
  381. }
  382. //dump($data);
  383. return $data;
  384. }catch (Exception $e) {
  385. return $data;
  386. }
  387. return $data;
  388. }
  389. protected function request_log_update($log_result){
  390. if(defined('API_REQUEST_ID')) { //记录app正常返回结果
  391. if(strlen(json_encode($log_result['data'])) > 10000) {
  392. $log_result['data'] = '数据太多,不记录';
  393. }
  394. db('api_request_log')->where('id',API_REQUEST_ID)->update(['result'=>json_encode($log_result)]);
  395. }
  396. }
  397. /**
  398. * 接口请求限制
  399. * @param int $apiLimit
  400. * @param int $apiLimitTime 单位:秒(s)
  401. * @param string $key
  402. * @return bool | true:通过 false:拒绝
  403. */
  404. public function apiLimit($apiLimit = 1, $apiLimitTime = 1, $key = '')
  405. {
  406. $userId = $this->auth->id;
  407. $controller = request()->controller();
  408. $action = request()->action();
  409. if (!$key) {
  410. $key = strtolower($controller) . '_' . strtolower($action) . '_' . $userId;
  411. }
  412. if (!RedisUtil::getInstance($key)->tryTimes($apiLimit,intval($apiLimitTime))){
  413. return false;
  414. }
  415. return true;
  416. }
  417. }