27 January 2008 19 Comments

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.

Share and Enjoy:
  • Twitter
  • Facebook
  • Google Bookmarks
  • del.icio.us
  • Posterous
  • Tumblr
  • FriendFeed
  • email

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

  1. tomson 27 January 2008 at 12:04 #

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

  2. Simo 27 January 2008 at 12:23 #

    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 13 March 2008 at 0:14 #

    Hi,
    Cool, thanks a lot!!
    Bas

    Webmaster Motortassen

  4. Racing Schools 6 July 2008 at 16:32 #

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

  5. Singapore Seminars 10 August 2008 at 19:55 #

    These codes rocks! More importantly, they work.

  6. Zack @ Katz Web Design 19 September 2008 at 18:48 #

    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 19 September 2008 at 18:49 #

    The PHP being `$transaction_string.$item_string;`

  8. Posy 25 September 2008 at 19:11 #

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

    thanks

    andy

  9. Andy 26 September 2008 at 12:56 #

    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 28 September 2008 at 11:04 #

    @ 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 1 October 2008 at 6:57 #

    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 2 May 2009 at 18:01 #

    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 3 May 2009 at 20:25 #

    @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 8 May 2009 at 4:53 #

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

  15. Bobbink - 11 Internet 21 June 2009 at 18:12 #

    Thanks for sharing, keep up the good work!

  16. Web Design Boynton Beach 13 July 2009 at 21:07 #

    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 15 July 2009 at 13:49 #

    Joris, are you not supporting this anymore?

  18. Robson Gomes 27 November 2009 at 1:02 #

    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?


Trackbacks/Pingbacks.

  1. Getting the current order ID in osCommerce | Media Growl Blog - 17. Nov, 2009

    [...] 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 [...]

Leave a Reply