Alipay.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427
  1. <?php
  2. namespace Yansongda\Pay\Gateways;
  3. use Symfony\Component\HttpFoundation\Request;
  4. use Symfony\Component\HttpFoundation\Response;
  5. use Yansongda\Pay\Contracts\GatewayApplicationInterface;
  6. use Yansongda\Pay\Contracts\GatewayInterface;
  7. use Yansongda\Pay\Events;
  8. use Yansongda\Pay\Exceptions\GatewayException;
  9. use Yansongda\Pay\Exceptions\InvalidArgumentException;
  10. use Yansongda\Pay\Exceptions\InvalidConfigException;
  11. use Yansongda\Pay\Exceptions\InvalidGatewayException;
  12. use Yansongda\Pay\Exceptions\InvalidSignException;
  13. use Yansongda\Pay\Gateways\Alipay\Support;
  14. use Yansongda\Supports\Collection;
  15. use Yansongda\Supports\Config;
  16. use Yansongda\Supports\Str;
  17. /**
  18. * @method Response app(array $config) APP 支付
  19. * @method Collection pos(array $config) 刷卡支付
  20. * @method Collection scan(array $config) 扫码支付
  21. * @method Collection transfer(array $config) 帐户转账
  22. * @method Response wap(array $config) 手机网站支付
  23. * @method Response web(array $config) 电脑支付
  24. * @method Collection mini(array $config) 小程序支付
  25. */
  26. class Alipay implements GatewayApplicationInterface
  27. {
  28. /**
  29. * Const mode_normal.
  30. */
  31. const MODE_NORMAL = 'normal';
  32. /**
  33. * Const mode_dev.
  34. */
  35. const MODE_DEV = 'dev';
  36. /**
  37. * Const mode_service.
  38. */
  39. const MODE_SERVICE = 'service';
  40. /**
  41. * Const url.
  42. */
  43. const URL = [
  44. self::MODE_NORMAL => 'https://openapi.alipay.com/gateway.do?charset=utf-8',
  45. self::MODE_DEV => 'https://openapi.alipaydev.com/gateway.do?charset=utf-8',
  46. ];
  47. /**
  48. * Alipay payload.
  49. *
  50. * @var array
  51. */
  52. protected $payload;
  53. /**
  54. * Alipay gateway.
  55. *
  56. * @var string
  57. */
  58. protected $gateway;
  59. /**
  60. * extends.
  61. *
  62. * @var array
  63. */
  64. protected $extends;
  65. /**
  66. * Bootstrap.
  67. *
  68. * @author yansongda <me@yansongda.cn>
  69. *
  70. * @throws \Exception
  71. */
  72. public function __construct(Config $config)
  73. {
  74. $this->gateway = Support::create($config)->getBaseUri();
  75. $this->payload = [
  76. 'app_id' => $config->get('app_id'),
  77. 'method' => '',
  78. 'format' => 'JSON',
  79. 'charset' => 'utf-8',
  80. 'sign_type' => 'RSA2',
  81. 'version' => '1.0',
  82. 'return_url' => $config->get('return_url'),
  83. 'notify_url' => $config->get('notify_url'),
  84. 'timestamp' => date('Y-m-d H:i:s'),
  85. 'sign' => '',
  86. 'biz_content' => '',
  87. 'app_auth_token' => $config->get('app_auth_token'),
  88. ];
  89. if ($config->get('app_cert_public_key') && $config->get('alipay_root_cert')) {
  90. $this->payload['app_cert_sn'] = Support::getCertSN($config->get('app_cert_public_key'));
  91. $this->payload['alipay_root_cert_sn'] = Support::getRootCertSN($config->get('alipay_root_cert'));
  92. }
  93. }
  94. /**
  95. * Magic pay.
  96. *
  97. * @author yansongda <me@yansongda.cn>
  98. *
  99. * @param string $method
  100. * @param array $params
  101. *
  102. * @throws GatewayException
  103. * @throws InvalidArgumentException
  104. * @throws InvalidConfigException
  105. * @throws InvalidGatewayException
  106. * @throws InvalidSignException
  107. *
  108. * @return Response|Collection
  109. */
  110. public function __call($method, $params)
  111. {
  112. if (isset($this->extends[$method])) {
  113. return $this->makeExtend($method, ...$params);
  114. }
  115. return $this->pay($method, ...$params);
  116. }
  117. /**
  118. * Pay an order.
  119. *
  120. * @author yansongda <me@yansongda.cn>
  121. *
  122. * @param string $gateway
  123. * @param array $params
  124. *
  125. * @throws InvalidGatewayException
  126. *
  127. * @return Response|Collection
  128. */
  129. public function pay($gateway, $params = [])
  130. {
  131. Events::dispatch(new Events\PayStarting('Alipay', $gateway, $params));
  132. $this->payload['return_url'] = $params['return_url'] ?? $this->payload['return_url'];
  133. $this->payload['notify_url'] = $params['notify_url'] ?? $this->payload['notify_url'];
  134. unset($params['return_url'], $params['notify_url']);
  135. $this->payload['biz_content'] = json_encode($params);
  136. $method = $gateway;
  137. $gateway = get_class($this).'\\'.Str::studly($gateway).'Gateway';
  138. if (class_exists($gateway)) {
  139. return $this->makePay($gateway,$method);
  140. }
  141. throw new InvalidGatewayException("Pay Gateway [{$gateway}] not exists");
  142. }
  143. /**
  144. * Verify sign.
  145. *
  146. * @author yansongda <me@yansongda.cn>
  147. *
  148. * @param array|null $data
  149. *
  150. * @throws InvalidSignException
  151. * @throws InvalidConfigException
  152. */
  153. public function verify($data = null, bool $refund = false): Collection
  154. {
  155. if (is_null($data)) {
  156. $request = Request::createFromGlobals();
  157. $data = $request->request->count() > 0 ? $request->request->all() : $request->query->all();
  158. }
  159. if (isset($data['fund_bill_list'])) {
  160. $data['fund_bill_list'] = htmlspecialchars_decode($data['fund_bill_list']);
  161. }
  162. Events::dispatch(new Events\RequestReceived('Alipay', '', $data));
  163. if (Support::verifySign($data)) {
  164. return new Collection($data);
  165. }
  166. Events::dispatch(new Events\SignFailed('Alipay', '', $data));
  167. throw new InvalidSignException('Alipay Sign Verify FAILED', $data);
  168. }
  169. /**
  170. * Query an order.
  171. *
  172. * @author yansongda <me@yansongda.cn>
  173. *
  174. * @param string|array $order
  175. *
  176. * @throws GatewayException
  177. * @throws InvalidConfigException
  178. * @throws InvalidSignException
  179. */
  180. public function find($order, string $type = 'wap'): Collection
  181. {
  182. $gateway = get_class($this).'\\'.Str::studly($type).'Gateway';
  183. if (!class_exists($gateway) || !is_callable([new $gateway(), 'find'])) {
  184. throw new GatewayException("{$gateway} Done Not Exist Or Done Not Has FIND Method");
  185. }
  186. $config = call_user_func([new $gateway(), 'find'], $order);
  187. $this->payload['method'] = $config['method'];
  188. $this->payload['biz_content'] = $config['biz_content'];
  189. $this->payload['sign'] = Support::generateSign($this->payload);
  190. Events::dispatch(new Events\MethodCalled('Alipay', 'Find', $this->gateway, $this->payload));
  191. return Support::requestApi($this->payload);
  192. }
  193. /**
  194. * Refund an order.
  195. *
  196. * @author yansongda <me@yansongda.cn>
  197. *
  198. * @throws GatewayException
  199. * @throws InvalidConfigException
  200. * @throws InvalidSignException
  201. */
  202. public function refund(array $order): Collection
  203. {
  204. $this->payload['method'] = 'alipay.trade.refund';
  205. $this->payload['biz_content'] = json_encode($order);
  206. $this->payload['sign'] = Support::generateSign($this->payload);
  207. Events::dispatch(new Events\MethodCalled('Alipay', 'Refund', $this->gateway, $this->payload));
  208. return Support::requestApi($this->payload);
  209. }
  210. /**
  211. * Cancel an order.
  212. *
  213. * @author yansongda <me@yansongda.cn>
  214. *
  215. * @param array|string $order
  216. *
  217. * @throws GatewayException
  218. * @throws InvalidConfigException
  219. * @throws InvalidSignException
  220. */
  221. public function cancel($order): Collection
  222. {
  223. $this->payload['method'] = 'alipay.trade.cancel';
  224. $this->payload['biz_content'] = json_encode(is_array($order) ? $order : ['out_trade_no' => $order]);
  225. $this->payload['sign'] = Support::generateSign($this->payload);
  226. Events::dispatch(new Events\MethodCalled('Alipay', 'Cancel', $this->gateway, $this->payload));
  227. return Support::requestApi($this->payload);
  228. }
  229. /**
  230. * Close an order.
  231. *
  232. * @param string|array $order
  233. *
  234. * @author yansongda <me@yansongda.cn>
  235. *
  236. * @throws GatewayException
  237. * @throws InvalidConfigException
  238. * @throws InvalidSignException
  239. */
  240. public function close($order): Collection
  241. {
  242. $this->payload['method'] = 'alipay.trade.close';
  243. $this->payload['biz_content'] = json_encode(is_array($order) ? $order : ['out_trade_no' => $order]);
  244. $this->payload['sign'] = Support::generateSign($this->payload);
  245. Events::dispatch(new Events\MethodCalled('Alipay', 'Close', $this->gateway, $this->payload));
  246. return Support::requestApi($this->payload);
  247. }
  248. /**
  249. * Download bill.
  250. *
  251. * @author yansongda <me@yansongda.cn>
  252. *
  253. * @param string|array $bill
  254. *
  255. * @throws GatewayException
  256. * @throws InvalidConfigException
  257. * @throws InvalidSignException
  258. */
  259. public function download($bill): string
  260. {
  261. $this->payload['method'] = 'alipay.data.dataservice.bill.downloadurl.query';
  262. $this->payload['biz_content'] = json_encode(is_array($bill) ? $bill : ['bill_type' => 'trade', 'bill_date' => $bill]);
  263. $this->payload['sign'] = Support::generateSign($this->payload);
  264. Events::dispatch(new Events\MethodCalled('Alipay', 'Download', $this->gateway, $this->payload));
  265. $result = Support::requestApi($this->payload);
  266. return ($result instanceof Collection) ? $result->get('bill_download_url') : '';
  267. }
  268. /**
  269. * Reply success to alipay.
  270. *
  271. * @author yansongda <me@yansongda.cn>
  272. */
  273. public function success(): Response
  274. {
  275. Events::dispatch(new Events\MethodCalled('Alipay', 'Success', $this->gateway));
  276. return new Response('success');
  277. }
  278. /**
  279. * extend.
  280. *
  281. * @author yansongda <me@yansongda.cn>
  282. *
  283. * @throws GatewayException
  284. * @throws InvalidConfigException
  285. * @throws InvalidSignException
  286. * @throws InvalidArgumentException
  287. */
  288. public function extend(string $method, callable $function, bool $now = true): ?Collection
  289. {
  290. if (!$now && !method_exists($this, $method)) {
  291. $this->extends[$method] = $function;
  292. return null;
  293. }
  294. $customize = $function($this->payload);
  295. if (!is_array($customize) && !($customize instanceof Collection)) {
  296. throw new InvalidArgumentException('Return Type Must Be Array Or Collection');
  297. }
  298. Events::dispatch(new Events\MethodCalled('Alipay', 'extend', $this->gateway, $customize));
  299. if (is_array($customize)) {
  300. $this->payload = $customize;
  301. $this->payload['sign'] = Support::generateSign($this->payload);
  302. return Support::requestApi($this->payload);
  303. }
  304. return $customize;
  305. }
  306. /**
  307. * Make pay gateway.
  308. *
  309. * @author yansongda <me@yansongda.cn>
  310. *
  311. * @throws InvalidGatewayException
  312. *
  313. * @return Response|Collection
  314. */
  315. protected function makePay(string $gateway, $method = '')
  316. {
  317. $app = new $gateway();
  318. if ($method == 'wap') {
  319. return $app->pay_wap($this->gateway, array_filter($this->payload, function ($value) {
  320. return '' !== $value && !is_null($value);
  321. }));
  322. }
  323. if ($app instanceof GatewayInterface) {
  324. return $app->pay($this->gateway, array_filter($this->payload, function ($value) {
  325. return '' !== $value && !is_null($value);
  326. }));
  327. }
  328. throw new InvalidGatewayException("Pay Gateway [{$gateway}] Must Be An Instance Of GatewayInterface");
  329. }
  330. /**
  331. * makeExtend.
  332. *
  333. * @author yansongda <me@yansongda.cn>
  334. *
  335. * @throws GatewayException
  336. * @throws InvalidArgumentException
  337. * @throws InvalidConfigException
  338. * @throws InvalidSignException
  339. */
  340. protected function makeExtend(string $method, array ...$params): Collection
  341. {
  342. $params = count($params) >= 1 ? $params[0] : $params;
  343. $function = $this->extends[$method];
  344. $customize = $function($this->payload, $params);
  345. if (!is_array($customize) && !($customize instanceof Collection)) {
  346. throw new InvalidArgumentException('Return Type Must Be Array Or Collection');
  347. }
  348. Events::dispatch(new Events\MethodCalled(
  349. 'Alipay',
  350. 'extend - '.$method,
  351. $this->gateway,
  352. is_array($customize) ? $customize : $customize->toArray()
  353. ));
  354. if (is_array($customize)) {
  355. $this->payload = $customize;
  356. $this->payload['sign'] = Support::generateSign($this->payload);
  357. return Support::requestApi($this->payload);
  358. }
  359. return $customize;
  360. }
  361. }