You are here

function commerce_braintree_js_create_cardonfile in Commerce Braintree 7.3

Same name and namespace in other branches
  1. 7.2 commerce_braintree.module \commerce_braintree_js_create_cardonfile()

Save a cardonfile entity from the JS based payment response.

1 call to commerce_braintree_js_create_cardonfile()
commerce_braintree_js_form_submit in ./commerce_braintree.module
Submit callback for the Braintree JS based payment methods.

File

./commerce_braintree.module, line 968
Integrates Braintree Transparent Redirect with Drupal Commerce.

Code

function commerce_braintree_js_create_cardonfile($order, $payment_method, $response) {
  if (empty($response->transaction->creditCard)) {
    watchdog('commerce_braintree', 'Cannot create card on file entity for order @order_id because there was no credit card property in the response provided by Braintree', array(
      '@order_id' => $order->order_id,
    ), WATCHDOG_ERROR);
    return FALSE;
  }
  $token = $response->transaction->creditCard['token'];

  // Attempt to load an existing card on file with the same token before
  // creating a new one.
  $cards = commerce_cardonfile_load_multiple(FALSE, array(
    'remote_id' => $token,
  ));
  if (!empty($cards)) {
    $cardonfile = reset($cards);
  }
  else {
    $cardonfile = commerce_cardonfile_new();
  }

  // Populate all of the cardonfile properties from the response object.
  $cardonfile->card_name = $response->transaction->billing['firstName'] . ' ' . $response->transaction->billing['lastName'];
  $cardonfile->card_type = $response->transaction->creditCard['cardType'];
  $cardonfile->card_exp_month = $response->transaction->creditCard['expirationMonth'];
  $cardonfile->card_exp_year = $response->transaction->creditCard['expirationYear'];
  $cardonfile->card_number = $response->transaction->creditCard['last4'];
  $cardonfile->payment_method = $payment_method['method_id'];
  $cardonfile->instance_id = $payment_method['instance_id'];
  $cardonfile->instance_default = TRUE;
  $cardonfile->uid = $order->uid;
  $cardonfile->remote_id = $response->transaction->creditCard['token'];
  $cardonfile->status = TRUE;
  commerce_cardonfile_save($cardonfile);

  // Save the Braintree vault data to the user profile.
  $user = user_load($order->uid);
  $user->data['braintree_vault'] = $response->transaction->customer;
  user_save($user);
}