GeneralPlugin.php 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. <?php
  2. declare(strict_types=1);
  3. namespace Yansongda\Pay\Plugin\Wechat;
  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\Request;
  12. use Yansongda\Pay\Rocket;
  13. use function Yansongda\Pay\get_wechat_base_uri;
  14. use function Yansongda\Pay\get_wechat_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('[wechat][GeneralPlugin] 通用插件开始装载', ['rocket' => $rocket]);
  24. $rocket->setRadar($this->getRequest($rocket));
  25. $this->doSomething($rocket);
  26. Logger::info('[wechat][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. $params = $rocket->getParams();
  52. $url = Pay::MODE_SERVICE === (get_wechat_config($params)['mode'] ?? null) ? $this->getPartnerUri($rocket) : $this->getUri($rocket);
  53. return 0 === strpos($url, 'http') ? $url : (get_wechat_base_uri($params).$url);
  54. }
  55. protected function getHeaders(): array
  56. {
  57. return [
  58. 'Accept' => 'application/json, text/plain, application/x-gzip',
  59. 'User-Agent' => 'yansongda/pay-v3',
  60. 'Content-Type' => 'application/json; charset=utf-8',
  61. ];
  62. }
  63. protected function getConfigKey(array $params): string
  64. {
  65. $key = ($params['_type'] ?? 'mp').'_app_id';
  66. if ('app_app_id' === $key) {
  67. $key = 'app_id';
  68. }
  69. return $key;
  70. }
  71. abstract protected function doSomething(Rocket $rocket): void;
  72. abstract protected function getUri(Rocket $rocket): string;
  73. protected function getPartnerUri(Rocket $rocket): string
  74. {
  75. return $this->getUri($rocket);
  76. }
  77. }