You are here

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

Class

PayflowLink
Provides the PayPal Payflow Link 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);

  // Prepare a name-value pair array to capture the requested amount.
  $nvp = [
    'TRXTYPE' => 'C',
    'ORIGID' => $payment
      ->getRemoteId(),
    'AMT' => Calculator::trim($amount
      ->getNumber()),
  ];
  $order = $payment
    ->getOrder();

  // Submit the refund request to Payflow Pro.
  $response = $this
    ->apiRequest('pro', $nvp, $order);

  // If the credit succeeded...
  if (intval($response['RESULT']) === 0) {

    // 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');
    }
    else {
      $payment
        ->setState('refunded');
    }
    $payment
      ->setRemoteState('C');
    $payment
      ->setRefundedAmount($new_refunded_amount);
    $payment
      ->save();
  }
  else {
    throw new PaymentGatewayException($this
      ->t('Refund failed: @reason', [
      '@reason' => $response['RESPMSG'],
    ]), $response['RESULT']);
  }
}