AppGateway.php 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. <?php
  2. namespace Yansongda\Pay\Gateways\Wechat;
  3. use Exception;
  4. use Symfony\Component\HttpFoundation\JsonResponse;
  5. use Symfony\Component\HttpFoundation\Response;
  6. use Yansongda\Pay\Events;
  7. use Yansongda\Pay\Exceptions\GatewayException;
  8. use Yansongda\Pay\Exceptions\InvalidArgumentException;
  9. use Yansongda\Pay\Exceptions\InvalidSignException;
  10. use Yansongda\Pay\Gateways\Wechat;
  11. use Yansongda\Supports\Str;
  12. class AppGateway extends Gateway
  13. {
  14. /**
  15. * Pay an order.
  16. *
  17. * @author yansongda <me@yansongda.cn>
  18. *
  19. * @param string $endpoint
  20. *
  21. * @throws GatewayException
  22. * @throws InvalidArgumentException
  23. * @throws InvalidSignException
  24. * @throws Exception
  25. */
  26. public function pay($endpoint, array $payload): Response
  27. {
  28. $payload['appid'] = Support::getInstance()->appid;
  29. $payload['trade_type'] = $this->getTradeType();
  30. if (Wechat::MODE_SERVICE === $this->mode) {
  31. $payload['sub_appid'] = Support::getInstance()->sub_appid;
  32. }
  33. $pay_request = [
  34. 'appid' => Wechat::MODE_SERVICE === $this->mode ? $payload['sub_appid'] : $payload['appid'],
  35. 'partnerid' => Wechat::MODE_SERVICE === $this->mode ? $payload['sub_mch_id'] : $payload['mch_id'],
  36. 'prepayid' => $this->preOrder($payload)->get('prepay_id'),
  37. 'timestamp' => strval(time()),
  38. 'noncestr' => Str::random(),
  39. 'package' => 'Sign=WXPay',
  40. ];
  41. $pay_request['sign'] = Support::generateSign($pay_request);
  42. Events::dispatch(new Events\PayStarted('Wechat', 'App', $endpoint, $pay_request));
  43. return new JsonResponse($pay_request);
  44. }
  45. /**
  46. * Get trade type config.
  47. *
  48. * @author yansongda <me@yansongda.cn>
  49. */
  50. protected function getTradeType(): string
  51. {
  52. return 'APP';
  53. }
  54. }