OnlyContractPlugin.php 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. <?php
  2. declare(strict_types=1);
  3. namespace Yansongda\Pay\Plugin\Wechat\Papay;
  4. use Closure;
  5. use Yansongda\Pay\Contract\PluginInterface;
  6. use Yansongda\Pay\Direction\NoHttpRequestDirection;
  7. use Yansongda\Pay\Exception\ContainerException;
  8. use Yansongda\Pay\Exception\InvalidConfigException;
  9. use Yansongda\Pay\Exception\ServiceNotFoundException;
  10. use Yansongda\Pay\Rocket;
  11. use function Yansongda\Pay\get_wechat_config;
  12. use function Yansongda\Pay\get_wechat_sign_v2;
  13. /**
  14. * 返回只签约(委托代扣)参数.
  15. *
  16. * @see https://pay.weixin.qq.com/wiki/doc/api/wxpay_v2/papay/chapter3_3.shtml
  17. */
  18. class OnlyContractPlugin implements PluginInterface
  19. {
  20. /**
  21. * @throws ContainerException
  22. * @throws InvalidConfigException
  23. * @throws ServiceNotFoundException
  24. */
  25. public function assembly(Rocket $rocket, Closure $next): Rocket
  26. {
  27. $config = get_wechat_config($rocket->getParams());
  28. $wechatId = $this->getWechatId($config, $rocket->getParams());
  29. if (!$rocket->getPayload()->has('notify_url')) {
  30. $wechatId['notify_url'] = $config['notify_url'] ?? '';
  31. }
  32. $rocket->mergePayload($wechatId);
  33. $rocket->mergePayload([
  34. 'sign' => get_wechat_sign_v2($rocket->getParams(), $rocket->getPayload()->all()),
  35. ]);
  36. $rocket->setDestination($rocket->getPayload());
  37. $rocket->setDirection(NoHttpRequestDirection::class);
  38. return $next($rocket);
  39. }
  40. protected function getWechatId(array $config, array $params): array
  41. {
  42. $configKey = $this->getConfigKey($params);
  43. return [
  44. 'appid' => $config[$configKey] ?? '',
  45. 'mch_id' => $config['mch_id'] ?? '',
  46. ];
  47. }
  48. protected function getConfigKey(array $params): string
  49. {
  50. $key = ($params['_type'] ?? 'mp').'_app_id';
  51. if ('app_app_id' === $key) {
  52. $key = 'app_id';
  53. }
  54. return $key;
  55. }
  56. }