ResponsePlugin.php 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. <?php
  2. declare(strict_types=1);
  3. namespace Yansongda\Pay\Plugin\Jsb;
  4. use Closure;
  5. use Psr\Http\Message\ResponseInterface;
  6. use Yansongda\Artful\Contract\PluginInterface;
  7. use Yansongda\Artful\Exception\InvalidResponseException;
  8. use Yansongda\Artful\Logger;
  9. use Yansongda\Artful\Rocket;
  10. use Yansongda\Pay\Exception\Exception;
  11. use Yansongda\Supports\Collection;
  12. class ResponsePlugin implements PluginInterface
  13. {
  14. /**
  15. * @throws InvalidResponseException
  16. */
  17. public function assembly(Rocket $rocket, Closure $next): Rocket
  18. {
  19. /* @var Rocket $rocket */
  20. $rocket = $next($rocket);
  21. Logger::debug('[Jsb][ResponsePlugin] 插件开始装载', ['rocket' => $rocket]);
  22. $this->validateResponse($rocket);
  23. Logger::info('[Jsb][ResponsePlugin] 插件装载完毕', ['rocket' => $rocket]);
  24. return $rocket;
  25. }
  26. /**
  27. * @throws InvalidResponseException
  28. */
  29. protected function validateResponse(Rocket $rocket): void
  30. {
  31. $destination = $rocket->getDestination();
  32. $destinationOrigin = $rocket->getDestinationOrigin();
  33. if ($destinationOrigin instanceof ResponseInterface
  34. && ($destinationOrigin->getStatusCode() < 200 || $destinationOrigin->getStatusCode() >= 300)) {
  35. throw new InvalidResponseException(Exception::RESPONSE_CODE_WRONG, '江苏银行返回状态码异常,请检查参数是否错误', $rocket->getDestination());
  36. }
  37. if ($destination instanceof Collection && '000000' !== $destination->get('respCode')) {
  38. throw new InvalidResponseException(Exception::RESPONSE_BUSINESS_CODE_WRONG, sprintf('江苏银行返回错误: respCode:%s respMsg:%s', $destination->get('respCode'), $destination->get('respMsg')), $rocket->getDestination());
  39. }
  40. }
  41. }