Api.php 15 KB

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