GatewaySubscriptionController.php
83 lines
| 1 | <?php |
| 2 | |
| 3 | namespace Give\Framework\PaymentGateways\Controllers; |
| 4 | |
| 5 | use Give\Donations\Models\Donation; |
| 6 | use Give\Framework\Exceptions\Primitives\Exception; |
| 7 | use Give\Framework\FieldsAPI\Exceptions\TypeNotSupported; |
| 8 | use Give\Framework\PaymentGateways\Actions\HandleGatewaySubscriptionCommand; |
| 9 | use Give\Framework\PaymentGateways\Commands\GatewayCommand; |
| 10 | use Give\Framework\PaymentGateways\Log\PaymentGatewayLog; |
| 11 | use Give\Framework\PaymentGateways\PaymentGateway; |
| 12 | use Give\Framework\PaymentGateways\Traits\HandleHttpResponses; |
| 13 | use Give\Subscriptions\Models\Subscription; |
| 14 | |
| 15 | /** |
| 16 | * @since 2.27.0 |
| 17 | */ |
| 18 | class GatewaySubscriptionController |
| 19 | { |
| 20 | use HandleHttpResponses; |
| 21 | |
| 22 | /** |
| 23 | * @var PaymentGateway |
| 24 | */ |
| 25 | protected $gateway; |
| 26 | |
| 27 | /** |
| 28 | * @since 2.27.0 |
| 29 | */ |
| 30 | public function __construct(PaymentGateway $gateway) |
| 31 | { |
| 32 | $this->gateway = $gateway; |
| 33 | } |
| 34 | |
| 35 | /** |
| 36 | * @since 2.27.0 |
| 37 | */ |
| 38 | public function create(Donation $donation, Subscription $subscription, array $gatewayData = []) |
| 39 | { |
| 40 | try { |
| 41 | $command = $this->gateway->createSubscription($donation, $subscription, $gatewayData); |
| 42 | $this->handleGatewayCommand($command, $donation, $subscription); |
| 43 | } catch (\Exception $exception) { |
| 44 | PaymentGatewayLog::error( |
| 45 | $exception->getMessage(), |
| 46 | [ |
| 47 | 'Payment Gateway' => $this->gateway::id(), |
| 48 | 'Donation' => $donation->toArray(), |
| 49 | 'Subscription' => $subscription->toArray(), |
| 50 | ] |
| 51 | ); |
| 52 | |
| 53 | $message = __( |
| 54 | 'An unexpected error occurred while processing the subscription. Please try again or contact the site administrator.', |
| 55 | 'give' |
| 56 | ); |
| 57 | |
| 58 | $this->handleExceptionResponse($exception, $message); |
| 59 | } |
| 60 | } |
| 61 | |
| 62 | /** |
| 63 | * Handle gateway subscription command |
| 64 | * |
| 65 | * @since 2.27.0 move logic into action |
| 66 | * @since 2.26.0 add RespondToBrowser command |
| 67 | * @since 2.21.0 Handle RedirectOffsite response. |
| 68 | * @since 2.18.0 |
| 69 | * |
| 70 | * @throws TypeNotSupported |
| 71 | * @throws Exception |
| 72 | */ |
| 73 | public function handleGatewayCommand( |
| 74 | GatewayCommand $command, |
| 75 | Donation $donation, |
| 76 | Subscription $subscription |
| 77 | ) { |
| 78 | $response = (new HandleGatewaySubscriptionCommand())($command, $donation, $subscription); |
| 79 | |
| 80 | $this->handleResponse($response); |
| 81 | } |
| 82 | } |
| 83 |