Follow

Custom Installation Instructions

This document contains all of the information you will need to install WhatCount's Behavioral Track & Trigger module onto your e-Commerce website.

WhatCounts uses a JavaScript library to capture events in the e-Commerce system. To ensure a successful integration, these instructions should be reviewed and executed by a developer with at least 1 to 3 years of JavaScript development experience. 

The two most important things for your developer to know in order to install these scripts successfully are:

  1. How your product and order information is accessible via API calls, template variables, or html scraping techniques.
  2. Where each script should be placed to have access to the appropriate information on the site.

If you do not feel comfortable with the instructions laid out below, please contact your Integration Project Manager about the installation services that WhatCounts offers.

Estimated Time For Installation 

We estimate that installing and testing these scripts will take between 1 to 5 hours of development time, depending on the complexity of the ecommerce system, the familiarity of the developer with the system, and whether Cart Recovery scripts are included as part of the installation.

Information Needed Before Installation 

You will need 2 Site Keys from WhatCounts: 1 for test and 1 for production. To locate your site keys:

  1. While logged in, click the gear icon in the top-right corner and select "Behavioral Track & Trigger Validator".

Settings.png

  2. Your Site Keys are located in the "Store Configuration Information" section:

Keys.png

Script Installation Instructions (v2) 

Each of the following scripts should be installed into a template for your e-Commerce site. For each script, fields in the format %%field%% should be replaced with a variable from your ecommerce system to provide the information described in the fields table. Optional fields should be replaced with an empty string (i.e. "") if they are not provided. Note that the products script (further below) also requires customization to properly capture page events and quantity information when a user adds an item to their shopping cart.

Main Script 

Page: This script should appear on every page on your site inside the <head> tag

Main ScriptCopy to Clipboard<script type="text/javascript">
!function(){ var analytics=window.analytics=window.analytics||[]; if(!analytics.initialize) { if(analytics.invoked) { window.console&&console.error&&console.error("Segment snippet included twice."); } else { analytics.invoked=!0; analytics.methods=["trackSubmit","debug", "trackClick","trackLink","trackForm","pageview","identify","group","track","ready","alias","page","once","off","on"]; analytics.factory=function(t){ return function() { var e=Array.prototype.slice.call(arguments); e.unshift(t); analytics.push(e); return analytics; } }; for(var t=0;t<analytics.methods.length;t++){ var e=analytics.methods[t]; analytics[e]=analytics.factory(e) } analytics.load=function(t){ analytics.apiKey = t; var e=document.createElement("script"); e.type="text/javascript"; e.async=!0; e.src="https://static.whatcounts.com/analytics.min.js"; var n=document.getElementsByTagName("script")[0];n.parentNode.insertBefore(e,n) }; analytics.SNIPPET_VERSION="4.0.0";
  window.analytics.load('%%wcapikey%%');
  window.analytics.page(undefined, undefined, undefined, {wcapiVersion: '2.0'});
}}}();
</script>

 

Fields Optional? Description
wcapikey N The API key provided by WhatCounts. This can be hardcoded in the template, but must be different on your test environment and production environment to avoid contaminating production data

Identify via Account Script 

Page: This script should appear on every page on your site inside the <head> tag, beneath the previous script, or on your cart and account pages

You should install this script so that it executes on any page where you can positively identify the user. For some sites that means it can be placed into the head after the main script, for other sites it will need to be placed on certain pages or templates where the customer information is available.  For all sites it is important that this triggers when the user makes a purchase, even if they do not log in.  If the user is making a purchase through a guest checkout process, the identify event should capture an email and any other available information, and leave customerid as an empty string.

