You are here

public function Stripe::refundPayment in Commerce Stripe 8

Refunds the given payment.

Parameters

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

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

Throws

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

Overrides SupportsRefundsInterface::refundPayment

File

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

Class

Stripe
Provides the Stripe payment gateway.

Namespace

Drupal\commerce_stripe\Plugin\Commerce\PaymentGateway

Code

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

  // If not specified, refund the entire amount.
  $amount = $amount ?: $payment
    ->getAmount();
  $this
    ->assertRefundAmount($payment, $amount);
  try {
    $remote_id = $payment
      ->getRemoteId();
    $minor_units_amount = $this->minorUnitsConverter
      ->toMinorUnits($amount);
    $data = [
      'charge' => $remote_id,
      'amount' => $minor_units_amount,
    ];
    $refund = Refund::create($data, [
      'idempotency_key' => \Drupal::getContainer()
        ->get('uuid')
        ->generate(),
    ]);
    ErrorHelper::handleErrors($refund);
  } catch (ApiErrorException $e) {
    ErrorHelper::handleException($e);
  }
  $old_refunded_amount = $payment
    ->getRefundedAmount();
  $new_refunded_amount = $old_refunded_amount
    ->add($amount);
  if ($new_refunded_amount
    ->lessThan($payment
    ->getAmount())) {
    $payment
      ->setState('partially_refunded');
  }
  else {
    $payment
      ->setState('refunded');
  }
  $payment
    ->setRefundedAmount($new_refunded_amount);
  $payment
    ->save();
}