You are here

public function Square::refundPayment in Commerce Square Connect 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/Square.php, line 409

Class

Square
Provides the Square payment gateway.

Namespace

Drupal\commerce_square\Plugin\Commerce\PaymentGateway

Code

public function refundPayment(PaymentInterface $payment, Price $amount = NULL) {
  $this
    ->assertPaymentState($payment, [
    'completed',
    'partially_refunded',
  ]);
  $amount = $amount ?: $payment
    ->getAmount();

  // Square only accepts integers and not floats.
  // @see https://docs.connect.squareup.com/api/connect/v2/#workingwithmonetaryamounts
  $square_amount = $this
    ->toMinorUnits($amount);
  list($transaction_id, $tender_id) = explode('|', $payment
    ->getRemoteId());
  $refund_request = new CreateRefundRequest([
    'idempotency_key' => uniqid(),
    'tender_id' => $tender_id,
    'amount_money' => new Money([
      'amount' => $square_amount,
      'currency' => $amount
        ->getCurrencyCode(),
    ]),
    'reason' => (string) $this
      ->t('Refunded through store backend'),
  ]);
  $mode = $this
    ->getMode();
  try {
    $transaction_api = new TransactionsApi($this
      ->getApiClient());
    $result = $transaction_api
      ->createRefund($this->configuration[$mode . '_location_id'], $transaction_id, $refund_request);
  } catch (ApiException $e) {
    throw ErrorHelper::convertException($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();
}