Identify ScriptCopy to Clipboard<script type="text/javascript">
(function() {

  // identify the customer if they have an account
  // If this script is installed on a page where you will always have
  //customer information, the below if statement can be removed

  if(%%loggedin%%) {

    window.analytics.identify("%%customerid%%", {
      name: "%%fullname%%",
      firstName: "%%firstname%%",
      lastName: "%%lastname%%",
      email: "%%email%%",
      storeid: "%%storeid%%",
      shippingAddress: {  // uses the default address
        street: "%%shippingstreet%%",
        city: "%%shippingcity%%",
        state: "%%shippingstate%%",
        postalCode: "%%shippingpostal%%",
        country: "%%shippingcountry%%",
      },
      billingAddress: {  // uses the default address
        street: "%%billingstreet%%",
        city: "%%billingcity%%",
        state: "%%billingstate%%",
        postalCode: "%%billingpostal%%",
        country: "%%billingcountry%%",
      },
    }, {wcapiVersion: '2.0'});

  }
})();
</script> 
Fields Optional? Description
loggedin N A check to see if there is a currently logged in customer we can identify. If so, we should show customer information in the identify event. If not, we can remove that event on the current page. This should return `true` or `false` to the page
customerid N The unique id for the currently logged in customer.

Note: These values MUST match the Customer ID values being passed to us in back-end order data. If no customer id is available for a given customer, leave this value null; do not populate the customer's email address.
fullname N The full name of the logged in customer if available, empty string otherwise
firstname N The first name for the logged in customer if available, empty string otherwise
lastname N The last name for the logged in customer if available, empty string otherwise
email N The email address for the logged in customer.  This is essential to include correctly for every identify event.
storeid Y The store id for this store.  Only needed when the script is used across multiple stores.
billingstreet Y The billing street of the logged in customer if available, empty string otherwise
billingcity Y The billing city of the logged in customer if available, empty string otherwise
billingstate Y The billing state of the logged in customer if available, empty string otherwise
billingpostal Y The billing postal/zip code of the logged in customer if available, empty string otherwise
billingcountry Y The billing country of the logged in customer if available, empty string otherwise
shippingstreet Y The shipping street of the logged in customer if available, empty string otherwise
shippingcity Y The shipping city of the logged in customer if available, empty string otherwise
shippingstate Y The shipping state of the logged in customer if available, empty string otherwise
shippingpostal Y The shipping postal/zip code of the logged in customer if available, empty string otherwise
shippingcountry Y The shipping country of the logged in customer if available, empty string otherwise

Identify via Email Script 

Page: Many sites provide forms for a user to enter their email to sign up for a newsletter or other email communication. This script should be included anywhere that occurs.

This script provides a second way of pulling in user information. Since it only pulls in an email, it is less rich than pulling in full login data. But for many sites it provides more opportunity for capturing data, including information from customers who may not yet have made a purchase.

Identify Email ScriptCopy to Clipboard<script type="text/javascript">
    // IMPORTANT: The following code will need to be customized for your ecommerce platform
    // The end result should be an identify event triggering when the user adds
    // their email from an email submission form.
    // entered.

    (function() {

        // this variable should be set to point at the form submission button
        // the exact code here may need to be customized for your site
    	var emailFormButton = document.getElementById('emailFormButton');

        // this variable should be set to point at the form submission input
        // the exact code here may need to be customized for your site
    	var emailInput = document.getElementById('emailInput');

    	if (emailFormButton) {
    		emailFormButton.addEventListener('click', function() {
    			window.analytics.identify(null, {
    	   			email: emailInput.value,
                    source: 'email-input',
    	  		}, {wcapiVersion: '2.0'});
    		});
    	}
    })();
    </script> 

Products Script 

Page: This script should be placed at the bottom of all product pages, as well as inside any additional dynamic content areas where a user can view a specific product and add it to their cart.

