E-commerce tracking in osCommerce with new Google Analytics tracking code

A few days ago, I was working on an existing osCommerce webshop and decided to install the new Google Analytics Tracking Code. Changing the script in the footer wasn’t all that had to be done (unfortunately). Since almost all functions have changed, the e-commerce script that registers the transaction also needed a few changes.

New Google Analytics Tracking Code (GATC ga.js)

I took a look around and couldn’t find the adjusted osCommerce code. The only solution was to program it myself and in order to spare you some valuable time, here it is…

The code below needs to be implemented on the checkout_success.php page.

First thing to do is build a transaction line and one or more item lines that will be used in the new pageTracker._addTrans() and pageTracker._addItem() functions.

// ############## Google Analytics - start ###############
// by Joris Roebben www.queromedia.com

// Is partner cookie set ?
if (isset($_COOKIE["PartnerCookie"])) {
    $partner = $_COOKIE["PartnerCookie"];
} else {
    $partner = 'none';
}

// Get order id
    $orders_query = tep_db_query("select orders_id from " . TABLE_ORDERS . " where customers_id = '" . (int)$customer_id . "' order by date_purchased desc limit 1");
    $orders = tep_db_fetch_array($orders_query);
    $order_id = $orders['orders_id'];

// Get order info for Analytics "Transaction line" (affiliation, city, state, country, total, tax and shipping)

// Set value for  "affiliation"
    $analytics_affiliation = $partner;

// Get info for "city", "state", "country"
    $orders_query = tep_db_query("select customers_city, customers_state, customers_country from " . TABLE_ORDERS . " where orders_id = '" . $order_id . "' AND customers_id = '" . (int)$customer_id . "'");
    $orders = tep_db_fetch_array($orders_query);
    $totals_query = tep_db_query("select value, class from " . TABLE_ORDERS_TOTAL . " where orders_id = '" . (int)$order_id . "' order by sort_order");
// Set values for "total", "tax" and "shipping"
    $analytics_total = '';
    $analytics_tax = '';
    $analytics_shipping = '';
     while ($totals = tep_db_fetch_array($totals_query)) {
        if ($totals['class'] == 'ot_total') {
            $analytics_total = number_format($totals['value'], 2);
            $total_flag = 'true';
        } else if ($totals['class'] == 'ot_tax') {
            $analytics_tax = number_format($totals['value'], 2);
            $tax_flag = 'true';
        } else if ($totals['class'] == 'ot_shipping') {
            $analytics_shipping = number_format($totals['value'], 2);
            $shipping_flag = 'true';
        }
     }

// Prepare the Analytics "Transaction line" string
    $transaction_string = 'pageTracker._addTrans("' . $order_id . '","' . $analytics_affiliation . '","' . str_replace(",", "", $analytics_total) . '","' . $analytics_tax . '","' . $analytics_shipping . '","' . $orders['customers_city'] . '","' . $orders['customers_state'] . '","' . $orders['customers_country'] . '");';

// Get products info for Analytics "Item lines"
    $item_string = '';
    $items_query = tep_db_query("select products_id, products_model, products_name, final_price, products_quantity from " . TABLE_ORDERS_PRODUCTS . " where orders_id = '" . $order_id . "' order by products_name");
    while ($items = tep_db_fetch_array($items_query)) {
		$category_query = tep_db_query("select p2c.categories_id, cd.categories_name from " . TABLE_PRODUCTS_TO_CATEGORIES . " p2c, " . TABLE_CATEGORIES_DESCRIPTION . " cd where p2c.products_id = '" . $items['products_id'] . "' AND cd.categories_id = p2c.categories_id AND cd.language_id = '" . (int)$languages_id . "'");
		$category = tep_db_fetch_array($category_query);

    $item_string .= 'pageTracker._addItem("' . $order_id . '","' . $items['products_id'] . '","' . $items['products_name'] . '","' . $category['categories_name'] . '","' . str_replace(",", "", number_format($items['final_price'], 2)) . '","' . $items['products_quantity'] . '");';
    }

// ############## Google Analytics - end ###############

// To test your installation, uncomment next line
//echo $transaction_string . $item_string;
?>

Next thing we need is a call to the new Google Analytics Tracking Code, using the transaction string and item string to register the total transaction and all items included in the transaction:

