You are here

public function Stripe::capturePayment in Commerce Stripe 8

Captures the given authorized payment.

Only payments in the 'authorization' state can be captured.

Parameters

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

\Drupal\commerce_price\Price $amount: The amount to capture. If NULL, defaults to the entire payment amount.

Throws

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

Overrides SupportsAuthorizationsInterface::capturePayment

File

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

Class

Stripe
Provides the Stripe payment gateway.

Namespace

Drupal\commerce_stripe\Plugin\Commerce\PaymentGateway

Code

public function capturePayment(PaymentInterface $payment, Price $amount = NULL) {
  $this
    ->assertPaymentState($payment, [
    'authorization',
  ]);

  // If not specified, capture the entire amount.
  $amount = $amount ?: $payment
    ->getAmount();
  try {
    $remote_id = $payment
      ->getRemoteId();
    $charge = Charge::retrieve($remote_id);
    $intent_id = $charge->payment_intent;
    $amount_to_capture = $this->minorUnitsConverter
      ->toMinorUnits($amount);
    if (!empty($intent_id)) {
      $intent = PaymentIntent::retrieve($intent_id);
      if ($intent->status != 'requires_capture') {
        throw new PaymentGatewayException('Only requires_capture PaymentIntents can be captured.');
      }
      $intent
        ->capture([
        'amount_to_capture' => $amount_to_capture,
      ]);
    }
    else {
      $charge->amount = $amount_to_capture;
      $transaction_data = [
        'amount' => $charge->amount,
      ];
      $charge
        ->capture($transaction_data);
    }
  } catch (ApiErrorException $e) {
    ErrorHelper::handleException($e);
  }
  $payment
    ->setState('completed');
  $payment
    ->setAmount($amount);
  $payment
    ->save();
}