You are here

public function Onsite::refundPayment in Commerce Core 8.2

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

modules/payment_example/src/Plugin/Commerce/PaymentGateway/Onsite.php, line 160

Class

Onsite
Provides the On-site payment gateway.

Namespace

Drupal\commerce_payment_example\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);

  // Perform the refund request here, throw an exception if it fails.
  // See \Drupal\commerce_payment\Exception for the available exceptions.
  $remote_id = $payment
    ->getRemoteId();
  $number = $amount
    ->getNumber();
  $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();
}