Jump to content
  • Checkout
  • Login
  • Get in touch

osCommerce

The e-commerce.

Adding Google Analytics tracking code to osC


woolef

Recommended Posts

Raiwa - when you generate the code at the analytics site it uses the shopdomain.com - so I would agree with Altoids' observation.

@@altoid, @@Roaddoctor,

 

I know this, that's why I tried first with shopdomain.com and wanted to add the separate affiliation entry. Then I tested with STORENAME and it worked too, so I decided to leave it more simple.

 

Sure we are talking about an updated Google Analytics account to Universal Analytics?

Link to comment
Share on other sites

@@altoid, @@Roaddoctor,

 

I know this, that's why I tried first with shopdomain.com and wanted to add the separate affiliation entry. Then I tested with STORENAME and it worked too, so I decided to leave it more simple.

 

Sure we are talking about an updated Google Analytics account to Universal Analytics?

Hello, yes confirming this is for Universal Analytics. I only made that change because Google was not showing data after the upgrade. I cannot say for certainty what caused what but since the timing was there I looked further. I can revert to the original code you provided and see what happens after a couple days, no big deal if the data is affected.

I am not a professional webmaster or PHP coder by background or training but I will try to help as best I can.

I remember what it was like when I first started with osC. It can be overwhelming.

However, I strongly recommend considering hiring a professional for extensive site modifications, site cleaning, etc.

There are several good pros here on osCommerce. Look around, you'll figure out who they are.

Link to comment
Share on other sites

@@altoid, @@Roaddoctor,

 

I know this, that's why I tried first with shopdomain.com and wanted to add the separate affiliation entry. Then I tested with STORENAME and it worked too, so I decided to leave it more simple.

 

Sure we are talking about an updated Google Analytics account to Universal Analytics?

@@altoid, @@Roaddoctor,

 

I found the development version with additional affiliation field. Please try and confirm:

Uninstall old version before replace.

