You are here

function commerce_square_refund_form_submit in Commerce Square Connect 7

Confirm form submit callback to refund an order.

File

includes/commerce_square.admin.inc, line 190
Provides admin menu callbacks for Commerce Square.

Code

function commerce_square_refund_form_submit($form, $form_state) {
  $transaction = $form_state['transaction'];
  $amount = commerce_currency_decimal_to_amount($form_state['values']['amount'], $transaction->currency_code);
  $client = SquareApi::createFromInstanceId($transaction->instance_id);
  try {
    $result = $client
      ->refund($transaction, $amount);
    $refund_transaction = commerce_payment_transaction_new('commerce_square', $transaction->order_id);
    $refund_transaction->instance_id = $transaction->instance_id;
    $refund_transaction->amount = -$amount;
    $refund_transaction->currency_code = $transaction->currency_code;
    $refund_transaction->status = COMMERCE_PAYMENT_STATUS_SUCCESS;
    $remote_transaction = $result
      ->getRefund();
    $tender_id = $remote_transaction
      ->getTenderId();
    $refund_transaction->remote_id = $remote_transaction
      ->getId() . '|' . $tender_id;
    $refund_transaction->order_id = $transaction->order_id;
    $refund_transaction->message = t('Manual refund');
    commerce_payment_transaction_save($refund_transaction);
    drupal_set_message(t('Amount successfully refunded'), 'status');
  } catch (ApiException $e) {

    /** @var \SquareConnect\Model\VoidTransactionResponse $result */
    $result = $e
      ->getResponseObject();
    foreach ($result
      ->getErrors() as $error) {
      drupal_set_message(sprintf('%s %s %s', $error
        ->getCode(), $error
        ->getCategory(), $error
        ->getDetail()), 'error');
    }
  } catch (Exception $e) {
    drupal_set_message(t('There was an error refunding the transaction: @message', array(
      '@message' => $e
        ->getMessage(),
    )), 'error');
  }

  // Redirect to payments page.
  drupal_goto('admin/commerce/orders/' . $transaction->order_id . '/payment');
}