Api.php 15 KB

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