LaunchPlugin.php 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. <?php
  2. declare(strict_types=1);
  3. namespace Yansongda\Pay\Plugin\Alipay;
  4. use Closure;
  5. use Yansongda\Pay\Contract\PluginInterface;
  6. use Yansongda\Pay\Exception\ContainerException;
  7. use Yansongda\Pay\Exception\Exception;
  8. use Yansongda\Pay\Exception\InvalidConfigException;
  9. use Yansongda\Pay\Exception\InvalidResponseException;
  10. use Yansongda\Pay\Exception\ServiceNotFoundException;
  11. use Yansongda\Pay\Logger;
  12. use Yansongda\Pay\Rocket;
  13. use Yansongda\Supports\Collection;
  14. use function Yansongda\Pay\should_do_http_request;
  15. use function Yansongda\Pay\verify_alipay_sign;
  16. class LaunchPlugin implements PluginInterface
  17. {
  18. /**
  19. * @throws ContainerException
  20. * @throws InvalidConfigException
  21. * @throws InvalidResponseException
  22. * @throws ServiceNotFoundException
  23. */
  24. public function assembly(Rocket $rocket, Closure $next): Rocket
  25. {
  26. /* @var Rocket $rocket */
  27. $rocket = $next($rocket);
  28. Logger::debug('[alipay][LaunchPlugin] 插件开始装载', ['rocket' => $rocket]);
  29. if (should_do_http_request($rocket->getDirection())) {
  30. $response = Collection::wrap($rocket->getDestination());
  31. $result = $response->get($this->getResultKey($rocket->getPayload()));
  32. $this->verifySign($rocket->getParams(), $response, $result);
  33. $rocket->setDestination(Collection::wrap($result));
  34. }
  35. Logger::info('[alipay][LaunchPlugin] 插件装载完毕', ['rocket' => $rocket]);
  36. return $rocket;
  37. }
  38. /**
  39. * @throws ContainerException
  40. * @throws InvalidConfigException
  41. * @throws InvalidResponseException
  42. * @throws ServiceNotFoundException
  43. */
  44. protected function verifySign(array $params, Collection $response, ?array $result): void
  45. {
  46. $sign = $response->get('sign', '');
  47. if ('' === $sign || is_null($result)) {
  48. throw new InvalidResponseException(Exception::INVALID_RESPONSE_SIGN, 'Verify Alipay Response Sign Failed: sign is empty', $response);
  49. }
  50. verify_alipay_sign($params, json_encode($result, JSON_UNESCAPED_UNICODE), $sign);
  51. }
  52. protected function getResultKey(Collection $payload): string
  53. {
  54. $method = $payload->get('method');
  55. return str_replace('.', '_', $method).'_response';
  56. }
  57. }