Api.php 19 KB

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