HttpClient.php 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. <?php
  2. namespace app\common\Service\Pay;
  3. use GuzzleHttp\Client;
  4. use GuzzleHttp\Exception\RequestException;
  5. use Psr\Http\Client\ClientInterface;
  6. use Psr\Http\Client\ClientExceptionInterface;
  7. use Psr\Http\Message\RequestInterface;
  8. use Psr\Http\Message\ResponseInterface;
  9. /**
  10. * 本 HttpClient 主要为了解决 yansongda\pay Http 必须继承 ClientInterface 问题(fa 框架的 GuzzleHttp\client 为 6.* 未继承 psr ClientInterface
  11. * 也可直接将本类当作 GuzzleHttp\Client 使用
  12. */
  13. class HttpClient implements ClientInterface
  14. {
  15. /**
  16. * GuzzleHttp Client 实例
  17. * @var Client
  18. */
  19. protected $client;
  20. /**
  21. * 单例实例
  22. * @var HttpClient
  23. */
  24. private static $instance;
  25. /**
  26. * 构造函数
  27. * @param array $config
  28. */
  29. public function __construct(array $config = [])
  30. {
  31. $this->client = new Client($config);
  32. }
  33. /**
  34. * 获取单例实例
  35. * @param array $config
  36. * @return HttpClient
  37. */
  38. public static function instance(array $config = [])
  39. {
  40. if (!static::$instance instanceof static) {
  41. static::$instance = new static($config);
  42. }
  43. return static::$instance;
  44. }
  45. /**
  46. * 发送 PSR-7 请求并返回 PSR-7 响应
  47. *
  48. * @param RequestInterface $request
  49. * @return ResponseInterface
  50. * @throws ClientExceptionInterface 如果发生错误且无法完成请求
  51. */
  52. public function sendRequest(RequestInterface $request): ResponseInterface
  53. {
  54. try {
  55. return $this->client->send($request);
  56. } catch (RequestException $e) {
  57. // 将 GuzzleHttp 异常转换为 PSR 客户端异常
  58. throw new class($e->getMessage(), $e->getCode(), $e) extends \RuntimeException implements ClientExceptionInterface {
  59. // PSR ClientExceptionInterface 实现
  60. };
  61. }
  62. }
  63. /**
  64. * 魔术方法,将其他方法调用代理到 GuzzleHttp Client
  65. * 使其能够当作 GuzzleHttp\Client 使用
  66. *
  67. * @param string $method
  68. * @param array $arguments
  69. * @return mixed
  70. */
  71. public function __call($method, $arguments)
  72. {
  73. return $this->client->{$method}(...$arguments);
  74. }
  75. /**
  76. * 获取底层的 GuzzleHttp Client
  77. * @return Client
  78. */
  79. public function getClient()
  80. {
  81. return $this->client;
  82. }
  83. /**
  84. * 设置 GuzzleHttp Client
  85. * @param Client $client
  86. * @return $this
  87. */
  88. public function setClient(Client $client)
  89. {
  90. $this->client = $client;
  91. return $this;
  92. }
  93. }