Api.php 15 KB

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