Api.php 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  1. <?php
  2. namespace app\common\controller;
  3. use app\common\library\Ua;
  4. use app\common\library\User;
  5. use app\main\constants\ErrorCodeConstants;
  6. use app\main\constants\OpenPlatformConstants;
  7. use app\main\constants\UrlConstants;
  8. use app\main\helper\ArrayHelper;
  9. use app\main\service\LogService;
  10. use app\main\service\OpenPlatformService;
  11. use app\main\service\UrlService;
  12. use app\main\service\UserService;
  13. use think\Config;
  14. use think\Cookie;
  15. use think\exception\HttpResponseException;
  16. use think\exception\ValidateException;
  17. use think\Lang;
  18. use think\Loader;
  19. use think\Log;
  20. use think\Request;
  21. use think\Response;
  22. /**
  23. * API控制器基类
  24. */
  25. class Api
  26. {
  27. const PAY_CALLBACK_PREFIX = 'callback';
  28. // const PALM_PAY_URL = 'https://pay.palmpay.cn/sdkServer/thirdpays/pay/WECHAT_SUB';
  29. //
  30. // const JOIN_PAY_URL = 'https://www.joinpay.com/trade/uniPayApi.action';
  31. //
  32. // const MIHUA_PAY_URL = 'http://paytest.mihuajinfu.com/paygateway/mbpay/order/v1';
  33. //
  34. // const JOIN_PAY_VERSION = '1.0';
  35. //
  36. // const PALM_PAY_VERSION = '3.0';
  37. //
  38. // const JOIN_PAY_TYPE = 'WEIXIN_GZH';
  39. /**
  40. * @var Request Request 实例
  41. */
  42. protected $request;
  43. /**
  44. * @var bool 验证失败是否抛出异常
  45. */
  46. protected $failException = false;
  47. /**
  48. * @var bool 是否批量验证
  49. */
  50. protected $batchValidate = false;
  51. /**
  52. * 微信内需登录的方法
  53. * @var array
  54. */
  55. protected $wxNeedLogin = [];
  56. /**
  57. * 浏览器需要强登录方法
  58. * @var array
  59. */
  60. protected $browserNeedLogin = [];
  61. /**
  62. * 前台用户系统
  63. * @var UserService
  64. */
  65. protected $user = null;
  66. /**
  67. * 当前url访问类型 0未识别 1后台首页 2支付页 3推广页
  68. * @var int
  69. */
  70. protected $urlType = 0;
  71. /**
  72. * 当前访问链接隶属于哪个渠道商/代理商
  73. * @var null
  74. */
  75. protected $urlAdminId = null;
  76. protected $urlChannelId = null;
  77. protected $urlAgentId = null;
  78. protected $sourceDomain = null;
  79. /**
  80. * @var int 当前请求时间戳
  81. */
  82. protected $time = null;
  83. /**
  84. * 支付域名全局变量
  85. */
  86. protected $currentPayHost = null;
  87. /**
  88. * 构造方法
  89. * @access public
  90. * @param Request $request Request 对象
  91. */
  92. public function __construct(Request $request = null)
  93. {
  94. LogService::info("REQUEST_TIME_START:".microtime(true));
  95. $this->request = is_null($request) ? Request::instance() : $request;
  96. if (!in_array(UrlService::instance()->getActionUrl(), UrlConstants::$ignoreCallbackInitialize)) {
  97. // 控制器初始化
  98. $this->_initialize();
  99. }
  100. }
  101. /**
  102. * 初始化操作
  103. * @access protected
  104. */
  105. protected function _initialize()
  106. {
  107. $this->time = $this->request->server('REQUEST_TIME');
  108. UserService::instance()->getRunTimeObject()->requestTime = $this->time;
  109. $result = UrlService::instance()->checkApiDomain();
  110. if($result->code != ErrorCodeConstants::SUCCESS){
  111. $this->error($result->msg);
  112. }
  113. $runtime = UserService::instance()->getRunTimeObject();
  114. $this->currentPayHost = $runtime->currentPayHost;
  115. $this->urlType = $runtime->urlType;
  116. $this->urlAdminId = $runtime->adminId;
  117. $this->urlAgentId = $runtime->agentId;
  118. $this->urlChannelId = $runtime->channelId;
  119. $this->sourceDomain = $runtime->sourceDomain;
  120. /**
  121. * 用户权限判断
  122. */
  123. $this->user = UserService::instance();
  124. if (!OpenPlatformService::instance()->getOpenPlatform()) {
  125. $this->error('平台配置有误');
  126. }
  127. OpenPlatformService::instance()->setSourceDomain($this->sourceDomain);
  128. if (Ua::isWeiXin()) { // 微信内
  129. //检测是否需要验证登录 && 检测是否登录
  130. if (UrlService::instance()->checkActionMatch(OpenPlatformConstants::WEXIN_NEED_LOGIN) && !$this->user->isLogin()) {
  131. $this->error('未登录');
  132. }
  133. } else { // 其他(浏览器)
  134. if (UrlService::instance()->checkActionMatch(OpenPlatformConstants::BROWSER_NEED_LOGIN) && !$this->user->isLogin()) {
  135. $this->error('未登录');
  136. }
  137. }
  138. }
  139. /**
  140. * 加载语言文件
  141. * @param string $name
  142. */
  143. protected function loadlang($name)
  144. {
  145. Lang::load(APP_PATH . $this->request->module() . '/lang/' . Lang::detect() . '/' . str_replace('.', '/', $name) . '.php');
  146. }
  147. /**
  148. * 操作成功返回的数据
  149. * @param string $msg 提示信息
  150. * @param mixed $data 要返回的数据
  151. * @param string $type 输出类型
  152. * @param array $header 发送的 Header 信息
  153. */
  154. protected function success($msg = '', $data = '', $type = 'json', array $header = [])
  155. {
  156. $this->result($data, 1, $msg, $type, $header);
  157. }
  158. /**
  159. * 操作失败返回的数据
  160. * @param string $msg 提示信息
  161. * @param mixed $data 要返回的数据
  162. * @param string $type 输出类型
  163. * @param array $header 发送的 Header 信息
  164. */
  165. protected function error($msg = '', $data = '', $type = 'json', array $header = [])
  166. {
  167. $this->result($data, 0, $msg, $type, $header);
  168. }
  169. /**
  170. * 返回封装后的 API 数据到客户端
  171. * @access protected
  172. * @param mixed $data 要返回的数据
  173. * @param int $code 返回的 code
  174. * @param mixed $msg 提示信息
  175. * @param string $type 返回数据格式
  176. * @param array $header 发送的 Header 信息
  177. * @return void
  178. * @throws HttpResponseException
  179. */
  180. protected function result($data, $code = 0, $msg = '', $type = '', array $header = [])
  181. {
  182. $result = [
  183. 'code' => $code,
  184. 'msg' => $msg,
  185. 'time' => Request::instance()->server('REQUEST_TIME'),
  186. 'data' => $data,
  187. ];
  188. $type = $type ?: $this->getResponseType();
  189. $response = Response::create($result, $type)->header($header);
  190. throw new HttpResponseException($response);
  191. }
  192. /**
  193. * 未找到请求的接口
  194. */
  195. public function _empty()
  196. {
  197. return $this->error('Api not found');
  198. }
  199. /**
  200. * 前置操作
  201. * @access protected
  202. * @param string $method 前置操作方法名
  203. * @param array $options 调用参数 ['only'=>[...]] 或者 ['except'=>[...]]
  204. * @return void
  205. */
  206. protected function beforeAction($method, $options = [])
  207. {
  208. if (isset($options['only']))
  209. {
  210. if (is_string($options['only']))
  211. {
  212. $options['only'] = explode(',', $options['only']);
  213. }
  214. if (!in_array($this->request->action(), $options['only']))
  215. {
  216. return;
  217. }
  218. }
  219. elseif (isset($options['except']))
  220. {
  221. if (is_string($options['except']))
  222. {
  223. $options['except'] = explode(',', $options['except']);
  224. }
  225. if (in_array($this->request->action(), $options['except']))
  226. {
  227. return;
  228. }
  229. }
  230. call_user_func([$this, $method]);
  231. }
  232. /**
  233. * 设置验证失败后是否抛出异常
  234. * @access protected
  235. * @param bool $fail 是否抛出异常
  236. * @return $this
  237. */
  238. protected function validateFailException($fail = true)
  239. {
  240. $this->failException = $fail;
  241. return $this;
  242. }
  243. /**
  244. * 验证数据
  245. * @access protected
  246. * @param array $data 数据
  247. * @param string|array $validate 验证器名或者验证规则数组
  248. * @param array $message 提示信息
  249. * @param bool $batch 是否批量验证
  250. * @param mixed $callback 回调方法(闭包)
  251. * @return array|string|true
  252. * @throws ValidateException
  253. */
  254. protected function validate($data, $validate, $message = [], $batch = false, $callback = null)
  255. {
  256. if (is_array($validate))
  257. {
  258. $v = Loader::validate();
  259. $v->rule($validate);
  260. }
  261. else
  262. {
  263. // 支持场景
  264. if (strpos($validate, '.'))
  265. {
  266. list($validate, $scene) = explode('.', $validate);
  267. }
  268. $v = Loader::validate($validate);
  269. !empty($scene) && $v->scene($scene);
  270. }
  271. // 批量验证
  272. if ($batch || $this->batchValidate)
  273. $v->batch(true);
  274. // 设置错误信息
  275. if (is_array($message))
  276. $v->message($message);
  277. // 使用回调验证
  278. if ($callback && is_callable($callback))
  279. {
  280. call_user_func_array($callback, [$v, &$data]);
  281. }
  282. if (!$v->check($data))
  283. {
  284. if ($this->failException)
  285. {
  286. throw new ValidateException($v->getError());
  287. }
  288. return $v->getError();
  289. }
  290. return true;
  291. }
  292. }