Products ScriptCopy to Clipboard<script type="text/javascript">
(function(){
  analytics.track('Viewed Product', {
    id: "%%productid%%",
    vsku: "%%vsku%%",
    psku: "%%psku%%",
    name: "%%productname%%",
    price: "%%price%%",
    priceMin: "%%minprice%%",
    priceMax: "%%maxprice%%",
    priceVaries: "%%pricevaries%%",
    available: "%%available%%",
    categories: [%%categories%%],
    storeid: "%%storeid%%",
  }, {wcapiVersion: '2.0'});

  // IMPORTANT: The following code will need to be customized for your ecommerce platform
  // The end result should be an "Added Product" event triggering when the user adds
  // a product to their cart
  //Quantity will also need to be selected dynamically based on an input on the page
  var addToCartButton = document.getElementById('addtocart');
  if(addToCartButton) {
    addToCartButton.addEventListener('click', function() {
      analytics.track('Added Product', {
       id: "%%productid%%",
       vsku: "%%vsku%%",
       psku: "%%psku%%",
       name: "%%productname%%",
       price: "%%price%%",
       available: "%%available%%",
       cartLink: "%%cartlink%%",
       quantity: document.getElementById('quantityselect').value,
       storeid: "%%storeid%%",
      }, {wcapiVersion: '2.0'});
    });
  }
  //This is the end of the area needing custom code

})();
</script> 
Fields Optional? Description
productid N The unique id for this product
vsku N The primary/variant sku for this product. If you only use a single sku for products, fill it in this field.
psku N The parent sku for this product, or an empty string if there is no parent sku. If you only use a single sku, leave this field empty or remove it
productname N The name of the product
price N The price of the product
minprice Y If the price of a product is variable, the minimum price
maxprice Y If the price of a product is variable, the maximum price
pricevaries Y This variable should be 'true' if the price varies, 'false' otherwise. It can be an empty string or not included if the store does not support variable prices per product
categories Y This should be a list of the categories that contain this product, in array form.  If your site has nested categories, those can be represented in the format ['parent category > child category > grandchild category', 'category2', 'parent category > category 3']
cartlink N This should be a url pointing to the shopping cart for the user. If your site has a single cart link, this can be hardcoded to that, but if you have per-user cart urls, you can fill this in dynamically.
available Y This variable should be 'true' if the product is available, 'false' if it is out of stock.
storeid Y The id of the store that the product belongs to.  Only applicable when the script is implemented across multiple stores

Categories Script (Optional) 

Page: This script should be placed at the bottom of all category pages

Categories ScriptCopy to Clipboard<script type="text/javascript">
(function(){
  analytics.track('Viewed Product Category', {
    category: "%%category%%",
  }, {wcapiVersion: '2.0'});

})();
</script> 
Fields Optional? Description
category N The category represented by this page. This can either be a single string like "Pants" which would be loaded as shown above, or in the case of hierarchical categories, an array of strings, shown like { category: ["Clothing", "Mens", "Pants"] }

Search Script (Optional) 

Page: This script should be included on your search results page.

Search ScriptCopy to Clipboard<script type="text/javascript"> 
(function(){ analytics.track('Searched Product', { query: "%%query%%", }, {wcapiVersion: '2.0'}); })(); </script> 
Fields Optional? Description
query N The search terms for the current search

Cart Script 

Page: This script should be included on your cart page, or within your dynamically loaded content if your shopping cart is loaded using AJAX.

**Important:** This script assumes that your shopping cart page reloads each time an item is removed from the cart or the items quantity is changed. If that is not the case, you will have to write some custom JavaScript to execute the `Viewed Cart` event after each change.

Cart ScriptCopy to Clipboard <script type="text/javascript"> 
(function() { 
    analytics.track('Viewed Cart', { 
        cartLink: '%%cartlink%%',
        products: [{ 
            id: '%%productid%%', 
            vsku: '%%productvsku%%', 
            psku: '%%productpsku%%', 
            name: '%%productname%%', 
            price: '%%productprice%%', 
            quantity: '%%productquantity%%', },
            storeid: '%%storeid%%', 
        /* One entry for each product purchased */
        ], }, {wcapiVersion: '2.0'}); })(); 
</script> 
Fields Optional? Description
productid N The unique id for the product. Multiple of these will be loaded onto the page, one for each element in the cart
productvsku N The primary/variant sku for the product. Multiple of these will be loaded onto the page, one for each element in the cart. If you only use a single sku for products, use this field for it.
productpsku N The parent sku for each product, or an empty string if there is no parent sku. If you only use a single sku for products, leave this field blank or don't include it.
productname N The name of each product
productprice N The price of each product
productquantity N The quantity of each product purchased
cartlink N This should be a url pointing to the shopping cart for the user. If your site has a single cart link, this can be hardcoded to that, but if you have per-user cart urls, you can fill this in dynamically.
storeid Y The id of the store that the product belongs to.  Only applicable when the script is implemented across multiple stores

Order Page Script 

Page: This script should be included on your completed order page.