<script type="text/javascript">
var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
</script>

<script type="text/javascript">
  var pageTracker = _gat._getTracker("UA-xxxxxx-x");
  pageTracker._initData();
  pageTracker._trackPageview();

  <?php echo $transaction_string.$item_string; ?>

  pageTracker._trackTrans();
</script>

That’s it ! Give it a try and should you encounter any problem, let me know.

Comments

19 responses to “E-commerce tracking in osCommerce with new Google Analytics tracking code”

  1. tomson Avatar

    That is a nice piece of programming, JayAre. Cheers!

  2. Simo Avatar

    Nice one!!!
    Are you going to submit this on the osCommerce forum?

    If so, you might wanna leave the partner section out of it ;)

  3. bas Avatar

    Hi,
    Cool, thanks a lot!!
    Bas

    Webmaster Motortassen

  4. Racing Schools Avatar

    The analytic codes were great. I’ve tried them.

  5. Singapore Seminars Avatar

    These codes rocks! More importantly, they work.

  6. Zack @ Katz Web Design Avatar

    Thanks Joris! This worked great.

    I am using STS, and for others who may have issues, what you need to do is add the first code to checkout_success.php somewhere in the main code (I put it right after the CHECKOUT_BAR_FINISHED section of the code. Then, you need to add the PHP to the bottom of the STS template you’re using.

    Thanks again, saved me tons of work!

  7. Zack @ Katz Web Design Avatar

    The PHP being `$transaction_string.$item_string;`

  8. Posy Avatar

    Thanks for this but… where in checkout_success.php do i put the 2 bits of code?

    thanks

    andy

  9. Andy Avatar

    err HELP

    I left a request for help but it seems to have dissapeared?

    I have treid this on our site and cant get it to work. I dont know if I have put the code in the right place in checkout_success.php .

    when i use the test line it prints out the correct responce but google is receiving nothing?

    any pointers would be great

    thanks

  10. JayAre Avatar

    @ Zack: You’re welcome

    @ Posy: just make sure you put the 2 bits of code in the body-section of checkout_success.php. The first bit is to construct the correct string you then use in the second bit, where you make the call to Google Analytics (the registration of the transaction). The lower in the code you put them, the better. Just make sure the first one is above the second one.

    @ Andy: As I understand it, you put the two bits of code in your checkout_success.php. Have you replaced the “UA-xxxxxx-x” with your own personal account number. If not, no e-commerce tracking will be registered in your account. And have you checked whether your site uses the new Google Analytics tracking code? It is not advised to combine the old one with the new one on the same website.
    If that’s not the problem, feel free to let me know.

  11. E-commerce Reviewer Avatar

    Good idea to implement tracking in the checkout phase to see exactly at what point baskets get abandoned. Sometimes people abandon baskets because they get a nasty surprise with shipping costs for example.

  12. hawa Avatar

    hello – testing out the code posted – looks like its reading everythig ok, but now my Goals seem to not be reading accurately…. have u had any similar issues with this?

    thank you!
    hiro

  13. Joris Avatar

    @hawa Make sure you install the second code snippet and replace the UA-xxxxxx-x with your own code. If you forgot the last, tracking of your goals will not work. Is that the problem?

  14. hawa Avatar

    hi J
    thank you for the response – everything seems to be working now… thank you so much!

  15. Bobbink - 11 Internet Avatar

    Thanks for sharing, keep up the good work!

  16. Web Design Boynton Beach Avatar

    Am I the only one that noticed that you can’t put the javascript in the body of the PHP?

    Also, now the the code is in, when the user successfully checks out, they are redirected to a “Your Cart is Empty” page. The invoice still comes through but not the confirmation page (checkout_success.php).

    From checkout_confirmation.php to shopping_cart.php.

    Please advise!

    Thanks!

  17. Web Design Boynton Beach Avatar

    Joris, are you not supporting this anymore?

  18. […] get the current order ID of a transaction in progress. This is probably because you want to put a Google Analytics Tracking Code or you might want to save the transaction ID generated by your payment gateway into your […]

  19. Robson Gomes Avatar

    I put the first code inside javascript tags the same way as is the second … but did not understand how to code .. Is this it?

Leave a Reply

Your email address will not be published. Required fields are marked *