Add GA e-commerce tracking in opencart

When I started blogging about Google code implementations like Google Conversion CodeGoogle Analytics Code and Ecommerce TrackingGoogle Remarketing Code and so on.

Many readers and developer asked to help to implement Google Analytics Ecommerce Tracking in Opencart (v1.x). So here it is.

In earlier post, I had described how to add Google Analytics code in Opencart.

Opencart Ecommerce

In this post, you will see how to add Google Analytics Ecommerce Tracking in Opencart. Since there is some extensions available for Opencart to add google analytics and ecommerce tracking, and for that you might have to buy that extension. Since I am developer, so I would prefer to deal with FTP rather than using any extensions. Before doing any changes in source code, I would to like to put it in highlight that always keep a backup of your website.

if you have kept back-up of your site, here it goes.

Steps to add Analytics Ecommerce Tracking in Opencart:

  • Login to FTP.
  • open order.php( file path \catalog\model\checkout\order.php)
  • Add the below code in order.php.
public function getOrderTax($order_id){
  $query = $this->db->query("SELECT * FROM " . DB_PREFIX . "order_total WHERE code = 'tax' AND order_id = '" . $order_id . "' LIMIT 1");
  return $query->row;	
}

public function getOrderShipping($order_id){
  $query = $this->db->query("SELECT * FROM " . DB_PREFIX . "order_total WHERE code = 'shipping' AND order_id = '" . $order_id . "' LIMIT 1");
  return $query->row;	
}

public function getOrderProducts($order_id){
  $query = $this->db->query("SELECT * FROM " . DB_PREFIX . "order_product WHERE order_id = '" . $order_id . "'");
  if($query->num_rows){
      return $query->rows;
  } else {
      return false;	
  }
}

Code will be like this.

<?php 
  class ModelCheckoutOrder extends Model {
    public function addOrder($data) {......} /* don't change any other methods/functions, leave them as it is. */ 
    /* NOC CODE BENGIN TO GET Order_Tax, Order_Shipping ,Order Products */
    public function getOrderTax($order_id) 
    {
      $query = $this->db->query("SELECT * FROM " . DB_PREFIX . "order_total WHERE code = 'tax' AND order_id = '" . $order_id . "' LIMIT 1");
      return $query->row;	
    }

    public function getOrderShipping($order_id){
      $query = $this->db->query("SELECT * FROM " . DB_PREFIX . "order_total WHERE code = 'shipping' AND order_id = '" . $order_id . "' LIMIT 1");
      return $query->row;	
    }

    public function getOrderProducts($order_id){
      $query = $this->db->query("SELECT * FROM " . DB_PREFIX . "order_product WHERE order_id = '" . $order_id . "'");
      if($query->num_rows){
          return $query->rows;
      } else {
          return false;	
      }
    }
    /* NOC CODE END HERE */
  }
  • Now save order.php and open success.php (file path  \catalog\controller\checkout\success.php).

Now in success.php, you have to add 2 codes on 2 places.

Code 1.

$order_id = $this->session->data['order_id'];

Code 2.

//NOC get Order-details
if(isset($order_id))
{
    //LOAD MODEL
    $this->load->model('checkout/order');
    
    //GET ORDER DETAILS
    $order_info = $this->model_checkout_order->getOrder($order_id);
    
    //NEW MODEL TO COLLECT TAX
    $get_order_tax = $this->model_checkout_order->getOrderTax($order_id);
    
    if($get_order_tax){
            //ASSIGN TAX TO NEW VARIABLE
            $order_tax = $get_order_tax['value'];
    } else {
            //THERE WAS NO TAX COLLECTED
            $order_tax = '';
    }
    
    //NEW MODEL TO COLLECT SHIPPING
    $get_order_shipping = $this->model_checkout_order->getOrderShipping($order_id);
    
    if($get_order_shipping){
            //ASSIGN SHIPPING TO NEW VARIABLE
            $order_shipping = $get_order_shipping['value'];
    } else {
            //THERE WAS NO SHIPPING COLLECTED
            $order_shipping = 0;
    }
    
    //NEW MODEL TO COLLECT ALL PRODUCTS ASSOCIATED WITH ORDER
    $get_order_products = $this->model_checkout_order->getOrderProducts($order_id);
    
    //CREATE ARRAY TO HOLD PRODUCTS
    $order_products = array();
    
    foreach($get_order_products as $prod){				
    
            $order_products[] = array(
                    'order_id'  => $order_id,
                    'model'     => $prod['model'],
                    'name'      => $prod['name'],
                    'category'  => '',
                    'price'     => number_format($prod['price'], 2, '.', ','),
                    'quantity'  => $prod['quantity']
            );
    
    }
    
    //NEW ORDER ARRAY
    $order_tracker = array(
            'order_id'    => $order_id,
            'store_name'  => $order_info['store_name'],
            'total'       => $order_info['total'],
            'tax'         => $order_tax,
            'shipping'    => $order_shipping,
            'city'        => $order_info['payment_city'],
            'state'       => $order_info['payment_zone'],
            'country'     => $order_info['payment_country'],
            'currency'    => $order_info['currency_code'],
            'products'    => $order_products
    );   
    $data['order_tracker'] = $order_tracker;
}

