Betaout Event Tracking for Shopify Ajex Based

Hi, Welcome Back! As promised i am back with an article about implementing Betaout on your Ajex Theme Based Shopify platform.

Let’s go in and setup betaout on shopify!

What are we going to track?

Betaout Event Tracking for Shopify Default Themes

  • Products Viewed
  • Added to Cart
  • Removed from Cart
  • Continued to Checkout
  • Completed the Order
  • User Id Tracking
  • User Profile Tracking
  • Revenue Tracking
  • Event Tracking

Our Strategy:

 

We are tracking events from Shopify theme template by on click JavaScript event button. We are created some specific function for track events like, View_Product, Add_to_Cart, Remove_from_cart, Update_Cart. So if you are using any custom function for this events in your Shopify store. So you can manually call our tracking function after the success of you custom tracking function.

 

Place the JavaScript Library in your shop’s theme

 

=> Step 1:

=> Then Go in Snippets Tab:

-> Add a new snippets name with ‘betaout’.

Add the Below Code to betaout.liquid page.

<!-- Start of Betaout Code -->
<script type="text/javascript" src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
 <!-- Betaout Identification Code  -- Paste Your API KEY and Project ID in var  _bOutAKEY = "API KEY", _bOutPID = "Project ID"  Which is provide by Betaout. -->
  <script type="text/javascript">// <![CDATA[
var _bOut = _bOut || [];
var _bOutAKEY = "API KEY",        
 _bOutPID = "PROJECT ID",
         _bOutCW = true,
 _bOutST = true;
     function _bOutS(u) {var d = document, f = d.getElementsByTagName("script")[0], _sc = d.createElement("script");
                         _sc.type = "text/javascript";
                         _sc.async = true;
                         _sc.src = u;
                         f.parentNode.insertBefore(_sc, f);}
     _bOutS("//d22vyp49cxb9py.cloudfront.net/jal-v1.min.js");
     _bOut.push(["identify", {"email": "{{customer.email}}", "name": "{{customer.name}}"}]);

// ]]>
</script>
<!-- End of Betaout Identification Code -->
<script type="text/javascript">// <![CDATA[
/*  -- Predifine Function for Betaout --  */  

<!-- Function For Get Cookie -->

function getCookie(cname) {
    var name = cname + "=";
    var ca = document.cookie.split(';');
    for(var i=0; i<ca.length; i++) {
         var c = ca[i];
         while (c.charAt(0)==' ') c = c.substring(1);
         if (c.indexOf(name) == 0) return c.substring(name.length,c.length);
     }
     return "";
 }
 <!-- Function For Create Category Array of product -->

  function getCategory(pid){ 
 var catgg= new Array();
      {% for collection in collections %}
       {% for product in collection.products %}
        if ({{product.id}}== pid){
           var idvg= "{{collection.id}}";
           var titvg= "{{collection.title}}";
         var cat1=new Array();
           cat1['n']=titvg;
           cat1['p']=0;
           catgg[idvg]=cat1;
           }
   {% endfor %}
   {% endfor %}
 return  catgg;
 }
 
<!-- Function For Track Remove product From Ajax -->

 function proRemoveAjex(pid){
  var total_price=0;
   setTimeout(function () {
    $.getJSON("/cart.js", function (data) {
        $.each(data, function (key, val) {
           if (key == "total_price") {
               total_price = val;
               _bOut.push(["customerActivity", '{{customer.email}}', 'removed_from_cart', {
               "products": [{
               "productId": pid,
               "currency": "{{shop.currency}}",
                   }],
               "orderInfo": {
               "shoppingCardNo": getCookie("cart"),
               "subtotalPrice": total_price/100
             }}
            ]);
        }});
     });
    },600);
   }

