You are here

function commerce_paypal_checkout_capture_form_submit in Commerce PayPal 7.2

Submit handler: process a prior authorization capture via PayPal Checkout.

File

modules/checkout/includes/commerce_paypal_checkout.admin.inc, line 87
Administrative forms for the Paypal Checkout module.

Code

function commerce_paypal_checkout_capture_form_submit($form, &$form_state) {
  $transaction = $form_state['transaction'];
  $order = $form_state['order'];
  $order_wrapper = entity_metadata_wrapper('commerce_order', $order);
  $order_total = $order_wrapper->commerce_order_total
    ->value();
  $amount = commerce_currency_decimal_to_amount($form_state['values']['amount'], $transaction->currency_code);
  $api_client = commerce_paypal_checkout_api_client($form_state['payment_method']['settings']);
  $params = array(
    'final_capture' => $order_total['amount'] == $amount,
    'amount' => array(
      'value' => commerce_paypal_checkout_price_amount($amount, $transaction->currency_code),
      'currency_code' => $transaction->currency_code,
    ),
  );
  try {

    // If the transaction was authorized more than 3 days ago, we need to
    // re-authorize the payment.
    if (time() >= $transaction->created + 86400 * 3) {
      $api_client
        ->reAuthorizePayment($transaction->remote_id, array(
        'amount' => $params['amount'],
      ));
    }
    $response = $api_client
      ->capturePayment($transaction->remote_id, $params);
    if (strtolower($response['status']) == 'completed') {
      $transaction->status = COMMERCE_PAYMENT_STATUS_SUCCESS;
    }
    else {
      $transaction->status = COMMERCE_PAYMENT_STATUS_FAILURE;
    }
    $transaction->remote_id = $response['id'];
    $transaction->amount = $amount;
    $transaction->remote_status = $response['status'];

    // Note the capture in the transaction message.
    $transaction->message .= '<br />' . t('Captured: @date', array(
      '@date' => format_date(REQUEST_TIME, 'short'),
    ));
    $transaction->payload[REQUEST_TIME . '-capture'] = $response;

    // Save the updated original transaction.
    commerce_payment_transaction_save($transaction);
  } catch (PayPalCheckoutHttpException $exception) {
    watchdog_exception('commerce_paypal_checkout', $exception);

    // Display an error message but leave the transaction pending.
    drupal_set_message(t('Prior authorization capture failed, so the transaction will remain in a pending status.'), 'error');
  }

  // Redirect back to the current order payment page.
  $form_state['redirect'] = 'admin/commerce/orders/' . $form_state['order']->order_id . '/payment';
}