ResponsePlugin.php 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. <?php
  2. declare(strict_types=1);
  3. namespace Yansongda\Pay\Plugin\Alipay\V2;
  4. use Closure;
  5. use Yansongda\Artful\Contract\PluginInterface;
  6. use Yansongda\Artful\Exception\InvalidResponseException;
  7. use Yansongda\Artful\Logger;
  8. use Yansongda\Artful\Rocket;
  9. use Yansongda\Pay\Exception\Exception;
  10. use Yansongda\Supports\Collection;
  11. use function Yansongda\Artful\should_do_http_request;
  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('[Alipay][ResponsePlugin] 插件开始装载', ['rocket' => $rocket]);
  22. $destination = $rocket->getDestination();
  23. $payload = $rocket->getPayload();
  24. $resultKey = str_replace('.', '_', $payload->get('method')).'_response';
  25. if (should_do_http_request($rocket->getDirection()) && $destination instanceof Collection) {
  26. $sign = $destination->get('sign', '');
  27. $response = $destination->get($resultKey, $destination->all());
  28. if (empty($sign) && '10000' !== ($response['code'] ?? 'null')) {
  29. throw new InvalidResponseException(Exception::RESPONSE_BUSINESS_CODE_WRONG, '支付宝网关响应异常: '.($response['sub_msg'] ?? $response['msg'] ?? '未知错误,请查看支付宝原始响应'), $rocket->getDestination());
  30. }
  31. $rocket->setDestination(new Collection(array_merge(
  32. ['_sign' => $sign],
  33. $response
  34. )));
  35. }
  36. Logger::info('[Alipay][ResponsePlugin] 插件装载完毕', ['rocket' => $rocket]);
  37. return $rocket;
  38. }
  39. }