Order Page ScriptCopy to Clipboard<script type="text/javascript"> 
//this snippet returns a single array of json objects 
(function(){ 
    analytics.track('Completed Order', { 
        products: [{ 
            id: '%%productid%%', 
            vsku: '%%productvsku%%', 
            psku: '%%productpsku%%', 
            name: '%%productname%%', 
            price: '%%productprice%%', 
            quantity: '%%productquantity%%', 
            storeid: '%%storeid%%',
        }, 
            /* One entry for each product purchased */
        ], }, {wcapiVersion: '2.0'}); })(); 
</script> 
Fields Optional? Description
productid N The unique id for each product ordered.
productvsku N The primary/variant sku for the product. Multiple of these will be loaded onto the page, one for each element in the cart. If you only use a single sku for products, use this field for it.
productpsku N The parent sku for each product, or an empty string if there is no parent sku. If you only use a single sku for products, leave this field blank or don't include it.
productname N The name of each product
productprice N The price of each product
productquantity N The quantity of each product purchased
storeid Y The id of the store that the product belongs to.  Only applicable when the script is implemented across multiple stores

Testing 

After completing the installation of every script on your test environment, please perform the following actions on your test environment in order to generate test events. If the installation is working currently, these test events should immediately be visible in our validator. We recommend keeping the validator open in a separate tab or window, and refreshing each team you perform each action, to confirm that 1) the appropriate resulting event appears in the validator, and 2) the properties of the event appear correctly.

For more specifics on what to test, please see each action below.

All installations should test the following:

  • Go to your home page.
    • Check: Does a "Page Event" fire in the validator?
  • Go to a product page
    • Check: Does a "Viewed Product Event" fire in the validator?
    • Check: Do the product properties appear correctly in the event detail in the validator?
      • Note: the most important thing to check here is that the "id" product property populates, and maps to the Product ID field being sent in your API/Plugin/Custom Data Feed.
  • If you have alternative ways of viewing products that you wish to support, view those as well.
    • Note: For example, some sites have a "Quick View" option that is different that a standard product page view. Check to ensure the "Viewed Product Event" fires on this view options, just as you did for the standard product page view above.
  • Add a product to your shopping cart
    • Check: Does an "Added Product Event" fire in the validator?
    • Check: Do the product properties appear correctly in the event detail in the validator?
      • Note: the most important thing to check here is that the "id" product property populates, and maps to the Product ID field being sent in your API/Plugin/Custom Data Feed.
    • Check: Does the "cartLink" property populate correctly?
  • Log in to an account
    • Check: Does an "Identify Event" fire in the validator?
    • Check: Do all customer traits appear correctly in the event detail in the validator?
      • Note: the most important thing to check here is that the "email" trait populates correctly
    • Repeat these testing steps for a login that occurs during the checkout process, if applicable.
    • Navigate to a few different pages while logged in. Does the "Identify Event" fire in the validator upon each new page load?
  • Enter your email address in any popups, lightboxes, or input forms on the site (such as an email signup form).
    • Check: Does an "Identify Event" fire in the validator?
    • Check: Does the "email" trait appear correctly in the event detail in the validator?
  • Go through the guest checkout process
    • Check: Once you submit your email address in the guest checkout workflow, does an "Identify Event" fire in the validator?
    • Check: Does the "email" trait appear correctly in the event detail in the validator?

If you will be running Cart Recovery campaigns, you should also test the following actions:

  • After adding a product, view your shopping cart page
    • Check: Does a "Viewed Cart Event" fire in the validator?
    • Check: Do the product properties for all products in the cart appear correctly in the event detail in the validator?
    • Check: Does the "cartLink" property populate correctly?
  • If you can edit or remove items from your cart directly from the shopping cart page, do so.
    • Check: does a new "Viewed Cart Event" fire in the validator?
    • Check: Do each of the above properties refresh correctly to reflect the updated cart contents?
  • Complete a test order
    • Check: Does a "Completed Order Event" fire in the validator?
    • Check: Do the product properties for all products in the order appear correctly in the event detail in the validator?

If you have installed the optional scripts to track category page views and site searches, you should also test the following actions:

  • Go to a product category page
    • Note: this event type is optional. Only test this if you have installed the "Categories Script".
    • Check: Does a "Viewed Product Category Event" fire in the validator?
    • Check: Does the "category" property appear correctly in the event detail in the validator?
  • Search for a product using your site search function
    • Note: this event type is optional. Only test this if you have installed the "Search Script".
    • Check: Does a "Searched Product Event" fire in the validator?
    • Check: Does the "query" property appear correctly in the event detail in the validator?

