Alipay.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422
  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. $gateway = get_class($this).'\\'.Str::studly($gateway).'Gateway';
  137. if (class_exists($gateway)) {
  138. return $this->makePay($gateway);
  139. }
  140. throw new InvalidGatewayException("Pay Gateway [{$gateway}] not exists");
  141. }
  142. /**
  143. * Verify sign.
  144. *
  145. * @author yansongda <me@yansongda.cn>
  146. *
  147. * @param array|null $data
  148. *
  149. * @throws InvalidSignException
  150. * @throws InvalidConfigException
  151. */
  152. public function verify($data = null, bool $refund = false): Collection
  153. {
  154. if (is_null($data)) {
  155. $request = Request::createFromGlobals();
  156. $data = $request->request->count() > 0 ? $request->request->all() : $request->query->all();
  157. }
  158. if (isset($data['fund_bill_list'])) {
  159. $data['fund_bill_list'] = htmlspecialchars_decode($data['fund_bill_list']);
  160. }
  161. Events::dispatch(new Events\RequestReceived('Alipay', '', $data));
  162. if (Support::verifySign($data)) {
  163. return new Collection($data);
  164. }
  165. Events::dispatch(new Events\SignFailed('Alipay', '', $data));
  166. throw new InvalidSignException('Alipay Sign Verify FAILED', $data);
  167. }
  168. /**
  169. * Query an order.
  170. *
  171. * @author yansongda <me@yansongda.cn>
  172. *
  173. * @param string|array $order
  174. *
  175. * @throws GatewayException
  176. * @throws InvalidConfigException
  177. * @throws InvalidSignException
  178. */
  179. public function find($order, string $type = 'wap'): Collection
  180. {
  181. $gateway = get_class($this).'\\'.Str::studly($type).'Gateway';
  182. if (!class_exists($gateway) || !is_callable([new $gateway(), 'find'])) {
  183. throw new GatewayException("{$gateway} Done Not Exist Or Done Not Has FIND Method");
  184. }
  185. $config = call_user_func([new $gateway(), 'find'], $order);
  186. $this->payload['method'] = $config['method'];
  187. $this->payload['biz_content'] = $config['biz_content'];
  188. $this->payload['sign'] = Support::generateSign($this->payload);
  189. Events::dispatch(new Events\MethodCalled('Alipay', 'Find', $this->gateway, $this->payload));
  190. return Support::requestApi($this->payload);
  191. }
  192. /**
  193. * Refund an order.
  194. *
  195. * @author yansongda <me@yansongda.cn>
  196. *
  197. * @throws GatewayException
  198. * @throws InvalidConfigException
  199. * @throws InvalidSignException
  200. */
  201. public function refund(array $order): Collection
  202. {
  203. $this->payload['method'] = 'alipay.trade.refund';
  204. $this->payload['biz_content'] = json_encode($order);
  205. $this->payload['sign'] = Support::generateSign($this->payload);
  206. Events::dispatch(new Events\MethodCalled('Alipay', 'Refund', $this->gateway, $this->payload));
  207. return Support::requestApi($this->payload);
  208. }
  209. /**
  210. * Cancel an order.
  211. *
  212. * @author yansongda <me@yansongda.cn>
  213. *
  214. * @param array|string $order
  215. *
  216. * @throws GatewayException
  217. * @throws InvalidConfigException
  218. * @throws InvalidSignException
  219. */
  220. public function cancel($order): Collection
  221. {
  222. $this->payload['method'] = 'alipay.trade.cancel';
  223. $this->payload['biz_content'] = json_encode(is_array($order) ? $order : ['out_trade_no' => $order]);
  224. $this->payload['sign'] = Support::generateSign($this->payload);
  225. Events::dispatch(new Events\MethodCalled('Alipay', 'Cancel', $this->gateway, $this->payload));
  226. return Support::requestApi($this->payload);
  227. }
  228. /**
  229. * Close an order.
  230. *
  231. * @param string|array $order
  232. *
  233. * @author yansongda <me@yansongda.cn>
  234. *
  235. * @throws GatewayException
  236. * @throws InvalidConfigException
  237. * @throws InvalidSignException
  238. */
  239. public function close($order): Collection
  240. {
  241. $this->payload['method'] = 'alipay.trade.close';
  242. $this->payload['biz_content'] = json_encode(is_array($order) ? $order : ['out_trade_no' => $order]);
  243. $this->payload['sign'] = Support::generateSign($this->payload);
  244. Events::dispatch(new Events\MethodCalled('Alipay', 'Close', $this->gateway, $this->payload));
  245. return Support::requestApi($this->payload);
  246. }
  247. /**
  248. * Download bill.
  249. *
  250. * @author yansongda <me@yansongda.cn>
  251. *
  252. * @param string|array $bill
  253. *
  254. * @throws GatewayException
  255. * @throws InvalidConfigException
  256. * @throws InvalidSignException
  257. */
  258. public function download($bill): string
  259. {
  260. $this->payload['method'] = 'alipay.data.dataservice.bill.downloadurl.query';
  261. $this->payload['biz_content'] = json_encode(is_array($bill) ? $bill : ['bill_type' => 'trade', 'bill_date' => $bill]);
  262. $this->payload['sign'] = Support::generateSign($this->payload);
  263. Events::dispatch(new Events\MethodCalled('Alipay', 'Download', $this->gateway, $this->payload));
  264. $result = Support::requestApi($this->payload);
  265. return ($result instanceof Collection) ? $result->get('bill_download_url') : '';
  266. }
  267. /**
  268. * Reply success to alipay.
  269. *
  270. * @author yansongda <me@yansongda.cn>
  271. */
  272. public function success(): Response
  273. {
  274. Events::dispatch(new Events\MethodCalled('Alipay', 'Success', $this->gateway));
  275. return new Response('success');
  276. }
  277. /**
  278. * extend.
  279. *
  280. * @author yansongda <me@yansongda.cn>
  281. *
  282. * @throws GatewayException
  283. * @throws InvalidConfigException
  284. * @throws InvalidSignException
  285. * @throws InvalidArgumentException
  286. */
  287. public function extend(string $method, callable $function, bool $now = true): ?Collection
  288. {
  289. if (!$now && !method_exists($this, $method)) {
  290. $this->extends[$method] = $function;
  291. return null;
  292. }
  293. $customize = $function($this->payload);
  294. if (!is_array($customize) && !($customize instanceof Collection)) {
  295. throw new InvalidArgumentException('Return Type Must Be Array Or Collection');
  296. }
  297. Events::dispatch(new Events\MethodCalled('Alipay', 'extend', $this->gateway, $customize));
  298. if (is_array($customize)) {
  299. $this->payload = $customize;
  300. $this->payload['sign'] = Support::generateSign($this->payload);
  301. return Support::requestApi($this->payload);
  302. }
  303. return $customize;
  304. }
  305. /**
  306. * Make pay gateway.
  307. *
  308. * @author yansongda <me@yansongda.cn>
  309. *
  310. * @throws InvalidGatewayException
  311. *
  312. * @return Response|Collection
  313. */
  314. protected function makePay(string $gateway)
  315. {
  316. $app = new $gateway();
  317. if ($app instanceof GatewayInterface) {
  318. return $app->pay($this->gateway, array_filter($this->payload, function ($value) {
  319. return '' !== $value && !is_null($value);
  320. }));
  321. }
  322. throw new InvalidGatewayException("Pay Gateway [{$gateway}] Must Be An Instance Of GatewayInterface");
  323. }
  324. /**
  325. * makeExtend.
  326. *
  327. * @author yansongda <me@yansongda.cn>
  328. *
  329. * @throws GatewayException
  330. * @throws InvalidArgumentException
  331. * @throws InvalidConfigException
  332. * @throws InvalidSignException
  333. */
  334. protected function makeExtend(string $method, array ...$params): Collection
  335. {
  336. $params = count($params) >= 1 ? $params[0] : $params;
  337. $function = $this->extends[$method];
  338. $customize = $function($this->payload, $params);
  339. if (!is_array($customize) && !($customize instanceof Collection)) {
  340. throw new InvalidArgumentException('Return Type Must Be Array Or Collection');
  341. }
  342. Events::dispatch(new Events\MethodCalled(
  343. 'Alipay',
  344. 'extend - '.$method,
  345. $this->gateway,
  346. is_array($customize) ? $customize : $customize->toArray()
  347. ));
  348. if (is_array($customize)) {
  349. $this->payload = $customize;
  350. $this->payload['sign'] = Support::generateSign($this->payload);
  351. return Support::requestApi($this->payload);
  352. }
  353. return $customize;
  354. }
  355. }