You are here

function commerce_amex_cardonfile_save in Commerce American Express Payment Gateway (Amex) 7

Request a token from Amex for a session and save the Card of File entity.

Parameters

object $order: The order - used for the user id and billing address.

object $payment_method: The payment method being used.

object $transaction: The transaction the card being saved was used in for the remote session id.

Return value

boolean

1 call to commerce_amex_cardonfile_save()
_commerce_amex_process_transaction in ./commerce_amex.module

File

./commerce_amex.module, line 1198
Implements American Express payment gateway for use in Drupal Commerce.

Code

function commerce_amex_cardonfile_save($order, $payment_method, $transaction) {
  $data = new stdClass();
  $data->sourceOfFunds['session'] = $transaction->remote_id;
  $data->sourceOfFunds['type'] = 'CARD';
  $url = $payment_method['settings']['txn_url'] . AMEX_TXN_PATH . $payment_method['settings']['merchant_id'] . '/token';
  $result = _commerce_amex_post_request($url, $payment_method['settings']['merchant_id'], $payment_method['settings']['password'], $data);

  // Process error and return false.
  if (isset($result->result) && $result->result == 'ERROR') {
    $transaction = _commerce_amex_error_process($result, $transaction);
    drupal_set_message(t('Unable to save your card data due to a remote server error'), 'error');
    return FALSE;
  }
  if (isset($result->token)) {
    $card_data = commerce_cardonfile_new();
    $card_data->uid = $order->uid;
    $card_data->payment_method = $payment_method['method_id'];
    $card_data->instance_id = $payment_method['instance_id'];
    $card_data->remote_id = $result->token;
    $card_data->card_type = !empty($result->sourceOfFunds->provided->card->scheme) ? strtolower($result->sourceOfFunds->provided->card->scheme) : 'card';
    $card_data->card_name = $transaction->data['owner'];
    $card_data->card_number = drupal_substr($result->sourceOfFunds->provided->card->number, -4);
    $card_data->card_exp_month = $result->sourceOfFunds->provided->card->expiry->month;
    $card_data->card_exp_year = 2000 + $result->sourceOfFunds->provided->card->expiry->year;
    $card_data->status = 1;
    $billing_profile = commerce_customer_profile_load($order->commerce_customer_billing[LANGUAGE_NONE][0]['profile_id']);

    // Save the new card on file.
    if (commerce_cardonfile_save($card_data, $billing_profile)) {
      return TRUE;
    }
    else {
      drupal_set_message(t('Unable to save your card data due to a server error'), 'error');
      return FALSE;
    }
  }
}