HtmlResponsePlugin.php 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. <?php
  2. declare(strict_types=1);
  3. namespace Yansongda\Pay\Plugin\Alipay;
  4. use Closure;
  5. use GuzzleHttp\Psr7\Response;
  6. use Yansongda\Pay\Contract\PluginInterface;
  7. use Yansongda\Pay\Logger;
  8. use Yansongda\Pay\Rocket;
  9. use Yansongda\Supports\Collection;
  10. class HtmlResponsePlugin implements PluginInterface
  11. {
  12. public function assembly(Rocket $rocket, Closure $next): Rocket
  13. {
  14. /* @var Rocket $rocket */
  15. $rocket = $next($rocket);
  16. Logger::debug('[alipay][HtmlResponsePlugin] 插件开始装载', ['rocket' => $rocket]);
  17. $radar = $rocket->getRadar();
  18. $response = 'GET' === $radar->getMethod() ?
  19. $this->buildRedirect($radar->getUri()->__toString(), $rocket->getPayload()) :
  20. $this->buildHtml($radar->getUri()->__toString(), $rocket->getPayload());
  21. $rocket->setDestination($response);
  22. Logger::info('[alipay][HtmlResponsePlugin] 插件装载完毕', ['rocket' => $rocket]);
  23. return $rocket;
  24. }
  25. protected function buildRedirect(string $endpoint, Collection $payload): Response
  26. {
  27. $url = $endpoint.(false === strpos($endpoint, '?') ? '?' : '&').$payload->query();
  28. $content = sprintf(
  29. '<!DOCTYPE html>
  30. <html lang="en">
  31. <head>
  32. <meta charset="UTF-8" />
  33. <meta http-equiv="refresh" content="0;url=\'%1$s\'" />
  34. <title>Redirecting to %1$s</title>
  35. </head>
  36. <body>
  37. Redirecting to %1$s.
  38. </body>
  39. </html>',
  40. htmlspecialchars($url, ENT_QUOTES)
  41. );
  42. return new Response(302, ['Location' => $url], $content);
  43. }
  44. protected function buildHtml(string $endpoint, Collection $payload): Response
  45. {
  46. $sHtml = "<form id='alipay_submit' name='alipay_submit' action='".$endpoint."' method='POST'>";
  47. foreach ($payload->all() as $key => $val) {
  48. $val = str_replace("'", '&apos;', $val);
  49. $sHtml .= "<input type='hidden' name='".$key."' value='".$val."'/>";
  50. }
  51. $sHtml .= "<input type='submit' value='ok' style='display:none;'></form>";
  52. $sHtml .= "<script>document.forms['alipay_submit'].submit();</script>";
  53. return new Response(200, [], $sHtml);
  54. }
  55. }