GeneralPlugin.php 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. <?php
  2. declare(strict_types=1);
  3. namespace Yansongda\Pay\Plugin\Unipay;
  4. use Closure;
  5. use Psr\Http\Message\RequestInterface;
  6. use Yansongda\Pay\Contract\PluginInterface;
  7. use Yansongda\Pay\Exception\ContainerException;
  8. use Yansongda\Pay\Exception\ServiceNotFoundException;
  9. use Yansongda\Pay\Logger;
  10. use Yansongda\Pay\Pay;
  11. use Yansongda\Pay\Provider\Unipay;
  12. use Yansongda\Pay\Request;
  13. use Yansongda\Pay\Rocket;
  14. use function Yansongda\Pay\get_unipay_config;
  15. abstract class GeneralPlugin implements PluginInterface
  16. {
  17. /**
  18. * @throws ServiceNotFoundException
  19. * @throws ContainerException
  20. */
  21. public function assembly(Rocket $rocket, Closure $next): Rocket
  22. {
  23. Logger::debug('[unipay][GeneralPlugin] 通用插件开始装载', ['rocket' => $rocket]);
  24. $rocket->setRadar($this->getRequest($rocket));
  25. $this->doSomething($rocket);
  26. Logger::info('[unipay][GeneralPlugin] 通用插件装载完毕', ['rocket' => $rocket]);
  27. return $next($rocket);
  28. }
  29. /**
  30. * @throws ContainerException
  31. * @throws ServiceNotFoundException
  32. */
  33. protected function getRequest(Rocket $rocket): RequestInterface
  34. {
  35. return new Request(
  36. $this->getMethod(),
  37. $this->getUrl($rocket),
  38. $this->getHeaders(),
  39. );
  40. }
  41. protected function getMethod(): string
  42. {
  43. return 'POST';
  44. }
  45. /**
  46. * @throws ContainerException
  47. * @throws ServiceNotFoundException
  48. */
  49. protected function getUrl(Rocket $rocket): string
  50. {
  51. $url = $this->getUri($rocket);
  52. if (0 === strpos($url, 'http')) {
  53. return $url;
  54. }
  55. $config = get_unipay_config($rocket->getParams());
  56. return Unipay::URL[$config['mode'] ?? Pay::MODE_NORMAL].$url;
  57. }
  58. protected function getHeaders(): array
  59. {
  60. return [
  61. 'User-Agent' => 'yansongda/pay-v3',
  62. 'Content-Type' => 'application/x-www-form-urlencoded;charset=utf-8',
  63. ];
  64. }
  65. abstract protected function doSomething(Rocket $rocket): void;
  66. abstract protected function getUri(Rocket $rocket): string;
  67. }