You are here

public function Stripe::voidPayment in Commerce Stripe 8

Voids the given payment.

Parameters

\Drupal\commerce_payment\Entity\PaymentInterface $payment: The payment to void.

Throws

\Drupal\commerce_payment\Exception\PaymentGatewayException Thrown when the transaction fails for any reason.

Overrides SupportsVoidsInterface::voidPayment

File

src/Plugin/Commerce/PaymentGateway/Stripe.php, line 312

Class

Stripe
Provides the Stripe payment gateway.

Namespace

Drupal\commerce_stripe\Plugin\Commerce\PaymentGateway

Code

public function voidPayment(PaymentInterface $payment) {
  $this
    ->assertPaymentState($payment, [
    'authorization',
  ]);

  // Void Stripe payment - release uncaptured payment.
  try {
    $remote_id = $payment
      ->getRemoteId();
    $charge = Charge::retrieve($remote_id);
    $intent_id = $charge->payment_intent;
    if (!empty($intent_id)) {
      $intent = PaymentIntent::retrieve($intent_id);
      $statuses_to_void = [
        'requires_payment_method',
        'requires_capture',
        'requires_confirmation',
        'requires_action',
      ];
      if (!in_array($intent->status, $statuses_to_void)) {
        throw new PaymentGatewayException('The PaymentIntent cannot be voided.');
      }
      $intent
        ->cancel();
    }
    else {
      $data = [
        'charge' => $remote_id,
      ];

      // Voiding an authorized payment is done by creating a refund.
      $release_refund = Refund::create($data);
      ErrorHelper::handleErrors($release_refund);
    }
  } catch (ApiErrorException $e) {
    ErrorHelper::handleException($e);
  }
  $payment
    ->setState('authorization_voided');
  $payment
    ->save();
}