Api.php 18 KB

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