You are here

public function Checkout::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/Checkout.php, line 571

Class

Checkout
Provides the PayPal 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);
  $old_refunded_amount = $payment
    ->getRefundedAmount();
  $new_refunded_amount = $old_refunded_amount
    ->add($amount);
  $params = [
    'amount' => [
      'value' => Calculator::trim($amount
        ->getNumber()),
      'currency_code' => $amount
        ->getCurrencyCode(),
    ],
  ];
  if ($new_refunded_amount
    ->lessThan($payment
    ->getAmount())) {
    $payment
      ->setState('partially_refunded');
  }
  else {
    $payment
      ->setState('refunded');
  }
  try {
    $sdk = $this->checkoutSdkFactory
      ->get($this->configuration);
    $response = $sdk
      ->refundPayment($payment
      ->getRemoteId(), $params);
    $response = Json::decode($response
      ->getBody()
      ->getContents());
  } catch (BadResponseException $exception) {
    $this->logger
      ->error($exception
      ->getResponse()
      ->getBody()
      ->getContents());
    throw new PaymentGatewayException('An error occurred while refunding the payment.');
  }
  if (strtolower($response['status']) !== 'completed') {
    throw new PaymentGatewayException(sprintf('Invalid state returned by PayPal. Expected: ("%s"), Actual: ("%s").', 'COMPLETED', $response['status']));
  }
  $payment
    ->setRemoteState($response['status']);
  $payment
    ->setRefundedAmount($new_refunded_amount);
  $payment
    ->save();
}