Categories: Google Analytics and Ecommerce Tracking

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.

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 .

Notes On Click

Share
Published by
Notes On Click
Tags: Adword conversion trackingadword remarketingEcommerce trackingopencart

Recent Posts

  • Adword Conversion Tracking
  • Google Adwords Remarketing

Conversion and Remaketing code in BigCommerce

In this blog, you will see how to add Adwords Conversion Tracking and Remarkeing Code in BigCommerce.BigCommerce is one of…

8 years ago
  • Google Analytics and Ecommerce Tracking

Ecommerce Tracking in OpenCart 2.3

Around 6 months back, I had published an article on “How to add GA e-commerce tracking in Opencart“. I am really thankful…

8 years ago
  • Google Analytics and Ecommerce Tracking

Google Analytics Definition and Common Terms

 If you have gone through our previous blog about Google Analytics, you might have sound understanding about Google Analytics and how it…

8 years ago
  • Google Analytics and Ecommerce Tracking

What is Google Analytics and it’s Features?

Do you want to know more about your visitors and how your content is performing?​ Whether you run a website…

8 years ago
  • Google Analytics and Ecommerce Tracking

How to Add Google Analytics in BigCommerce

In this blog, you will see how to add Google Analytics and E-commerce Tracking Code  in BigCommerce. BigCommerce is one of the…

8 years ago
  • Google Analytics and Ecommerce Tracking

Google Analytics and E-commerce Tracking in Miva Merchant

If you have gone through some of previous blog, you might have seen how to install google analytics, e-commerce tracking…

8 years ago