MpGateway.php 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. <?php
  2. namespace Yansongda\Pay\Gateways\Wechat;
  3. use Exception;
  4. use Yansongda\Pay\Events;
  5. use Yansongda\Pay\Exceptions\GatewayException;
  6. use Yansongda\Pay\Exceptions\InvalidArgumentException;
  7. use Yansongda\Pay\Exceptions\InvalidSignException;
  8. use Yansongda\Supports\Collection;
  9. use Yansongda\Supports\Str;
  10. class MpGateway extends Gateway
  11. {
  12. /**
  13. * @var bool
  14. */
  15. protected $payRequestUseSubAppId = false;
  16. /**
  17. * Pay an order.
  18. *
  19. * @author yansongda <me@yansongda.cn>
  20. *
  21. * @param string $endpoint
  22. *
  23. * @throws GatewayException
  24. * @throws InvalidArgumentException
  25. * @throws InvalidSignException
  26. * @throws Exception
  27. */
  28. public function pay($endpoint, array $payload): Collection
  29. {
  30. $payload['trade_type'] = $this->getTradeType();
  31. $pay_request = [
  32. 'appId' => !$this->payRequestUseSubAppId ? $payload['appid'] : $payload['sub_appid'],
  33. 'timeStamp' => strval(time()),
  34. 'nonceStr' => Str::random(),
  35. 'package' => 'prepay_id='.$this->preOrder($payload)->get('prepay_id'),
  36. 'signType' => 'MD5',
  37. ];
  38. $pay_request['paySign'] = Support::generateSign($pay_request);
  39. Events::dispatch(new Events\PayStarted('Wechat', 'JSAPI', $endpoint, $pay_request));
  40. return new Collection($pay_request);
  41. }
  42. /**
  43. * Get trade type config.
  44. *
  45. * @author yansongda <me@yansongda.cn>
  46. */
  47. protected function getTradeType(): string
  48. {
  49. return 'JSAPI';
  50. }
  51. }