You are here

public function ExpressCheckout::refundPayment in Commerce PayPal 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/ExpressCheckout.php, line 327

Class

ExpressCheckout
Provides the Paypal Express Checkout payment gateway.

Namespace

Drupal\commerce_paypal\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);
  $amount = $this->rounder
    ->round($amount);
  $extra['amount'] = $amount
    ->getNumber();

  // Check if the Refund is partial or full.
  $old_refunded_amount = $payment
    ->getRefundedAmount();
  $new_refunded_amount = $old_refunded_amount
    ->add($amount);
  if ($new_refunded_amount
    ->lessThan($payment
    ->getAmount())) {
    $payment
      ->setState('partially_refunded');
    $extra['refund_type'] = 'Partial';
  }
  else {
    $payment
      ->setState('refunded');
    if ($amount
      ->lessThan($payment
      ->getAmount())) {
      $extra['refund_type'] = 'Partial';
    }
    else {
      $extra['refund_type'] = 'Full';
    }
  }

  // RefundTransaction API Operation (NVP).
  // Refund (full or partial) an Express Checkout transaction.
  $paypal_response = $this
    ->doRefundTransaction($payment, $extra);
  if ($paypal_response['ACK'] == 'Failure') {
    $message = $paypal_response['L_LONGMESSAGE0'];
    throw new PaymentGatewayException($message, $paypal_response['L_ERRORCODE0']);
  }
  $payment
    ->setRefundedAmount($new_refunded_amount);
  $payment
    ->save();
}