You are here

function commerce_braintree_dropin_cardonfile_form in Commerce Braintree 7.2

Same name and namespace in other branches
  1. 7.3 modules/commerce_braintree_dropin/commerce_braintree_dropin.module \commerce_braintree_dropin_cardonfile_form()

Form callback for commerce_cardonfile entities.

File

modules/commerce_braintree_dropin/commerce_braintree_dropin.module, line 217
Provides integration with Braintree Drop-in UI.

Code

function commerce_braintree_dropin_cardonfile_form($form, &$form_state, $op, $card) {
  $form_state['card'] = $card;
  $account = user_load($card->uid);
  $arguments = array();
  $payment_instance = commerce_payment_method_instance_load($card->instance_id);
  $form_state['payment_instance'] = $payment_instance;
  commerce_braintree_initialize($payment_instance);
  if (!empty($card->remote_id)) {

    // Query Braintree for the payment method matching this card on file.
    try {
      $payment_method = \Braintree_PaymentMethod::find($card->remote_id);
    } catch (Exception $ex) {

      // If Braintree doesn't return the payment method, we cannot proceed.
      drupal_set_message(t('We are unable to locate your stored payment method'), 'error');
      watchdog('commerce_braintree_dropin', 'Unable to fetch Braintree payment method due to @error', array(
        '@error' => $ex
          ->getMessage(),
      ), WATCHDOG_ERROR);
      return array();
    }
  }

  // Determine the Braintree customer id and append it to the API request.
  if (!empty($account->data) && !empty($account->data['braintree_vault'])) {

    // Set the Braintree Customer ID if stored on the user object.
    $arguments['customerId'] = $account->data['braintree_vault']['id'];
  }
  else {
    if (!empty($payment_method->customerId)) {

      // Set the Braintree Customer ID from the loaded payment method.
      $arguments['customerId'] = $payment_method->customerId;
    }
  }

  // Append common the drop-in ui form elements to the form array.
  $form += (array) commerce_braintree_dropin_submit_form_elements($payment_instance, $arguments);

  // Remove the card on file options since we're always saving these.
  unset($form['cardonfile']);
  $form['customer_id'] = array(
    '#type' => 'value',
    '#value' => !empty($arguments['customerId']) ? $arguments['customerId'] : FALSE,
  );
  $form['actions'] = array(
    '#type' => 'container',
  );
  $form['actions']['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Save Payment Method'),
  );
  return $form;
}