Index.php 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: lts
  5. * Date: 2019-08-08
  6. * Time: 19:53
  7. */
  8. namespace app\clientappapi\controller;
  9. use app\main\constants\ClientApiConstants;
  10. use app\main\service\LogService;
  11. use think\Exception;
  12. use think\Request;
  13. use think\Response;
  14. use think\exception\HttpResponseException;
  15. class Index
  16. {
  17. public function index()
  18. {
  19. $code = Request::instance()->param('code');
  20. if (empty($code)) {
  21. $this->error('没有接口编码');
  22. }
  23. if (empty(ClientApiConstants::APP_PATH_MAPPING[$code])) {
  24. $this->error('没有找到对应的接口,code:' . $code);
  25. }
  26. $apiPath = ClientApiConstants::APP_PATH_MAPPING[$code];
  27. try {
  28. action($apiPath);
  29. } catch (Exception $e) {
  30. LogService::exception($e);
  31. $this->error($e->getMessage());
  32. }
  33. }
  34. /**
  35. * 操作失败返回的数据
  36. * @param string $msg 提示信息
  37. * @param int $code 错误代码
  38. * @param mixed $data 要返回的数据
  39. * @param array $header 发送的 Header 信息
  40. */
  41. protected function error(
  42. $msg = '',
  43. $code = ClientApiConstants::CLIENT_API_CODE_FAIL,
  44. $data = [],
  45. array $header = []
  46. ) {
  47. if (empty($msg)) {
  48. if (isset(ClientApiConstants::$errMsgList[$code])) {
  49. $msg = ClientApiConstants::$errMsgList[$code];
  50. }
  51. }
  52. $result = [
  53. 'code' => $code,
  54. 'msg' => $msg,
  55. 'time' => Request::instance()->server('REQUEST_TIME'),
  56. 'data' => $data,
  57. ];
  58. if (empty($result['data'])) {
  59. $result['data'] = new \ArrayObject(array());
  60. }
  61. $response = Response::create($result, 'json')->header($header);
  62. throw new HttpResponseException($response);
  63. }
  64. }