<?php
/*
  $Id$

  osCommerce, Open Source E-Commerce Solutions
  http://www.oscommerce.com

  Copyright (c) 2010 osCommerce

  Updated for Google Universal Analytics 2014 by @raiwa
  
  Released under the GNU General Public License
*/

  class ht_google_analytics {
    var $code = 'ht_google_analytics';
    var $group = 'header_tags';
    var $title;
    var $description;
    var $sort_order;
    var $enabled = false;

    function ht_google_analytics() {
      $this->title = MODULE_HEADER_TAGS_GOOGLE_ANALYTICS_TITLE;
      $this->description = MODULE_HEADER_TAGS_GOOGLE_ANALYTICS_DESCRIPTION;

      if ( defined('MODULE_HEADER_TAGS_GOOGLE_ANALYTICS_STATUS') ) {
        $this->sort_order = MODULE_HEADER_TAGS_GOOGLE_ANALYTICS_SORT_ORDER;
        $this->enabled = (MODULE_HEADER_TAGS_GOOGLE_ANALYTICS_STATUS == 'True');
      }
    }

    function execute() {
      global $PHP_SELF, $oscTemplate, $customer_id;

      if (tep_not_null(MODULE_HEADER_TAGS_GOOGLE_ANALYTICS_ID) && tep_not_null(MODULE_HEADER_TAGS_GOOGLE_ANALYTICS_AFFILIATION)) {
        if (MODULE_HEADER_TAGS_GOOGLE_ANALYTICS_JS_PLACEMENT != 'Header') {
          $this->group = 'footer_scripts';
        }

        $header = '<script>;' . "\n";
        $header .= "  (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
  (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
  m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
  })(window,document,'script','//www.google-analytics.com/analytics.js','ga');" . "\n";
  
        $header .= "  ga('create', '" . tep_output_string(MODULE_HEADER_TAGS_GOOGLE_ANALYTICS_ID) . "', '" . tep_output_string(MODULE_HEADER_TAGS_GOOGLE_ANALYTICS_AFFILIATION) . "');
  ga('send', 'pageview');" . "\n";

        if ( (MODULE_HEADER_TAGS_GOOGLE_ANALYTICS_EC_TRACKING == 'True') && (basename($PHP_SELF) == FILENAME_CHECKOUT_SUCCESS) && tep_session_is_registered('customer_id') ) {
          $order_query = tep_db_query("select orders_id, billing_city, billing_state, billing_country from " . TABLE_ORDERS . " where customers_id = '" . (int)$customer_id . "' order by date_purchased desc limit 1");

          if (tep_db_num_rows($order_query) == 1) {
            $order = tep_db_fetch_array($order_query);

            $totals = array();

            $order_totals_query = tep_db_query("select value, class from " . TABLE_ORDERS_TOTAL . " where orders_id = '" . (int)$order['orders_id'] . "'");
            while ($order_totals = tep_db_fetch_array($order_totals_query)) {
              $totals[$order_totals['class']] = $order_totals['value'];
            }

            $header .= "  ga('require', 'ecommerce', 'ecommerce.js');" . "\n";
            $header .= "  ga('ecommerce:addTransaction',{
    'id': '" . (int)$order['orders_id'] . "',
    'affiliation': '" . tep_output_string(MODULE_HEADER_TAGS_GOOGLE_ANALYTICS_AFFILIATION) . "',
    'revenue': '" . (isset($totals['ot_total']) ? $this->format_raw($totals['ot_total'], DEFAULT_CURRENCY) : 0) . "',
    'shipping': '" . (isset($totals['ot_shipping']) ? $this->format_raw($totals['ot_shipping'], DEFAULT_CURRENCY) : 0) . "', 
    'tax': '" . (isset($totals['ot_tax']) ? $this->format_raw($totals['ot_tax'], DEFAULT_CURRENCY) : 0) . "'
  });" . "\n";

            $order_products_query = tep_db_query("select op.products_id, pd.products_name, op.final_price, op.products_quantity from " . TABLE_ORDERS_PRODUCTS . " op, " . TABLE_PRODUCTS_DESCRIPTION . " pd, " . TABLE_LANGUAGES . " l where op.orders_id = '" . (int)$order['orders_id'] . "' and op.products_id = pd.products_id and l.code = '" . tep_db_input(DEFAULT_LANGUAGE) . "' and l.languages_id = pd.language_id");
            while ($order_products = tep_db_fetch_array($order_products_query)) {
              $category_query = tep_db_query("select cd.categories_name from " . TABLE_CATEGORIES_DESCRIPTION . " cd, " . TABLE_PRODUCTS_TO_CATEGORIES . " p2c, " . TABLE_LANGUAGES . " l where p2c.products_id = '" . (int)$order_products['products_id'] . "' and p2c.categories_id = cd.categories_id and l.code = '" . tep_db_input(DEFAULT_LANGUAGE) . "' and l.languages_id = cd.language_id limit 1");
              $category = tep_db_fetch_array($category_query);

              $header .= "  ga('ecommerce:addItem', {
    'id': '" . (int)$order['orders_id'] . "',
    'sku': '" . (int)$order_products['products_id'] . "',
    'name': '" . tep_output_string($order_products['products_name']) . "',
    'category': '" . tep_output_string($category['categories_name']) . "',
    'price': '" . $this->format_raw($order_products['final_price']) . "',
    'quantity': '" . (int)$order_products['products_quantity'] . "'
  });" . "\n";
            }

            $header .= "  ga('ecommerce:send');" . "\n";
          }
        }

        $header .= '</script>' . "\n";

        $oscTemplate->addBlock($header, $this->group);
      }
    }

    function format_raw($number, $currency_code = '', $currency_value = '') {
      global $currencies, $currency;

      if (empty($currency_code) || !$currencies->is_set($currency_code)) {
        $currency_code = $currency;
      }

      if (empty($currency_value) || !is_numeric($currency_value)) {
        $currency_value = $currencies->currencies[$currency_code]['value'];
      }

      return number_format(tep_round($number * $currency_value, $currencies->currencies[$currency_code]['decimal_places']), $currencies->currencies[$currency_code]['decimal_places'], '.', '');
    }

    function isEnabled() {
      return $this->enabled;
    }

    function check() {
      return defined('MODULE_HEADER_TAGS_GOOGLE_ANALYTICS_STATUS');
    }

    function install() {
      tep_db_query("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function, date_added) values ('Enable Google Analytics Module', 'MODULE_HEADER_TAGS_GOOGLE_ANALYTICS_STATUS', 'True', 'Do you want to add Google Analytics to your shop?', '6', '1', 'tep_cfg_select_option(array(\'True\', \'False\'), ', now())");
      tep_db_query("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('Google Analytics ID', 'MODULE_HEADER_TAGS_GOOGLE_ANALYTICS_ID', '', 'The Google Analytics profile ID to track.', '6', '0', now())");
      tep_db_query("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('Google Analytics Affiliation', 'MODULE_HEADER_TAGS_GOOGLE_ANALYTICS_AFFILIATION', '', 'The Google Analytics profile Affiliation to track.', '6', '0', now())");
      tep_db_query("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function, date_added) values ('E-Commerce Tracking', 'MODULE_HEADER_TAGS_GOOGLE_ANALYTICS_EC_TRACKING', 'True', 'Do you want to enable e-commerce tracking? (E-Commerce tracking must also be enabled in your Google Analytics profile settings)', '6', '1', 'tep_cfg_select_option(array(\'True\', \'False\'), ', now())");
      tep_db_query("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function, date_added) values ('Javascript Placement', 'MODULE_HEADER_TAGS_GOOGLE_ANALYTICS_JS_PLACEMENT', 'Header', 'Should the Google Analytics javascript be loaded in the header or footer?', '6', '1', 'tep_cfg_select_option(array(\'Header\', \'Footer\'), ', now())");
      tep_db_query("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('Sort Order', 'MODULE_HEADER_TAGS_GOOGLE_ANALYTICS_SORT_ORDER', '0', 'Sort order of display. Lowest is displayed first.', '6', '0', now())");
    }

    function remove() {
      tep_db_query("delete from " . TABLE_CONFIGURATION . " where configuration_key in ('" . implode("', '", $this->keys()) . "')");
    }

    function keys() {
      return array('MODULE_HEADER_TAGS_GOOGLE_ANALYTICS_STATUS', 'MODULE_HEADER_TAGS_GOOGLE_ANALYTICS_ID', 'MODULE_HEADER_TAGS_GOOGLE_ANALYTICS_AFFILIATION', 'MODULE_HEADER_TAGS_GOOGLE_ANALYTICS_EC_TRACKING', 'MODULE_HEADER_TAGS_GOOGLE_ANALYTICS_JS_PLACEMENT', 'MODULE_HEADER_TAGS_GOOGLE_ANALYTICS_SORT_ORDER');
    }
  }
