Api.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652
  1. <?php
  2. namespace app\common\controller;
  3. use app\common\library\Auth;
  4. use app\utils\LogUtil;
  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. /**
  58. * @var int 日志类型 1 文件;2sql
  59. */
  60. public $logType = 2;
  61. /**
  62. * 构造方法
  63. * @access public
  64. * @param Request $request Request 对象
  65. */
  66. public function __construct(Request $request = null)
  67. {
  68. $this->request = is_null($request) ? Request::instance() : $request;
  69. if(config('site.apisite_switch') == 0){
  70. $notice = config('site.apisite_notice') ?: '全站维护中';
  71. $this->error($notice);
  72. }
  73. // 验签
  74. //$this->apiverifysign();
  75. // 控制器初始化
  76. $this->_initialize();
  77. //日志
  78. $this->request_log();
  79. //用户活跃
  80. $this->user_active();
  81. // 前置操作方法
  82. if ($this->beforeActionList) {
  83. foreach ($this->beforeActionList as $method => $options) {
  84. is_numeric($method) ?
  85. $this->beforeAction($options) :
  86. $this->beforeAction($method, $options);
  87. }
  88. }
  89. }
  90. //验签,2048位,265截取
  91. public function apiverifysign(){
  92. /*$ip = request()->ip();
  93. if($ip == '127.0.0.1'){
  94. return true;
  95. }*/
  96. //$modulename = $this->request->module();
  97. //$controllername = $this->request->controller();
  98. $actionname = $this->request->action();
  99. if (in_array($actionname,['upload','uploads','recognizingsounds','alipaynotify','trtc_callback','callback'])) {
  100. return true;
  101. }
  102. //解密签名开始
  103. $sign = $this->request->request('sign','','trim');
  104. if(empty($sign)){
  105. $this->error('缺少签名');
  106. }
  107. $sign = base64_decode($sign);
  108. $private_key_str = config('app_rsa.private_key');
  109. $private_key = "-----BEGIN RSA PRIVATE KEY-----" .PHP_EOL.
  110. wordwrap($private_key_str, 64, PHP_EOL, true) .
  111. PHP_EOL."-----END RSA PRIVATE KEY-----";
  112. $signgetdata = []; //被解密出来的数据
  113. $split_len = 256;
  114. $sign_split = str_split($sign, $split_len);
  115. foreach($sign_split as $key => $sign_val){
  116. $signgetdata_child = null;
  117. openssl_private_decrypt($sign_val, $signgetdata_child, $private_key); // 使用私钥解密数据
  118. $signgetdata[] = $signgetdata_child;
  119. }
  120. $signgetdata = implode('',$signgetdata);
  121. if (!$signgetdata) {
  122. $this->error('签名错误1');
  123. }
  124. //dump($signgetdata);
  125. //解密签名结束
  126. //接收到的参数,组成我自己的验签体string
  127. $request_all = $this->request->request();
  128. unset($request_all['s']);
  129. unset($request_all['sign']);
  130. ksort($request_all);
  131. $request_str = '';
  132. foreach($request_all as $key => $param){
  133. $request_str .= $key.'='.$param.'&';
  134. }
  135. $request_str .= 'signkey=F_dC923_35270PdsIIUIUTRERYTYYU';
  136. //dump($request_str);
  137. //作对比
  138. if($request_str != $signgetdata){
  139. $this->error('验签错误');
  140. }
  141. //echo '验签正确';
  142. return true;
  143. }
  144. /**
  145. * 初始化操作
  146. * @access protected
  147. */
  148. protected function _initialize()
  149. {
  150. //跨域请求检测
  151. check_cors_request();
  152. // 检测IP是否允许
  153. // check_ip_allowed();
  154. //移除HTML标签
  155. $this->request->filter('trim,strip_tags,htmlspecialchars');
  156. $this->auth = Auth::instance();
  157. $modulename = $this->request->module();
  158. $controllername = Loader::parseName($this->request->controller());
  159. $actionname = strtolower($this->request->action());
  160. // token
  161. $token = $this->request->server('HTTP_TOKEN', $this->request->request('token', \think\Cookie::get('token')));
  162. $path = str_replace('.', '/', $controllername) . '/' . $actionname;
  163. // 设置当前请求的URI
  164. $this->auth->setRequestUri($path);
  165. // 检测是否需要验证登录
  166. if (!$this->auth->match($this->noNeedLogin)) {
  167. //初始化
  168. $this->auth->init($token);
  169. //检测是否登录
  170. if (!$this->auth->isLogin()) {
  171. $this->error(__('Please login first'), null, 401);
  172. }
  173. // 判断是否需要验证权限
  174. /*if (!$this->auth->match($this->noNeedRight)) {
  175. // 判断控制器和方法判断是否有对应权限
  176. if (!$this->auth->check($path)) {
  177. $this->error(__('You have no permission'), null, 403);
  178. }
  179. }*/
  180. } else {
  181. // 如果有传递token才验证是否登录状态
  182. if ($token) {
  183. $this->auth->init($token);
  184. //传就必须传对
  185. if (!$this->auth->isLogin()) {
  186. $this->error(__('Please login first'), null, 401);
  187. }
  188. }
  189. }
  190. $upload = \app\common\model\Config::upload();
  191. // 上传信息配置后
  192. Hook::listen("upload_config_init", $upload);
  193. Config::set('upload', array_merge(Config::get('upload'), $upload));
  194. // 加载当前控制器语言包
  195. $this->loadlang($controllername);
  196. }
  197. /**
  198. * 加载语言文件
  199. * @param string $name
  200. */
  201. protected function loadlang($name)
  202. {
  203. $name = Loader::parseName($name);
  204. Lang::load(APP_PATH . $this->request->module() . '/lang/' . $this->request->langset() . '/' . str_replace('.', '/', $name) . '.php');
  205. }
  206. /**
  207. * 操作成功返回的数据
  208. * @param string $msg 提示信息
  209. * @param mixed $data 要返回的数据
  210. * @param int $code 错误码,默认为1
  211. * @param string $type 输出类型
  212. * @param array $header 发送的 Header 信息
  213. */
  214. protected function success($msg = '', $data = null, $code = 1, $type = null, array $header = [])
  215. {
  216. if($msg == 1){
  217. $msg = 'success';
  218. }
  219. if(empty($msg)){
  220. $msg = '操作成功';
  221. }
  222. $this->result($msg, $data, $code, $type, $header);
  223. }
  224. //find查询出来的结果如果为空数组,强制转换object
  225. protected function success_find($msg = '', $data = null, $code = 1, $type = null, array $header = [])
  226. {
  227. if(empty($msg)){
  228. $msg = '操作成功';
  229. }
  230. if(is_null($data) || $data === []){
  231. $data = (object)[];
  232. }
  233. $this->result($msg, $data, $code, $type, $header);
  234. }
  235. /**
  236. * 操作失败返回的数据
  237. * @param string $msg 提示信息
  238. * @param mixed $data 要返回的数据
  239. * @param int $code 错误码,默认为0
  240. * @param string $type 输出类型
  241. * @param array $header 发送的 Header 信息
  242. */
  243. protected function error($msg = '', $data = null, $code = 0, $type = null, array $header = [])
  244. {
  245. if(empty($msg)){
  246. $msg = __('Invalid parameters');
  247. }
  248. $this->result($msg, $data, $code, $type, $header);
  249. }
  250. /**
  251. * 返回封装后的 API 数据到客户端
  252. * @access protected
  253. * @param mixed $msg 提示信息
  254. * @param mixed $data 要返回的数据
  255. * @param int $code 错误码,默认为0
  256. * @param string $type 输出类型,支持json/xml/jsonp
  257. * @param array $header 发送的 Header 信息
  258. * @return void
  259. * @throws HttpResponseException
  260. */
  261. protected function result($msg, $data = null, $code = 0, $type = null, array $header = [])
  262. {
  263. $result = [
  264. 'code' => $code,
  265. 'msg' => $msg,
  266. 'time' => Request::instance()->server('REQUEST_TIME'),
  267. 'data' => $data,
  268. ];
  269. //日志
  270. $this->request_log_update($result);
  271. // 如果未设置类型则自动判断
  272. $type = $type ? $type : ($this->request->param(config('var_jsonp_handler')) ? 'jsonp' : $this->responseType);
  273. if (isset($header['statuscode'])) {
  274. $code = $header['statuscode'];
  275. unset($header['statuscode']);
  276. } else {
  277. //未设置状态码,根据code值判断
  278. $code = $code >= 1000 || $code < 200 ? 200 : $code;
  279. }
  280. $response = Response::create($result, $type, $code)->header($header);
  281. throw new HttpResponseException($response);
  282. }
  283. /**
  284. * 前置操作
  285. * @access protected
  286. * @param string $method 前置操作方法名
  287. * @param array $options 调用参数 ['only'=>[...]] 或者 ['except'=>[...]]
  288. * @return void
  289. */
  290. protected function beforeAction($method, $options = [])
  291. {
  292. if (isset($options['only'])) {
  293. if (is_string($options['only'])) {
  294. $options['only'] = explode(',', $options['only']);
  295. }
  296. if (!in_array($this->request->action(), $options['only'])) {
  297. return;
  298. }
  299. } elseif (isset($options['except'])) {
  300. if (is_string($options['except'])) {
  301. $options['except'] = explode(',', $options['except']);
  302. }
  303. if (in_array($this->request->action(), $options['except'])) {
  304. return;
  305. }
  306. }
  307. call_user_func([$this, $method]);
  308. }
  309. /**
  310. * 设置验证失败后是否抛出异常
  311. * @access protected
  312. * @param bool $fail 是否抛出异常
  313. * @return $this
  314. */
  315. protected function validateFailException($fail = true)
  316. {
  317. $this->failException = $fail;
  318. return $this;
  319. }
  320. /**
  321. * 验证数据
  322. * @access protected
  323. * @param array $data 数据
  324. * @param string|array $validate 验证器名或者验证规则数组
  325. * @param array $message 提示信息
  326. * @param bool $batch 是否批量验证
  327. * @param mixed $callback 回调方法(闭包)
  328. * @return array|string|true
  329. * @throws ValidateException
  330. */
  331. protected function validate($data, $validate, $message = [], $batch = false, $callback = null)
  332. {
  333. if (is_array($validate)) {
  334. $v = Loader::validate();
  335. $v->rule($validate);
  336. } else {
  337. // 支持场景
  338. if (strpos($validate, '.')) {
  339. list($validate, $scene) = explode('.', $validate);
  340. }
  341. $v = Loader::validate($validate);
  342. !empty($scene) && $v->scene($scene);
  343. }
  344. // 批量验证
  345. if ($batch || $this->batchValidate) {
  346. $v->batch(true);
  347. }
  348. // 设置错误信息
  349. if (is_array($message)) {
  350. $v->message($message);
  351. }
  352. // 使用回调验证
  353. if ($callback && is_callable($callback)) {
  354. call_user_func_array($callback, [$v, &$data]);
  355. }
  356. if (!$v->check($data)) {
  357. if ($this->failException) {
  358. throw new ValidateException($v->getError());
  359. }
  360. return $v->getError();
  361. }
  362. return true;
  363. }
  364. /**
  365. * 刷新Token
  366. */
  367. protected function token()
  368. {
  369. $token = $this->request->param('__token__');
  370. //验证Token
  371. if (!Validate::make()->check(['__token__' => $token], ['__token__' => 'require|token'])) {
  372. $this->error(__('Token verification error'), ['__token__' => $this->request->token()]);
  373. }
  374. //刷新Token
  375. $this->request->token();
  376. }
  377. /**
  378. * 接口请求限制
  379. * @param int $apiLimit
  380. * @param int $apiLimitTime
  381. * @param string $key
  382. * @return bool | true:通过 false:拒绝
  383. */
  384. public function apiLimit($apiLimit = 1, $apiLimitTime = 1000, $key = '')
  385. {
  386. $userId = $this->auth->id;
  387. $controller = request()->controller();
  388. $action = request()->action();
  389. if (!$key) {
  390. $key = strtolower($controller) . '_' . strtolower($action) . '_' . $userId;
  391. }
  392. $redis = new Redis();
  393. $redisconfig = config("redis");
  394. $redis->connect($redisconfig["host"], $redisconfig["port"]);
  395. if ($redisconfig['redis_pwd']) {
  396. $redis->auth($redisconfig['redis_pwd']);
  397. }
  398. if($redisconfig['redis_selectdb'] > 0){
  399. $redis->select($redisconfig['redis_selectdb']);
  400. }
  401. //
  402. //指定键值新增+1 并获取
  403. $count = $redis->incr($key);
  404. if ($count > $apiLimit) {
  405. return false;
  406. }
  407. //设置过期时间
  408. if ($count == 1) {
  409. $redis->pExpire($key, $apiLimitTime);
  410. }
  411. return true;
  412. }
  413. /*
  414. * api 请求日志
  415. * */
  416. protected function request_log(){
  417. //api_request_log
  418. $modulename = $this->request->module();
  419. $controllername = $this->request->controller();
  420. $actionname = $this->request->action();
  421. if(strtolower($actionname) == 'callback'){
  422. return true;
  423. }
  424. defined('API_REQUEST_LOG_TYPE') or define('API_REQUEST_LOG_TYPE', $this->logType);
  425. $params = $this->request->request();
  426. if ($this->logType === 1){
  427. //日志统一写入
  428. register_shutdown_function([new LogUtil, 'close']);
  429. LogUtil::getInstance('Api/'); //设置日志存入通道
  430. LogUtil::info('uid', 'Api-Middleware-Log', 'request_log', $this->auth->id);
  431. LogUtil::info('url', 'Api-Middleware-Log', 'request_log', $modulename . '/' . $controllername . '/' . $actionname);
  432. LogUtil::info('params', 'Api-Middleware-Log', 'request_log', $params);
  433. LogUtil::info('ip', 'Api-Middleware-Log', 'request_log', request()->ip());
  434. }else{
  435. $data = [
  436. 'uid' => $this->auth->id,
  437. 'api' => $modulename.'/'.$controllername.'/'.$actionname,
  438. 'params' => json_encode($params),
  439. 'addtime' => time(),
  440. 'adddatetime' => date('Y-m-d H:i:s'),
  441. 'ip' => request()->ip(),
  442. ];
  443. $request_id = db('api_request_log')->insertGetId($data);
  444. defined('API_REQUEST_ID') or define('API_REQUEST_ID', $request_id);
  445. }
  446. }
  447. protected function request_log_update($log_result){
  448. $actionname = $this->request->action();
  449. if(strtolower($actionname) == 'givegifttoyou'){
  450. //return true;
  451. }
  452. if ($this->logType === 1){
  453. if (strlen(json_encode($log_result['data'])) > 1000) {
  454. $log_result['data'] = '数据太多,不记录';
  455. }
  456. LogUtil::info('result', 'Api-Middleware-Log', 'request_log', $log_result);
  457. }else{
  458. if(defined('API_REQUEST_ID')) { //记录app正常返回结果
  459. if(strlen(json_encode($log_result['data'])) > 1000) {
  460. $log_result['data'] = '数据太多,不记录';
  461. }
  462. db('api_request_log')->where('id',API_REQUEST_ID)->update(['result'=>json_encode($log_result)]);
  463. }
  464. }
  465. }
  466. //更新用户活跃
  467. protected function user_active(){
  468. if($this->auth->isLogin()){
  469. db('user_active')->where('user_id',$this->auth->id)->update(['requesttime'=>time()]);
  470. }
  471. }
  472. //获取用户是否活跃,7200秒,2小时
  473. //1活跃,0不活跃
  474. protected function user_activeinfo($user_id,$requesttime = 0){
  475. if(empty($requesttime)){
  476. $requesttime = db('user_active')->where('user_id',$user_id)->value('requesttime');
  477. }
  478. $result = [
  479. 'is_active' => 1,
  480. 'active_text' => get_last_time($requesttime).'在线',
  481. ];
  482. if(time() - $requesttime > 7200){
  483. $result = [
  484. 'is_active' => 0,
  485. 'active_text' => '离线',
  486. ];
  487. }
  488. return $result;
  489. }
  490. //获取用户是否vip,1是,0否
  491. protected function is_vip($user_id){
  492. $result = 0;
  493. $vip_endtime = db('user_wallet')->where('user_id',$user_id)->value('vip_endtime');
  494. $result = $vip_endtime > time() ? 1 : 0;
  495. return $result;
  496. }
  497. //用户是否有某项权限
  498. //1有,0没有
  499. protected function user_power($user_id,$power = ''){
  500. $is_vip = $this->is_vip($user_id);
  501. if($is_vip != 1){
  502. return 0;
  503. }
  504. $power = db('user_power')->where('user_id',$user_id)->value($power);
  505. return $power;
  506. }
  507. //是否关注
  508. protected function is_follow($uid,$follow_uid){
  509. $where = [
  510. 'uid' => $uid,
  511. 'follow_uid' => $follow_uid,
  512. ];
  513. $check = db('user_follow')->where($where)->find();
  514. if($check){
  515. return 1;
  516. }else{
  517. return 0;
  518. }
  519. }
  520. //是否拉黑
  521. protected function is_black($uid,$black_user_id){
  522. $where = [
  523. 'user_id' => $uid,
  524. 'black_user_id' => $black_user_id,
  525. ];
  526. $check = db('user_blacklist')->where($where)->find();
  527. if($check){
  528. return 1;
  529. }else{
  530. return 0;
  531. }
  532. }
  533. //是否好友
  534. protected function is_friend($uid,$follow_uid){
  535. $is_follow = $this->is_follow($uid,$follow_uid);
  536. $be_follow = $this->is_follow($follow_uid,$uid);
  537. if($is_follow && $be_follow){
  538. return 1;
  539. }
  540. return 0;
  541. }
  542. // 返回执行日期所在周的第一天(周一)日期
  543. public function firstOfWeek($date) {
  544. $now = strtotime($date); //当时的时间戳
  545. $number = date("w",$now); //当时是周几
  546. $number = $number == 0 ? 7 : $number; //如遇周末,将0换成7
  547. $diff_day = $number - 1; //求到周一差几天
  548. return date("Ymd",$now - ($diff_day * 60 * 60 * 24));
  549. }
  550. }