Upgrading from event definition v1 to v2 

In July 2018 we updated our instructions for installing script code in order to improve accuracy in our cart recovery calculations.  Upgrading to V2 is fairly straightforward.  You will need to

  1. Go through the events in the documentation above and make sure that all of the events that are not listed as optional are implemented in your code. 
  2. If you had previously implemented a "Viewed Cart" event, make sure to add the cartLink property described in the documentation above
  3. Update all wcapiVersion: 1.0 instances in your code to read wcapiVersion: 2.0
  4. After allowing some events to come through, use the validator tool in the WhatCounts app to verify that no errors are present

Troubleshooting: Selectors and events in JavaScript 

This section is for users who are not comfortable selecting elements on the page in JavaScript or triggering events based off of user action. Since the products snippet above requires customization to correctly work on a given site, this is a brief explanation of how to create custom selectors and event handlers for a site.

Selectors in JavaScript 

Several of the scripts in this document require reacting to user events happening on the page. For instance, in the products page script we have an example script that looks like this:

Copy to Clipboardvar addToCartButton = document.getElementById('addtocart'); 
if(addToCartButton) { 
    addToCartButton.addEventListener('click', function() { 
        analytics.track('Added Product', { 
            //properties here ... 
        }, { wcapiVersion: '1.0'}); 
    }); 
} 

The problem with this snippet is that it is not very generalized. It assumes that you have an element on your page that has a single control for adding an element to a cart with an id "addtocart". In some cases that assumption will be accurate, but in most cases your setup will be different. You may have multiple add to cart buttons, or your add to cart button might have a different id or no id. In this case you'll have to generalize the above example to fit your installation.

The 2 easiest ways to select an element in JavaScript are using ids and classes. Ids should be used when there is only a single element on a page that you wish to select, classes can be used when you want to select multiple items. Selecting an element with an id in JavaScript is simple.

To select

Copy to Clipboard<button id="foo">Do something</button> 

You can call

Copy to Clipboardvar button = document.getElementById('foo'); 

inside of a script.

Selecting a set of elements with a class isn't too much more complicated.

To select each button with the bar class

Copy to Clipboard<button class="bar">Button 1</button>
<button class="bar">Button 2</button> 

you can call

Copy to Clipboardvar buttons = document.querySelectorAll('.bar '); 

Note that the argument, '.bar', is the css syntax for selecting elements with the class bar, rather than the plain name used with document.getElementById. If you're familiar with CSS, you can use querySelectorAll to use more advanced selectors using the same syntax as CSS.

Of course in some cases, your site might not currently have classes or ids on all of the elements that you want to select. In that case we suggest adding them. If you're adding classes, we recommend ending the class name with something like "-js" so that you know that it is for selecting with JavaScript and not for use in css styling. So you could change a button like this

Copy to Clipboard<button>Add To Cart</button> 

to

Copy to Clipboard<button class="add-to-cart-js">Add To Cart</button> 

at which point it would be selectable.

Event Listeners in JavaScript 

Once you have a reference to an element or a set of elements, we can listen to events on them. In JavaScript this is done with the "addEventListener" function. The 2 main events we may want to listen to in our scripts are click events (for when a customer clicks on a button to perform an action) and change events (for when a customer updates an input with a new value).

Listening to click events on a set of elements with the class "add-to-cart-js" looks like this

Copy to Clipboardvar buttons = document.querySelectorAll('.add-to-cart-js '); 
for (var i = 0; i < buttons.length; i++) { 
    buttons[i].addEventListener('click', function() { 
        //do stuff here when the user clicks on the button 
    }); 
} 

Listening to a change event on a single input with id "quantity-js" looks like this

Copy to Clipboardvar quantityInput = document.getElementById('quantity-js'); 
quantityInput.addEventListener('change', function() { 
    var inputValue = this.value; 
}); 

Compatibility Note 

"addEventListener" is not supported in versions of internet explorer prior to version 9. If you need to support Internet Explorer versions 8 or earlier, you will need to use a more complicated approach, or use a dom library like jQuery (see below). Here's a version of the above snippet that supports Internet Explorer 8.