?>
Link to comment
Share on other sites

Raiwa, all I did was (temporarily hard coded) replace as Altoid suggested:

 

// $header .= " ga('create', '" . tep_output_string(MODULE_HEADER_TAGS_GOOGLE_ANALYTICS_ID) . "', '" . STORE_NAME . "');

 

with

 

$header .= " ga('create', '" . tep_output_string(MODULE_HEADER_TAGS_GOOGLE_ANALYTICS_ID) . "', 'myydomainnamehardcoded.com');

ga('send', 'pageview');" . "\n";

 

 

Now my shops source output matches with the analytics provided example code. I haven't tried your code above yet. Yes of course this is just a matter of how the shop owner has STORE_NAME defined. In my case I don't use a domain.com, hence the workaround being discussed.

-Dave

Link to comment
Share on other sites

@@altoid, @@Roaddoctor,

 

I found the development version with additional affiliation field. Please try and confirm:

Uninstall old version before replace.

OK, I'll install this and keep an eye on things for a few days then let you know.

 

Thanks

I am not a professional webmaster or PHP coder by background or training but I will try to help as best I can.

I remember what it was like when I first started with osC. It can be overwhelming.

However, I strongly recommend considering hiring a professional for extensive site modifications, site cleaning, etc.

There are several good pros here on osCommerce. Look around, you'll figure out who they are.

Link to comment
Share on other sites

Raiwa, all I did was (temporarily hard coded) replace as Altoid suggested:

 

// $header .= " ga('create', '" . tep_output_string(MODULE_HEADER_TAGS_GOOGLE_ANALYTICS_ID) . "', '" . STORE_NAME . "');

 

with

 

$header .= " ga('create', '" . tep_output_string(MODULE_HEADER_TAGS_GOOGLE_ANALYTICS_ID) . "', 'myydomainnamehardcoded.com');

ga('send', 'pageview');" . "\n";

 

 

Now my shops source output matches with the analytics provided example code. I haven't tried your code above yet. Yes of course this is just a matter of how the shop owner has STORE_NAME defined. In my case I don't use a domain.com, hence the workaround being discussed.

My store name is also setup different from the provided example by google: "mydomainnameame.com" and however it works.

Link to comment
Share on other sites

OK, I'll install this and keep an eye on things for a few days then let you know.

 

Thanks

if you could try a few days with the old code, it woul be good, just to see if it works for you.

Link to comment
Share on other sites

if you could try a few days with the old code, it woul be good, just to see if it works for you.

Will do, I'll let you know.

I am not a professional webmaster or PHP coder by background or training but I will try to help as best I can.

I remember what it was like when I first started with osC. It can be overwhelming.

However, I strongly recommend considering hiring a professional for extensive site modifications, site cleaning, etc.

There are several good pros here on osCommerce. Look around, you'll figure out who they are.

Link to comment
Share on other sites

Hello @@altoid, @@Roaddoctor,

I had a deeper look on the developer information for google universal analytics and found this:
http://www.oscommerce.com/forums/topic/335292-adding-google-analytics-tracking-code-to-osc/page-2#entry1699752
 