Code will be like this.

<?php 
class ControllerCheckoutSuccess extends Controller { 
  public function index() 
  { 
  $this->load->language('checkout/success');

    if (isset($this->session->data['order_id'])) {
      $this->cart->clear();
                    
            $order_id = $this->session->data['order_id']; /* <-- NOC NEW LINE (SAVE ORDER ID.) */
      // Add to activity log 
      $this->load->model('account/activity');

      if ($this->customer->isLogged()) {
        $activity_data = array(
          'customer_id' => $this->customer->getId(),
          'name'        => $this->customer->getFirstName() . ' ' . $this->customer->getLastName(),
          'order_id'    => $this->session->data['order_id']
        );

        $this->model_account_activity->addActivity('order_account', $activity_data);
      } else {
        $activity_data = array(
          'name'     => $this->session->data['guest']['firstname'] . ' ' . $this->session->data['guest']['lastname'],
          'order_id' => $this->session->data['order_id']
        );

        $this->model_account_activity->addActivity('order_guest', $activity_data);
      }
                       
 
      unset($this->session->data['shipping_method']);
      unset($this->session->data['shipping_methods']);
      unset($this->session->data['payment_method']);
      unset($this->session->data['payment_methods']);
      unset($this->session->data['guest']);
      unset($this->session->data['comment']);
      unset($this->session->data['order_id']);
      unset($this->session->data['coupon']);
      unset($this->session->data['reward']);
      unset($this->session->data['voucher']);
      unset($this->session->data['vouchers']);
      unset($this->session->data['totals']);

    }

    $this->document->setTitle($this->language->get('heading_title'));

    $data['breadcrumbs'] = array();

    $data['breadcrumbs'][] = array(
      'text' => $this->language->get('text_home'),
      'href' => $this->url->link('common/home')
    );

    $data['breadcrumbs'][] = array(
      'text' => $this->language->get('text_basket'),
      'href' => $this->url->link('checkout/cart')
    );

    $data['breadcrumbs'][] = array(
      'text' => $this->language->get('text_checkout'),
      'href' => $this->url->link('checkout/checkout', '', 'SSL')
    );
        
        
           
        //NOC get Order-details
        if(isset($order_id))
        {
        //LOAD MODEL
        $this->load->model('checkout/order');

        //GET ORDER DETAILS
        $order_info = $this->model_checkout_order->getOrder($order_id);

        //NEW MODEL TO COLLECT TAX
        $get_order_tax = $this->model_checkout_order->getOrderTax($order_id);

        if($get_order_tax){
                //ASSIGN TAX TO NEW VARIABLE
                $order_tax = $get_order_tax['value'];
        } else {
                //THERE WAS NO TAX COLLECTED
                $order_tax = '';
        }

        //NEW MODEL TO COLLECT SHIPPING
        $get_order_shipping = $this->model_checkout_order->getOrderShipping($order_id);

        if($get_order_shipping){
                //ASSIGN SHIPPING TO NEW VARIABLE
                $order_shipping = $get_order_shipping['value'];
        } else {
                //THERE WAS NO SHIPPING COLLECTED
                $order_shipping = 0;
        }

        //NEW MODEL TO COLLECT ALL PRODUCTS ASSOCIATED WITH ORDER
        $get_order_products = $this->model_checkout_order->getOrderProducts($order_id);

        //CREATE ARRAY TO HOLD PRODUCTS
        $order_products = array();

        foreach($get_order_products as $prod){				

                $order_products[] = array(
                        'order_id'  => $order_id,
                        'model'     => $prod['model'],
                        'name'      => $prod['name'],
                        'category'  => '',
                        'price'     => number_format($prod['price'], 2, '.', ','),
                        'quantity'  => $prod['quantity']
                );

        }

        //NEW ORDER ARRAY
        $order_tracker = array(
                'order_id'    => $order_id,
                'store_name'  => $order_info['store_name'],
                'total'       => $order_info['total'],
                'tax'         => $order_tax,
                'shipping'    => $order_shipping,
                'city'        => $order_info['payment_city'],
                'state'       => $order_info['payment_zone'],
                'country'     => $order_info['payment_country'],
                'currency'    => $order_info['currency_code'],
                'products'    => $order_products
        );

        $data['order_tracker'] = $order_tracker;

        }
        //END MODIFICATION
                
                
                
    $data['breadcrumbs'][] = array(
      'text' => $this->language->get('text_success'),
      'href' => $this->url->link('checkout/success')
    );

  /* leave other codes as it is */
  }
}
  • Save success.php.
  • Open success.tpl (File Path \catalog\view\theme\template name\template\common\success.tpl).
  • Add the below code in success.tpl.
