AddPayloadSignaturePlugin.php 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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\ContainerException;
  7. use Yansongda\Artful\Exception\InvalidConfigException;
  8. use Yansongda\Artful\Exception\ServiceNotFoundException;
  9. use Yansongda\Artful\Logger;
  10. use Yansongda\Artful\Rocket;
  11. use Yansongda\Pay\Exception\Exception;
  12. use function Yansongda\Pay\get_private_cert;
  13. use function Yansongda\Pay\get_provider_config;
  14. class AddPayloadSignaturePlugin implements PluginInterface
  15. {
  16. /**
  17. * @throws ContainerException
  18. * @throws InvalidConfigException
  19. * @throws ServiceNotFoundException
  20. */
  21. public function assembly(Rocket $rocket, Closure $next): Rocket
  22. {
  23. Logger::debug('[Alipay][AddPayloadSignaturePlugin] 插件开始装载', ['rocket' => $rocket]);
  24. $rocket->mergePayload(['sign' => $this->getSign($rocket)]);
  25. Logger::info('[Alipay][AddPayloadSignaturePlugin] 插件装载完毕', ['rocket' => $rocket]);
  26. return $next($rocket);
  27. }
  28. /**
  29. * @throws ContainerException
  30. * @throws InvalidConfigException
  31. * @throws ServiceNotFoundException
  32. */
  33. protected function getSign(Rocket $rocket): string
  34. {
  35. $privateKey = $this->getPrivateKey($rocket->getParams());
  36. $content = $rocket->getPayload()->sortKeys()->toString();
  37. openssl_sign($content, $sign, $privateKey, OPENSSL_ALGO_SHA256);
  38. return base64_encode($sign);
  39. }
  40. /**
  41. * @throws ContainerException
  42. * @throws InvalidConfigException
  43. * @throws ServiceNotFoundException
  44. */
  45. protected function getPrivateKey(array $params): string
  46. {
  47. $privateKey = get_provider_config('alipay', $params)['app_secret_cert'] ?? null;
  48. if (is_null($privateKey)) {
  49. throw new InvalidConfigException(Exception::CONFIG_ALIPAY_INVALID, '配置异常: 缺少支付宝配置 -- [app_secret_cert]');
  50. }
  51. return get_private_cert($privateKey);
  52. }
  53. }