You are here

function uc_googleanalytics_ecommerce_js in Ubercart 6.2

Same name and namespace in other branches
  1. 8.4 uc_googleanalytics/uc_googleanalytics.module \uc_googleanalytics_ecommerce_js()
  2. 7.3 uc_googleanalytics/uc_googleanalytics.module \uc_googleanalytics_ecommerce_js()

Build the e-commerce JS passed to Google Analytics for order tracking.

Supports Google Analytics 2.x, 3.x and 4.x.

Parameters

$order: The fully loaded order object to convert into GA JS.

Return value

The JS that should be added to the page footer.

1 call to uc_googleanalytics_ecommerce_js()
uc_googleanalytics_footer in uc_googleanalytics/uc_googleanalytics.module
Implements hook_footer().

File

uc_googleanalytics/uc_googleanalytics.module, line 96
Adds the required Javascript to the checkout completion page to allow e-commerce statistics tracking through Google Analytics.

Code

function uc_googleanalytics_ecommerce_js($order) {
  $script2 = '';
  $script3 = '';
  $script4 = 'ga("require", "ecommerce");';

  // Lookup the name of the country or default to the ID if it can't be found
  // for some reason.
  if ($country_data = uc_get_country_data(array(
    'country_id' => $order->billing_country,
  ))) {
    $order->billing_country_name = $country_data[0]['country_name'];
  }
  else {
    $order->billing_country_name = $order->billing_country;
  }

  // Lookup the name of the zone.
  $order->billing_zone_name = uc_zone_get_by_id($order->billing_zone);

  // Calculate order tax and shipping totals.
  $order->tax_total = 0;
  $order->shipping_total = 0;
  foreach ($order->line_items as $line_item) {
    if ($line_item['type'] == 'tax') {
      $order->tax_total += $line_item['amount'];
    }
    elseif ($line_item['type'] == 'shipping') {
      $order->shipping_total += $line_item['amount'];
    }
  }

  // Build the transaction arguments.
  $trans = array(
    'order_id' => $order->order_id,
    'store' => variable_get('uc_store_name', variable_get('site_name', 'Ubercart')),
    'total' => $order->order_total,
    'tax' => $order->tax_total,
    'shipping' => $order->shipping_total,
    'city' => $order->billing_city,
    'state' => $order->billing_zone_name,
    'country' => $order->billing_country_name,
  );

  // Allow modules to alter the transaction arguments.
  drupal_alter('ucga_trans', $trans, $order);

  // Put the arguments into an array that is safe to implode directly.
  $args = array(
    '"' . $trans['order_id'] . '"',
    drupal_to_js($trans['store']),
    '"' . $trans['total'] . '"',
    '"' . $trans['tax'] . '"',
    '"' . $trans['shipping'] . '"',
    drupal_to_js($trans['city']),
    drupal_to_js($trans['state']),
    drupal_to_js($trans['country']),
  );

  // Create Google Universal Analytics friendly associative array.
  $universal_args = array(
    'id' => $trans['order_id'],
    'affiliation' => $trans['store'],
    'revenue' => $trans['total'],
    'tax' => $trans['tax'],
    'shipping' => $trans['shipping'],
    'city' => $trans['city'],
    'region' => $trans['state'],
    'country' => $trans['country'],
  );

  // Add the transaction line to the JS.
  $script2 .= 'pageTracker._addTrans(' . implode(', ', $args) . ');';
  $script3 .= '_gaq.push(["_addTrans", ' . implode(', ', $args) . ']);';
  $script4 .= 'ga("ecommerce:addTransaction", ' . drupal_to_js($universal_args) . ');';

  // Loop through the products on the order.
  foreach ($order->products as $product) {
    $product->category = '';

    // Try to find a category (term) for the product. Since products most often
    // only have one category, the first one returned (based on tid) is chosen.
    if (module_exists('taxonomy')) {
      $terms = taxonomy_node_get_terms(node_load($product->nid));
      if (count($terms)) {
        $term = array_shift($terms);
        $product->category = $term->name;
      }
    }
    if (empty($product->category)) {
      $product->category = t('No category');
    }

    // Build the item arguments.
    $item = array(
      'order_id' => $order->order_id,
      'sku' => $product->model,
      'name' => $product->title,
      'category' => $product->category,
      'price' => $product->price,
      'qty' => $product->qty,
    );

    // Allow modules to alter the item arguments.
    drupal_alter('ucga_item', $item, $product, $trans, $order);

    // Create a context for uc_price
    $context = array(
      'revision' => 'altered',
      'type' => 'order_product',
      'caller' => 'uc_googleanalytics',
      'subject' => array(
        'order_product' => $product,
        'order' => $order,
        'node' => node_load($product->nid),
      ),
    );

    // Put the arguments into an array that is safe to implode directly.
    $args = array(
      '"' . $item['order_id'] . '"',
      drupal_to_js($item['sku']),
      drupal_to_js($item['name']),
      drupal_to_js((string) $item['category']),
      '"' . uc_price($item['price'], $context) . '"',
      '"' . $item['qty'] . '"',
    );

    // Create Google Universal Analytics friendly associative array.
    $universal_args = array(
      'id' => $item['order_id'],
      'sku' => $item['sku'],
      'name' => $item['name'],
      'category' => (string) $item['category'],
      'price' => uc_price($item['price'], $context),
      'quantity' => $item['qty'],
    );

    // Add the item line to the JS.
    $script2 .= 'pageTracker._addItem(' . implode(', ', $args) . ');';
    $script3 .= '_gaq.push(["_addItem", ' . implode(', ', $args) . ']);';
    $script4 .= 'ga("ecommerce:addItem", ' . drupal_to_js($universal_args) . ');';
  }

  // Add the function to submit the transaction to GA.
  $script2 .= 'pageTracker._trackTrans();';
  $script3 .= '_gaq.push(["_trackTrans"]);';
  $script4 .= 'ga("ecommerce:send");';

  // Detect Google Analytics module version.
  $version = db_result(db_query("SELECT schema_version FROM {system} WHERE type = 'module' AND name = 'googleanalytics'"));
  if ($version >= 6400) {
    return $script4;
  }
  elseif ($version >= 6300) {
    return $script3;
  }
  else {
    return $script2;
  }
}