create

Creates a new default tracker object.

ga('create', trackingId, opt_configObject);

Parameters

String trackingId – The web property ID for the site being tracked.
Object opt_configObject – An optional object containing configuration field/value pairs.

Examples

Create a default tracker.

ga('create', 'UA-XXXX-Y', 'auto');

Note: The default tracker is given the name t0 by default.

Create a tracker using a custom cookie name.

ga('create', 'UA-XXXX-Y', 'auto', {'cookieName': '_ga2'});

Create a tracker using the Synchronous syntax:

var tracker = ga.create('UA-XXXX-Y', 'auto');

ga('create', ...) can accept both position arguments and object arguments for the trackingId, cookieDomain and name fields. Order is important. For example, the following two snippets are identical:

ga('create', 'UA-XXXX-Y', 'auto', 'T1000');

ga('create', {trackingId: 'UA-XXXX-Y', cookieDomain: 'auto', name: 'T1000'});

So it seems in this line:
ga('create', 'UA-XXXX-Y', 'auto');

the second parameter should be the cookie domain, so I suppose the wrong parameter STORE NAME is automatically replaced by the correct domain. That's why it works in my store I suppose. Maybe it doesn't work always.

So I suggest we could use: 

str_replace('www.', '', HTTP_SERVER)

instead of STORE NAME to keep things easy?

Or use 'auto' like they suggest here:

https://developers.google.com/analytics/devguides/collection/analyticsjs/?hl=en

<!-- Google Analytics -->
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');

ga('create', 'UA-XXXX-Y', 'auto');
ga('send', 'pageview');

</script>
<!-- End Google Analytics -->


In the e-commerce tracking part it's different, there they say:
https://developers.google.com/analytics/devguides/collection/gajs/gaTrackingEcommerce?hl=en

pageTracker._addTrans(
"1234", // transaction ID - required
"Womens Apparel", // affiliation or store name
"11.99", // total - required
"1.29", // tax
"15.00", // shipping
"San Jose", // city
"California", // state or province
"USA" // country
);

So here it doesn't matter which we use.

 

What are your thoughts?

 

Rainer

Link to comment
Share on other sites

@@raiwa

 

Thanks for researching this. Using str_replace('www.', '', HTTP_SERVER) my page source shows the results of http://mydomain dot com

 

Using just HTTP_SERVER I get http://www dot mydomain dot com which is what I have set up to show as the domain (with the www)

 

Right now, running Analytics in real time, it's showing me visiting and browsing the site so that is a good sign.

 

I'll let this run today and see how things go.

 

For now I have no specific preference as long as it works.

 

Thanks

I am not a professional webmaster or PHP coder by background or training but I will try to help as best I can.

I remember what it was like when I first started with osC. It can be overwhelming.

However, I strongly recommend considering hiring a professional for extensive site modifications, site cleaning, etc.

There are several good pros here on osCommerce. Look around, you'll figure out who they are.

Link to comment
Share on other sites

@@raiwa

 

Thanks for researching this. Using str_replace('www.', '', HTTP_SERVER) my page source shows the results of http://mydomain dot com

 

Using just HTTP_SERVER I get http://www dot mydomain dot com which is what I have set up to show as the domain (with the www)

 

Right now, running Analytics in real time, it's showing me visiting and browsing the site so that is a good sign.

 

I'll let this run today and see how things go.

 

For now I have no specific preference as long as it works.

 

Thanks

@@altoid,

 

Then it should be:

str_replace('http://www.', '', HTTP_SERVER)

although for subdomain stores maybe it should be then:

str_replace('http://', '', str_replace('www.', '', HTTP_SERVER))

Rainer

Link to comment
Share on other sites

Then it should be:

str_replace('http://www.', '', HTTP_SERVER)
although for subdomain stores maybe it should be then:

str_replace('http://', '', str_replace('www.', '', HTTP_SERVER))
Rainer

 

Great, thanks much for following up with this.

I am not a professional webmaster or PHP coder by background or training but I will try to help as best I can.

I remember what it was like when I first started with osC. It can be overwhelming.

However, I strongly recommend considering hiring a professional for extensive site modifications, site cleaning, etc.

There are several good pros here on osCommerce. Look around, you'll figure out who they are.

Link to comment
Share on other sites

  • 2 months later...

Hi,

 

Just had an error using Jim (kymaton)  PDF Datasheet contribution which is as picky as hell

[08-Sep-2014 08:32:01 America/New_York] PHP Warning:  Cannot modify header information - headers already sent by 

best debug module I have seen haha simple white space at the bottom of the module

 

Regards

John

To improve is to change; to be perfect is to change often.

 

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...