You are here

public function Payflow::refundPayment in Commerce PayPal 8

TODO: Find a way to store the capture ID.

Overrides SupportsRefundsInterface::refundPayment

File

src/Plugin/Commerce/PaymentGateway/Payflow.php, line 452

Class

Payflow
Provides the PayPal Payflow 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 ($payment
    ->getCompletedTime() < strtotime('-180 days')) {
    throw new InvalidRequestException("Unable to refund a payment captured more than 180 days ago.");
  }

  // If not specified, refund the entire amount.
  $amount = $amount ?: $payment
    ->getAmount();
  $amount = $this->rounder
    ->round($amount);
  $this
    ->assertRefundAmount($payment, $amount);
  $transaction_number = $this
    ->getTransactionNumber($payment);
  if (empty($transaction_number)) {
    throw new InvalidRequestException('Could not determine the remote payment details.');
  }
  try {
    $new_refunded_amount = $payment
      ->getRefundedAmount()
      ->add($amount);
    $data = $this
      ->executeTransaction([
      'trxtype' => 'C',
      'origid' => $transaction_number,
      'amt' => $amount
        ->getNumber(),
    ]);
    if ($data['result'] !== '0') {
      throw new PaymentGatewayException('Credit could not be completed. Message: ' . $data['respmsg'], $data['result']);
    }
    if ($new_refunded_amount
      ->lessThan($payment
      ->getAmount())) {
      $payment
        ->setState('partially_refunded');
    }
    else {
      $payment
        ->setState('refunded');
    }
    $payment
      ->setRefundedAmount($new_refunded_amount);
    $payment
      ->save();
  } catch (RequestException $e) {
    throw new InvalidRequestException("Could not refund the payment.", $e
      ->getCode(), $e);
  }
}