You are here

public function HostedFields::refundPayment in Commerce Braintree 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/HostedFields.php, line 301

Class

HostedFields
Provides the HostedFields payment gateway.

Namespace

Drupal\commerce_braintree\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();
    $decimal_amount = $amount
      ->getNumber();
    $result = $this->api
      ->transaction()
      ->refund($remote_id, $decimal_amount);
    ErrorHelper::handleErrors($result);
  } catch (BraintreeException $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();
}