<!-- Function For Track Remove product From cart page -->

    function proRemoveCart(pid){
  var total_price=0;
    {% for item in cart.items %}
    if({{item.product.id}} == pid){
      total_price= {{cart.total_price}}-{{item.line_price}};
    }
    {% endfor %}
    _bOut.push(["customerActivity", '{{customer.email}}', 'removed_from_cart', {
               "products": [{
               "productId": pid,
               "currency": "{{shop.currency}}",
                   }],
               "orderInfo": {
               "shoppingCardNo": getCookie("cart"),
               "subtotalPrice": total_price/100
             }}
            ]);
    }

 <!-- Function For Track Add and Update cart detail -->

  function updatecartval(){
     var items = [];
      var total_price = 0;
      var parray = [];
       setTimeout(function () {
             $.getJSON("/cart.js", function (data) {
                 $.each(data, function (key, val) {
                     if (key == "total_price") {
                         total_price = val;
                     }
                     if (key == "items") {
                         for (var item in val) {
                         var test = {"productId": val[item]['product_id'],
                                 "sku": val[item]['sku'],
                                 "price": val[item]['price']/100,
                                 "specialPrice": '',
                                 "productTitle": val[item]['product_title'],
                                 "stockAvailability": "1",
                                 "pageURL": val[item]['url'],
                                 "pictureURL": val[item]['image'],
                                 "currency": "{{shop.currency}}",
                                 "category": getCategory(val[item]['product_id']),
                                 "qty": val[item]['quantity'],
                                 "brandName": val[item]['vendor']};
                                    parray.push(test);
                         }
                     }
                 });
                _bOut.push(["customerActivity", "{{customer.email}}", "update_cart", {
                              "products": parray,
                              "or": {
                            "shoppingCardNo": getCookie("cart"),
                             "subtotalPrice": total_price/100 } 
                             }]);
             });
         }, 100);
  }
 
<!--JavaScript code For Track Add to cart, Update cart and Remove product from cart -->

 $(document).ready(function () {

   $('#betaout_id').val(getCookie("_ampUITN"));

   $(".remove").click(function(){

    proRemoveCart(parseInt($(this).find(".boutpid").attr("data-id")));
   });
    $(".remove_item").click(function(){

    proRemoveCart(parseInt($(this).find(".boutpid").attr("data-id")));

   });

    $('body').on('click', '.ajaxifyCart--remove', function () {

    proRemoveAjex(parseInt($(this).find(".boutpid").attr("data-id")));
   });

   $("#addToCart").click(function(){

        updatecartval ();
   });

   $(".add_to_cart").click(function(){

        updatecartval ();
   });
   $('body').on('click', '.add_to_cart', function () { 

       updatecartval ();
       });

   $('body').on('click', '.sc-shopify-qs-add-to-cart-list', function () {

        updatecartval ();
       });

   $('body').on('click', '.btn-secondary update-cart', function () {

        updatecartval ();
       });

   $(".update-cart").click(function(){
        updatecartval (); 
  });
 }); 

<!-- JavaScript code For Track Viewed products detail -->

 {% if template contains 'product' %}
 var catgg= new Array();
   var idvg= "{{collection.id}}";
   var titvg= "{{collection.title}}";
     var cat1=new Array();
   cat1['n']=titvg; 
  cat1['p']=0;
   catgg['"'+idvg+'"']=cat1;
 _bOut.push(["customerActivity", '{{customer.email}}', 'viewed', { 
                    "products": [{ "productId": "{{product.id}}",
 "sku": "{{product.title}}",
 "productTitle": "{{product.title}}",
 "price": "{{product.price | money_without_currency }}",
 "specialPrice": "",
 "status": "{{product.available}}",
 "stockAvailability": "{{product.available}}",
 "brandName": "{{product.vendor}}",
 "pageURL": "{{product.url}}",
 "pictureURL": "https:".concat("{{product.featured_image.src | product_img_url: 'grande'}}"),
 "currency": "{{shop.currency}}",
 "category": getCategory({{product.id}}),
 "qty": "{{product.variants.first.inventory_quantity}}"
   }]}
 ]); 
{% endif %}

// ]]>
</script>

<!-- End of Betaout Code -->

Note – Replace
(–YOUR API KEY–) with your own Betaout API Key
AND
(–YOUR PROJECT ID –) with your own Betaout  Project Id

 

=> Step 2:    Go on Templates Tab:

-> Open theme.liquid or the layout that is used in all the pages of your shop.

Add the Below Code to Theme.Liquid in <head> Tag:

 

{% include 'betaout' %}

 

-> Click on cart.liquid page:

Screenshot from 2015-07-28 16:14:37

 

Add 1 line within FOR LOOP and after   <a title=”Remove Item” href=”/cart/change?line=1&quantity=0″>Remove</a> or <a href=”/cart/change?line={{ forloop.index }}&amp;quantity=0″ …> Tag as show on figure::

 

 <div data-id="{{item.product.id}}" class="boutpid"></div> 

