Alipay.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423
  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_SERVICE => 'https://openapi.alipay.com/gateway.do?charset=utf-8',
  46. self::MODE_DEV => 'https://openapi-sandbox.dl.alipaydev.com/gateway.do?charset=utf-8',
  47. ];
  48. /**
  49. * Alipay payload.
  50. *
  51. * @var array
  52. */
  53. protected $payload;
  54. /**
  55. * Alipay gateway.
  56. *
  57. * @var string
  58. */
  59. protected $gateway;
  60. /**
  61. * extends.
  62. *
  63. * @var array
  64. */
  65. protected $extends;
  66. /**
  67. * Bootstrap.
  68. *
  69. * @author yansongda <me@yansongda.cn>
  70. *
  71. * @throws \Exception
  72. */
  73. public function __construct(Config $config)
  74. {
  75. $this->gateway = Support::create($config)->getBaseUri();
  76. $this->payload = [
  77. 'app_id' => $config->get('app_id'),
  78. 'method' => '',
  79. 'format' => 'JSON',
  80. 'charset' => 'utf-8',
  81. 'sign_type' => 'RSA2',
  82. 'version' => '1.0',
  83. 'return_url' => $config->get('return_url'),
  84. 'notify_url' => $config->get('notify_url'),
  85. 'timestamp' => date('Y-m-d H:i:s'),
  86. 'sign' => '',
  87. 'biz_content' => '',
  88. 'app_auth_token' => $config->get('app_auth_token'),
  89. ];
  90. if ($config->get('app_cert_public_key') && $config->get('alipay_root_cert')) {
  91. $this->payload['app_cert_sn'] = Support::getCertSN($config->get('app_cert_public_key'));
  92. $this->payload['alipay_root_cert_sn'] = Support::getRootCertSN($config->get('alipay_root_cert'));
  93. }
  94. }
  95. /**
  96. * Magic pay.
  97. *
  98. * @author yansongda <me@yansongda.cn>
  99. *
  100. * @param string $method
  101. * @param array $params
  102. *
  103. * @throws GatewayException
  104. * @throws InvalidArgumentException
  105. * @throws InvalidConfigException
  106. * @throws InvalidGatewayException
  107. * @throws InvalidSignException
  108. *
  109. * @return Response|Collection
  110. */
  111. public function __call($method, $params)
  112. {
  113. if (isset($this->extends[$method])) {
  114. return $this->makeExtend($method, ...$params);
  115. }
  116. return $this->pay($method, ...$params);
  117. }
  118. /**
  119. * Pay an order.
  120. *
  121. * @author yansongda <me@yansongda.cn>
  122. *
  123. * @param string $gateway
  124. * @param array $params
  125. *
  126. * @throws InvalidGatewayException
  127. *
  128. * @return Response|Collection
  129. */
  130. public function pay($gateway, $params = [])
  131. {
  132. Events::dispatch(new Events\PayStarting('Alipay', $gateway, $params));
  133. $this->payload['return_url'] = $params['return_url'] ?? $this->payload['return_url'];
  134. $this->payload['notify_url'] = $params['notify_url'] ?? $this->payload['notify_url'];
  135. unset($params['return_url'], $params['notify_url']);
  136. $this->payload['biz_content'] = json_encode($params);
  137. $gateway = get_class($this).'\\'.Str::studly($gateway).'Gateway';
  138. if (class_exists($gateway)) {
  139. return $this->makePay($gateway);
  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)
  316. {
  317. $app = new $gateway();
  318. if ($app instanceof GatewayInterface) {
  319. return $app->pay($this->gateway, array_filter($this->payload, function ($value) {
  320. return '' !== $value && !is_null($value);
  321. }));
  322. }
  323. throw new InvalidGatewayException("Pay Gateway [{$gateway}] Must Be An Instance Of GatewayInterface");
  324. }
  325. /**
  326. * makeExtend.
  327. *
  328. * @author yansongda <me@yansongda.cn>
  329. *
  330. * @throws GatewayException
  331. * @throws InvalidArgumentException
  332. * @throws InvalidConfigException
  333. * @throws InvalidSignException
  334. */
  335. protected function makeExtend(string $method, array ...$params): Collection
  336. {
  337. $params = count($params) >= 1 ? $params[0] : $params;
  338. $function = $this->extends[$method];
  339. $customize = $function($this->payload, $params);
  340. if (!is_array($customize) && !($customize instanceof Collection)) {
  341. throw new InvalidArgumentException('Return Type Must Be Array Or Collection');
  342. }
  343. Events::dispatch(new Events\MethodCalled(
  344. 'Alipay',
  345. 'extend - '.$method,
  346. $this->gateway,
  347. is_array($customize) ? $customize : $customize->toArray()
  348. ));
  349. if (is_array($customize)) {
  350. $this->payload = $customize;
  351. $this->payload['sign'] = Support::generateSign($this->payload);
  352. return Support::requestApi($this->payload);
  353. }
  354. return $customize;
  355. }
  356. }