Api.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397
  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. /**
  15. * API控制器基类
  16. */
  17. class Api
  18. {
  19. /**
  20. * @var Request Request 实例
  21. */
  22. protected $request;
  23. /**
  24. * @var bool 验证失败是否抛出异常
  25. */
  26. protected $failException = false;
  27. /**
  28. * @var bool 是否批量验证
  29. */
  30. protected $batchValidate = false;
  31. /**
  32. * @var array 前置操作方法列表
  33. */
  34. protected $beforeActionList = [];
  35. /**
  36. * 无需登录的方法,同时也就不需要鉴权了
  37. * @var array
  38. */
  39. protected $noNeedLogin = [];
  40. /**
  41. * 无需鉴权的方法,但需要登录
  42. * @var array
  43. */
  44. protected $noNeedRight = [];
  45. /**
  46. * 权限Auth
  47. * @var Auth
  48. */
  49. protected $auth = null;
  50. /**
  51. * 默认响应输出类型,支持json/xml
  52. * @var string
  53. */
  54. protected $responseType = 'json';
  55. /**
  56. * 构造方法
  57. * @access public
  58. * @param Request $request Request 对象
  59. */
  60. public function __construct(Request $request = null)
  61. {
  62. $this->request = is_null($request) ? Request::instance() : $request;
  63. // 控制器初始化
  64. $this->_initialize();
  65. //日志
  66. $this->request_log();
  67. // 前置操作方法
  68. if ($this->beforeActionList) {
  69. foreach ($this->beforeActionList as $method => $options) {
  70. is_numeric($method) ?
  71. $this->beforeAction($options) :
  72. $this->beforeAction($method, $options);
  73. }
  74. }
  75. }
  76. /**
  77. * 初始化操作
  78. * @access protected
  79. */
  80. protected function _initialize()
  81. {
  82. //跨域请求检测
  83. check_cors_request();
  84. // 检测IP是否允许
  85. check_ip_allowed();
  86. //移除HTML标签
  87. $this->request->filter('trim,strip_tags,htmlspecialchars');
  88. $this->auth = Auth::instance();
  89. $modulename = $this->request->module();
  90. $controllername = Loader::parseName($this->request->controller());
  91. $actionname = strtolower($this->request->action());
  92. // token
  93. $token = $this->request->server('HTTP_TOKEN', $this->request->request('token', \think\Cookie::get('token')));
  94. $path = str_replace('.', '/', $controllername) . '/' . $actionname;
  95. // 设置当前请求的URI
  96. $this->auth->setRequestUri($path);
  97. // 检测是否需要验证登录
  98. if (!$this->auth->match($this->noNeedLogin)) {
  99. //初始化
  100. $this->auth->init($token);
  101. //检测是否登录
  102. if (!$this->auth->isLogin()) {
  103. $this->error(__('Please login first'), null, 401);
  104. }
  105. // 判断是否需要验证权限
  106. if (!$this->auth->match($this->noNeedRight)) {
  107. // 判断控制器和方法判断是否有对应权限
  108. if (!$this->auth->check($path)) {
  109. $this->error(__('You have no permission'), null, 403);
  110. }
  111. }
  112. } else {
  113. // 如果有传递token才验证是否登录状态
  114. if ($token) {
  115. $this->auth->init($token);
  116. }
  117. }
  118. $upload = \app\common\model\Config::upload();
  119. // 上传信息配置后
  120. Hook::listen("upload_config_init", $upload);
  121. Config::set('upload', array_merge(Config::get('upload'), $upload));
  122. // 加载当前控制器语言包
  123. $this->loadlang($controllername);
  124. }
  125. /**
  126. * 加载语言文件
  127. * @param string $name
  128. */
  129. protected function loadlang($name)
  130. {
  131. $name = Loader::parseName($name);
  132. Lang::load(APP_PATH . $this->request->module() . '/lang/' . $this->request->langset() . '/' . str_replace('.', '/', $name) . '.php');
  133. }
  134. /**
  135. * 操作成功返回的数据
  136. * @param string $msg 提示信息
  137. * @param mixed $data 要返回的数据
  138. * @param int $code 错误码,默认为1
  139. * @param string $type 输出类型
  140. * @param array $header 发送的 Header 信息
  141. */
  142. protected function success($msg = '', $data = null, $code = 1, $type = null, array $header = [])
  143. {
  144. if ($data && in_array(request()->action(), ['getUserInfo'])) {
  145. //手机号/微信号 私钥加密
  146. // $private_key = "-----BEGIN RSA PRIVATE KEY-----" .PHP_EOL.
  147. // wordwrap(config('private_key'), 64, PHP_EOL, true) .
  148. // PHP_EOL."-----END RSA PRIVATE KEY-----";
  149. $public_key = "-----BEGIN PUBLIC KEY-----" .PHP_EOL.
  150. wordwrap(config('public_key'), 64, PHP_EOL, true) .
  151. PHP_EOL."-----END PUBLIC KEY-----";
  152. if (isset($data['mobile']) && $data['mobile']) {
  153. $mobile = "";
  154. // openssl_private_encrypt($data['mobile'], $mobile, $private_key); // 使用私钥加密数据
  155. openssl_public_encrypt($data['mobile'], $mobile, $public_key);
  156. $data['mobile'] = base64_encode($mobile);
  157. }
  158. if (isset($data['wechat'])) {
  159. if ($data['wechat']) {
  160. $wechat = "";
  161. // openssl_private_encrypt($data['wechat'], $wechat, $private_key); // 使用私钥加密数据
  162. openssl_public_encrypt($data['wechat'], $wechat, $public_key);
  163. $data['wechat'] = base64_encode($wechat);
  164. } else {
  165. $data['wechat'] = '';
  166. }
  167. }
  168. if (isset($data['wechat_auth'])) {
  169. if ($data['wechat_auth']) {
  170. $wechat_auth = "";
  171. // openssl_private_encrypt($data['wechat_auth'], $wechat_auth, $private_key); // 使用私钥加密数据
  172. openssl_public_encrypt($data['wechat_auth'], $wechat_auth, $public_key);
  173. $data['wechat_auth'] = base64_encode($wechat_auth);
  174. } else {
  175. $data['wechat_auth'] = '';
  176. }
  177. }
  178. }
  179. $this->result($msg, $data, $code, $type, $header);
  180. }
  181. /**
  182. * 操作失败返回的数据
  183. * @param string $msg 提示信息
  184. * @param mixed $data 要返回的数据
  185. * @param int $code 错误码,默认为0
  186. * @param string $type 输出类型
  187. * @param array $header 发送的 Header 信息
  188. */
  189. protected function error($msg = '', $data = null, $code = 0, $type = null, array $header = [])
  190. {
  191. $this->result($msg, $data, $code, $type, $header);
  192. }
  193. /**
  194. * 返回封装后的 API 数据到客户端
  195. * @access protected
  196. * @param mixed $msg 提示信息
  197. * @param mixed $data 要返回的数据
  198. * @param int $code 错误码,默认为0
  199. * @param string $type 输出类型,支持json/xml/jsonp
  200. * @param array $header 发送的 Header 信息
  201. * @return void
  202. * @throws HttpResponseException
  203. */
  204. protected function result($msg, $data = null, $code = 0, $type = null, array $header = [])
  205. {
  206. $result = [
  207. 'code' => $code,
  208. 'msg' => $msg,
  209. 'time' => Request::instance()->server('REQUEST_TIME'),
  210. 'data' => $data,
  211. ];
  212. // 如果未设置类型则自动判断
  213. $type = $type ? $type : ($this->request->param(config('var_jsonp_handler')) ? 'jsonp' : $this->responseType);
  214. if (isset($header['statuscode'])) {
  215. $code = $header['statuscode'];
  216. unset($header['statuscode']);
  217. } else {
  218. //未设置状态码,根据code值判断
  219. $code = $code >= 1000 || $code < 200 ? 200 : $code;
  220. }
  221. $response = Response::create($result, $type, $code)->header($header);
  222. throw new HttpResponseException($response);
  223. }
  224. /**
  225. * 前置操作
  226. * @access protected
  227. * @param string $method 前置操作方法名
  228. * @param array $options 调用参数 ['only'=>[...]] 或者 ['except'=>[...]]
  229. * @return void
  230. */
  231. protected function beforeAction($method, $options = [])
  232. {
  233. if (isset($options['only'])) {
  234. if (is_string($options['only'])) {
  235. $options['only'] = explode(',', $options['only']);
  236. }
  237. if (!in_array($this->request->action(), $options['only'])) {
  238. return;
  239. }
  240. } elseif (isset($options['except'])) {
  241. if (is_string($options['except'])) {
  242. $options['except'] = explode(',', $options['except']);
  243. }
  244. if (in_array($this->request->action(), $options['except'])) {
  245. return;
  246. }
  247. }
  248. call_user_func([$this, $method]);
  249. }
  250. /**
  251. * 设置验证失败后是否抛出异常
  252. * @access protected
  253. * @param bool $fail 是否抛出异常
  254. * @return $this
  255. */
  256. protected function validateFailException($fail = true)
  257. {
  258. $this->failException = $fail;
  259. return $this;
  260. }
  261. /**
  262. * 验证数据
  263. * @access protected
  264. * @param array $data 数据
  265. * @param string|array $validate 验证器名或者验证规则数组
  266. * @param array $message 提示信息
  267. * @param bool $batch 是否批量验证
  268. * @param mixed $callback 回调方法(闭包)
  269. * @return array|string|true
  270. * @throws ValidateException
  271. */
  272. protected function validate($data, $validate, $message = [], $batch = false, $callback = null)
  273. {
  274. if (is_array($validate)) {
  275. $v = Loader::validate();
  276. $v->rule($validate);
  277. } else {
  278. // 支持场景
  279. if (strpos($validate, '.')) {
  280. list($validate, $scene) = explode('.', $validate);
  281. }
  282. $v = Loader::validate($validate);
  283. !empty($scene) && $v->scene($scene);
  284. }
  285. // 批量验证
  286. if ($batch || $this->batchValidate) {
  287. $v->batch(true);
  288. }
  289. // 设置错误信息
  290. if (is_array($message)) {
  291. $v->message($message);
  292. }
  293. // 使用回调验证
  294. if ($callback && is_callable($callback)) {
  295. call_user_func_array($callback, [$v, &$data]);
  296. }
  297. if (!$v->check($data)) {
  298. if ($this->failException) {
  299. throw new ValidateException($v->getError());
  300. }
  301. return $v->getError();
  302. }
  303. return true;
  304. }
  305. /**
  306. * 刷新Token
  307. */
  308. protected function token()
  309. {
  310. $token = $this->request->param('__token__');
  311. //验证Token
  312. if (!Validate::make()->check(['__token__' => $token], ['__token__' => 'require|token'])) {
  313. $this->error(__('Token verification error'), ['__token__' => $this->request->token()]);
  314. }
  315. //刷新Token
  316. $this->request->token();
  317. }
  318. /*
  319. * api 请求日志
  320. * */
  321. protected function request_log(){
  322. //api_request_log
  323. $modulename = $this->request->module();
  324. $controllername = $this->request->controller();
  325. $actionname = $this->request->action();
  326. $data = [
  327. 'uid' => $this->auth->id,
  328. 'api' => $modulename.'/'.$controllername.'/'.$actionname,
  329. 'params' => json_encode($this->request->request()),
  330. 'addtime' => time(),
  331. 'adddatetime' => date('Y-m-d H:i:s'),
  332. 'ip' => request()->ip(),
  333. ];
  334. $request_id = db('api_request_log')->insertGetId($data);
  335. defined('API_REQUEST_ID') or define('API_REQUEST_ID', $request_id);
  336. }
  337. protected function request_log_update($log_result){
  338. if(defined('API_REQUEST_ID')) { //记录app正常返回结果
  339. if(strlen(json_encode($log_result['data'])) > 10000) {
  340. $log_result['data'] = '数据太多,不记录';
  341. }
  342. db('api_request_log')->where('id',API_REQUEST_ID)->update(['result'=>json_encode($log_result)]);
  343. }
  344. }
  345. }