Copy to Clipboardvar quantityInput = document.getElementById('quantity-js'); 
if (quantityInput.addEventListener) { 
    quantityInput.addEventListener('change', function() { 
        var inputValue = this.value; }); 
} else if (quantityInput.attachEvent) { 
    quantityInput.attachEvent('onchange', function(el) { 
        return function() { var inputValue = el.value; }; 
    }(quantityInput)); 
} 

jQuery 

WhatCount's browse scripts have no external dependencies beyond the analytics script that the main script loads in. But if you already have jQuery or another JavaScript DOM library on your site, it can make the process of selecting events much easier, especially if you have to support old versions of Internet Explorer.

Here's the 2 examples above written in jQuery:

Copy to Clipboard//trigger function when the user clicks on any element with the class add-to-cart-js 
$('.add-to-cart-js').on('click', function() { 
    //do stuff here when the user clicks on a button 
}); 
Copy to Clipboard //get value of the input of the element with id quantity-js every time it changes 
$('#quantity-js').on('change', function() { 
    var inputValue = this.value; 
}); 

Click Tracking Only Script Installation Instructions Edit section

When using WhatCounts Behavioral Tracking only for tracking click attribution for emails, a simplifed installation is possible.  Only a modified version of the main script is needed.  Note that it will still be necessary to replace %%wcapikey%% in the script below with the api key for your store.  

Main Script 

Page: This script should appear on every page on your site inside the <head> tag

Main ScriptCopy to Clipboard<script type="text/javascript">
!function(){ var analytics=window.analytics=window.analytics||[]; if(!analytics.initialize) { if(analytics.invoked) { window.console&&console.error&&console.error("Segment snippet included twice."); } else { analytics.invoked=!0; analytics.methods=["trackSubmit","debug", "trackClick","trackLink","trackForm","pageview","identify","group","track","ready","alias","page","once","off","on"]; analytics.factory=function(t){ return function() { var e=Array.prototype.slice.call(arguments); e.unshift(t); analytics.push(e); return analytics; } }; for(var t=0;t<analytics.methods.length;t++){ var e=analytics.methods[t]; analytics[e]=analytics.factory(e) } analytics.load=function(t){ analytics.apiKey = t; var e=document.createElement("script"); e.type="text/javascript"; e.async=!0; e.src="https://static.whatcounts.com/analytics.min.js"; var n=document.getElementsByTagName("script")[0];n.parentNode.insertBefore(e,n) }; analytics.SNIPPET_VERSION="4.0.0";
  window.analytics.load('%%wcapikey%%');
}}}();
</script>
Fields Optional? Description
wcapikey N The API key provided by WhatCounts. This can be hardcoded in the template, but must be different on your test environment and production environment to avoid contaminating production data

 

Whatcounts 2019 Migration Instructions 

If you originally installed your behavioral tracking script prior to April 2019, you will need to update your main script to point to a new version of the script.  This can be done either by 

  1. Following the instructions from the Main Script area at the top of this page, and replacing your existing main script with the updated version.  Important: Make sure to add back in your apiKey.
  2. Search your existing Main Script for a reference to cdn.windsorcircle.com/analytics.min.js and replace it with static.whatcounts.com/analytics.min.js
Privacy Law Compliance 
Each Customer is responsible for obtaining the requisite consent in accordance with applicable law from its customers and third parties for us to collect and use the Target Data as necessary for the provisioning of the WhatCounts Services. Customer is solely responsible for the quality, accuracy, and legality of the Target Data provided to WhatCounts by or on behalf of the Customer; and the means by which Customer acquired such Target Data.  Unless otherwise specifically disclosed to and agreed to by WhatCounts, the Target Data provided by Customer shall not include any sensitive or special personal data that imposes specific data security or data protection obligations on WhatCounts that are different or in addition to those specified in the written agreement(s) between the parties and the WhatCounts Privacy Policy.

By providing this data you acknowledge that the data you are providing is in compliance with the written agreement(s) between the parties and our privacy policy.

Was this article helpful?
0 out of 0 found this helpful
Have more questions? Submit a request

Comments

Powered by Zendesk