WebGateway.php 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. <?php
  2. namespace Yansongda\Pay\Gateways\Wechat;
  3. use Symfony\Component\HttpFoundation\RedirectResponse;
  4. use Symfony\Component\HttpFoundation\Response;
  5. use Symfony\Component\HttpFoundation\Request;
  6. use Yansongda\Pay\Events;
  7. use Yansongda\Pay\Exceptions\GatewayException;
  8. use Yansongda\Pay\Exceptions\InvalidArgumentException;
  9. use Yansongda\Pay\Exceptions\InvalidSignException;
  10. use Yansongda\Supports\Collection;
  11. class WebGateway extends Gateway
  12. {
  13. /**
  14. * Pay an order.
  15. *
  16. * @param string $endpoint
  17. * @param array $payload
  18. *
  19. * @author yansongda <me@yansongda.cn>
  20. *
  21. */
  22. public function pay($endpoint, array $payload): Response
  23. {
  24. $payload['spbill_create_ip'] = Request::createFromGlobals()->server->get('SERVER_ADDR');
  25. $payload['trade_type'] = $this->getTradeType();
  26. $code_url = $this->preOrder($payload)['code_url'];
  27. $params = [
  28. 'body' => $payload['body'],
  29. 'code_url' => $code_url,
  30. 'out_trade_no' => $payload['out_trade_no'],
  31. 'return_url' => Support::getInstance()->return_url,
  32. 'total_fee' => $payload['total_fee'],
  33. ];
  34. $params['sign'] = md5(implode('', $params) . Support::getInstance()->app_id);
  35. $endpoint = addon_url("epay/api/wechat");
  36. Events::dispatch(new Events\PayStarted('Wechat', 'Web/Wap', $endpoint, $payload));
  37. return $this->buildPayHtml($endpoint, $params);
  38. }
  39. /**
  40. * Build Html response.
  41. *
  42. * @param string $endpoint
  43. * @param array $payload
  44. * @param string $method
  45. *
  46. * @return Response
  47. * @author yansongda <me@yansongda.cn>
  48. *
  49. */
  50. protected function buildPayHtml($endpoint, $payload, $method = 'POST'): Response
  51. {
  52. if (strtoupper($method) === 'GET') {
  53. return RedirectResponse::create($endpoint . '?' . http_build_query($payload));
  54. }
  55. $sHtml = "<form id='wechat_submit' name='wechat_submit' action='" . $endpoint . "' method='" . $method . "'>";
  56. foreach ($payload as $key => $val) {
  57. $val = str_replace("'", '&apos;', $val);
  58. $sHtml .= "<input type='hidden' name='" . $key . "' value='" . $val . "'/>";
  59. }
  60. $sHtml .= "<input type='submit' value='ok' style='display:none;'></form>";
  61. $sHtml .= "<script>document.forms['wechat_submit'].submit();</script>";
  62. return Response::create($sHtml);
  63. }
  64. /**
  65. * Get trade type config.
  66. *
  67. * @return string
  68. * @author yansongda <me@yansongda.cn>
  69. *
  70. */
  71. protected function getTradeType(): string
  72. {
  73. return 'NATIVE';
  74. }
  75. }