-> Add 1 more line as show on figure: Screenshot from 2015-07-28 15:03:18 As shown below, add a hidden <input> field to the cart form (<form action="/cart">). Before  <button type=”submit” name=”checkout”> Tag.

<input id="betaout_id" type="hidden" name="attributes[b]" />

 

=> Step 3:

Settings->Checkout->Additional Content & Scripts*

Head to https://myshopify.com/admin/settings/checkout to modify your checkout settings.

In the section “Order processing”, under “Additional content & scripts”, paste the sample from below.

 

<script type="text/javascript">// <![CDATA[

function setCookie(cname, cvalue) {
 var d = new Date();
 d.setTime(d.getTime() + (1*60*60));
 var expires = "expires="+d.toUTCString();
 document.cookie = cname + "=" + cvalue + "; " + expires+"; path=/";
 }

 document.cookie="_ampEm="document.cookie="_ampUITN={{attributes.b}};path=/";
var _bOut = _bOut || [];
 var _bOutAKEY = "BETAOUT API KEY",
 _bOutPID = "BETAOUT PROJECT ID",
  _bOutCW = true,
 _bOutST = true;

 function _bOutS(u) {
var d = document,
 f = d.getElementsByTagName("script")[0],
 _sc = d.createElement("script");
 _sc.type = "text/javascript";
 _sc.async = true;
 _sc.src = u;
 f.parentNode.insertBefore(_sc, f);
}

 _bOutS("//d22vyp49cxb9py.cloudfront.net/jal-v1.min.js");
 setTimeout(function(){ _bOut.push(["identify", {"email": "{{order.customer.email}}", "name": "{{order.customer.name}}"}]);
 var parray = new Array();

 {% for line_item in order.line_items %}
 parray.push({"productId": "{{line_item.product_id }}",
 "sku": "{{ line_item.sku  }}",
 "productTitle": "{{line_item.title}}",
 "price": "{{ product.price | money_without_currency }}".replace(",",""),
 "specialPrice": "{{ line_item.price | money_without_currency }}".replace(",",""),
 "status": "{{line_item.product.available}}",
 "stockAvailability": "{{line_item.product.variant.inventory_quantity}}",
 "brandName": "{{line_item.vendor}}",
 "pageURL": "{{line_item.product.url}}",
 "pictureURL": "{{ line_item.product.image.src | product_img_url: 'medium' }}",
 "currency": "{{shop.currency}}",
 "category": "",
 });
 {% endfor %}
 var oarray = new Array({"orderId": "{{order.order_number}}", 
"shoppingCartNo": "{{order.cart.id}}",
 "subtotalPrice": "{{order.subtotal_price | money_without_currency }}".replace(",",""),
 "totalShipping": "{{order.shipping_price | money_without_currency}}".replace(",",""),
 "totalTaxes": "{{order.tax_price | money_without_currency}}".replace(",",""),
 "totalDiscount": "{{checkout.discounts_amount | money_without_currency}}".replace(",",""),
 "totalPrice": "{{order.total_price | money_without_currency}}".replace(",",""),
 "promocode": "{{gift_card.code}}",
 "couponcode": "{{gift_card.code}}",
 "currency": "{{shop.currency}}",
 "financialStatus": "{{order.financial_status}}" });
 _bOut.push(["customerActivity", '{{order.customer.email}}', 'purchased', { "products": parray, "or": oarray[0] }]);
 },200);
 document.cookie = "_ampEm=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/";

// ]]>
</script>

 

Note-

– At the place of <BETAOUT API KEY>  enter your Betaout Api Key

– At the place of <BETAOUT PROJECT ID>  enter your Betaout Project Id

Example-

var _bOutAKEY = "t4m2sab26o70z869n8l3846ej8708sjh5adhslr9kj",
_bOutPID = "20505"

 

 

Important things to note:

1.) Betaout automatically tracks advertising campaigns like Adwords, Bing Ads, Fb, etc so no need to tag them manually.

2.) In shopify when someone goes from Cart to Checkout the tracking breaks since shopify won’t allow codes on their checkout pages. To solve this we would have implemented cross domain tracking but Betaout doesn’t need it since it retains the cookies.

*The javacript code may change in future so you have to keep an eye.