<?php if(isset($order_tracker)){ 

        $tracking_info = '<script type="text/javascript">';
        $tracking_info .= "ga('require', 'ecommerce', 'ecommerce.js');";

//ADD TOP LEVEL TRACKING INFO
        $tracking_info .= "ga('ecommerce:addTransaction', {
        id: '" . $order_tracker['order_id'] . "', 
        affiliation: '" . $order_tracker['store_name'] . "',
        revenue: '" . $order_tracker['total'] . "', 
        shipping: '" . $order_tracker['shipping'] . "' , 
        tax: '" . $order_tracker['tax'] . "' }); ";


//ADD INFO FOR EACH PRODUCT
        foreach($order_tracker['products'] as $product){
            $tracking_info .= "ga('ecommerce:addItem', {
            id: '" . $order_tracker['order_id'] . "',
            sku: '" . $product['model'] . "',
            name: '" . $product['name'] . "', 
            category: '', 
            price: '" . $product['price'] . "', 
            quantity: '" . $product['quantity'] . "'});";
        }

    $tracking_info .= "ga('ecommerce:send');";


        $tracking_info .= '</script>';

        echo $tracking_info;

    } ?>

Code will be like this.

<?php echo $header; ?>
<!- - Leave the other codes as it is -->

<?php if(isset($order_tracker)){ 

        $tracking_info = '<script type="text/javascript">';
        $tracking_info .= "ga('require', 'ecommerce', 'ecommerce.js');";

//ADD TOP LEVEL TRACKING INFO
        $tracking_info .= "ga('ecommerce:addTransaction', {
        id: '" . $order_tracker['order_id'] . "', 
        affiliation: '" . $order_tracker['store_name'] . "',
        revenue: '" . $order_tracker['total'] . "', 
        shipping: '" . $order_tracker['shipping'] . "' , 
        tax: '" . $order_tracker['tax'] . "' }); ";


//ADD INFO FOR EACH PRODUCT
        foreach($order_tracker['products'] as $product){
            $tracking_info .= "ga('ecommerce:addItem', {
            id: '" . $order_tracker['order_id'] . "',
            sku: '" . $product['model'] . "',
            name: '" . $product['name'] . "', 
            category: '', 
            price: '" . $product['price'] . "', 
            quantity: '" . $product['quantity'] . "'});";
        }

    $tracking_info .= "ga('ecommerce:send');";


        $tracking_info .= '</script>';

        echo $tracking_info;

    } ?>
    <!--THIS IS THE END OF THE TRACKING MOD-->
    
<?php echo $footer; ?>
  • Save success.tpl.
  • Now upload order.php, success.php, and success.tpl on the server.
  • Kindly do a test purchases to ensure every thing is working fine. and to check ecommerce code is working or not you can use Tag Assistant (By Google) plugin on Google Chrome Browser.

If you are facing any issue kindly feel free to leave comment or contact me .

21 thoughts on “Add GA e-commerce tracking in opencart

  1. I am a web developer, and I have worked on various ecom site. opencart is one of them. once my client asked to implement Google analytics ecommerce on their website. Thanks to you, after a long search i got proper solution for that. I m really appreciating your writing.

    I would love to follow your other blogs.

  2. Thanks for this blog ,lastly I got a big help from you by this blog. this blog helped me resolved my big problem without any spending .

    If you don’t mind , I have some other issues. if you have any solutions or suggestions regarding that. that will help a lot to me.

    1. Thanks Roma,
      Instruction in this blog help you implement ecommerce tracting code on opencart 2, I think you are using Opencart 2.1 or higher or Source code of your website had been customized little bit.
      I am working on the code for higher version, very soon I will try to come with some proper solution.

  3. Pingback:Ecommerce Tracking in OpenCart 2.3 | Notes on Click

  4. Hi ;

    my site domain tesbihmoda.com

    I installed all codes complete. but “http://tesbihmoda.com/index.php?route=checkout/checkout” on page 5. step in “internal server error” gives the error.

    How do I fix

  5. Thanks for advice!!
    I have added also my curency
    //ADD TOP LEVEL TRACKING INFO
    $tracking_info .= “ga(‘ecommerce:addTransaction’, {
    id: ‘” . $order_tracker[‘order_id’] . “‘,
    affiliation: ‘” . $order_tracker[‘store_name’] . “‘,
    revenue: ‘” . $order_tracker[‘total’] . “‘,
    shipping: ‘” . $order_tracker[‘shipping’] . “‘ ,
    tax: ‘” . $order_tracker[‘tax’] . “‘,
    currency:: ‘” . $order_tracker[‘currency’] . “‘ }); “;

  6. Dear Dinesh!

    That’s an awesome “tutorial”. Works for me like it has to.
    One question. What’s the way of the tracking the product category?

    Why is it empty everywhere? –> ‘category’ => ”,

  7. Hello,
    I have have added the code into a development area of a legacy website I have inherited (1.5.6.4_rc). Using screen output I can see that $order_tracking is being created in success.php however neither $order_tracking or data[‘order_tracking’] seem to make it through to success.tpl – if I try to output these to the screen I just get a variable/array does not exist. Is there any obvious gochas I am missing?

  8. hello
    How are you?
    as per your instruction I added your code in my opencart file but it generating lots of errors also unable to send order

    could you please help me out.
    As this is website is live now so i am going to revert your code.

    please help
    Regards

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.