Last updated: Dec 27 2017

Area: Episerver Profile Store Applies to versions: 1.3.0 and higher

Tracking API

This topic provides an overview of the tracking API for Episerver Profile Store, which provides the endpoint for tracking of statistics. Data is sent to the tracker as track events. 

Authentication

Use the Authorization header for authentication with a value in the following format: epi-single key; it contains the subscription key that is passed to the tracker with each request.

Endpoints

Post is the default and preferable method to track, and allows sending additional payload data.

You can track and send single or batch messages to and from the Tracking API. Batch tracking works the same way as single tracking, and takes a list of track events. You can have a maximum of 100 track events in each batch, with a limit of 256KB for each track event.

Endpoint for tracking API single track event is POST https://example.com/api/v1.0/Track.

{
  "user": {
    "name": "string",
    "email": "string",
    "information": {}
  },
  "payload": {},
  "deviceId": "string",
  "eventType": "string",
  "value": "string",
  "pageUri": "string",
  "pageTitle": "string",
  "eventTime": "2017-09-19T08:24:19.996Z",
"scope": "scope name" }

Endpoint for tracking many events in batches is POST https://example.com/api/v1.0/TrackBulk.

[
  {
    "user": {
      "name": "string",
      "email": "string",
      "information": {}
    },
    "payload": {},
    "deviceId": "string",
    "eventType": "string",
    "value": "string",
    "pageUri": "string",
    "pageTitle": "string",
    "eventTime": "2017-09-18T14:23:28.340Z"
  },
  {
    "user": {
      "name": "string",
      "email": "string",
      "information": {}
    },
    "payload": {},
    "deviceId": "string",
    "eventType": "string",
    "value": "string",
    "pageUri": "string",
    "pageTitle": "string",
    "eventTime": "2017-09-19T08:24:19.996Z"
  }
]

Required properties

  • deviceId [string]. The device identifier is generated by the client (website) and must be provided in each tracking request to Tracking API. Use _madid as the name of the cookie when storing a device ID in a visitor browser.
  • eventType [string]. The type of tracking event.
  • value [string]. The tracking data value.

Optional properties

  • pageTitle [string]. The page title.
  • user [object]. A JSON object with user information that can have the following optional properties:
    • name [string]. The user's name.
    • email [string]. The user's email.
    • information [object]. Information related to the user as a list of strings.
  • payload [object]. A JSON object with any kind of data.
  • pageUri [string]. The page URI where the event occurred.
  • eventTime [string]. The date and time, in UTC, when the event occurred.
  • scope (string). The scope this tracking event belongs to. DefaultScope is used when not set. (Scope is a concept for separating tracking events, and profiles into different scopes.)

Tracking Ip-address

Use the Epi-User-IP-Address header to pass the visitor IP address to the Tracking API, for example when tracking statistics in website .NET code.

How to use EPiServer.Tracking.Core API and ProfileStore packages

Prerequisites

  • Nuget packages
    • EPiServer.Tracking.Core
    • EPiServer.Tracking.Cms
    • EPiServer.Profiles.Common
    • EPiServer.Profiles.Client
  • Prepare the API URLs and Subscription Keys
    • TrackingApiBaseUrl
    • TrackingApiSubscriptionKey
    • Make sure that episerver:profiles.ProfileStoreTrackingEnabled = true and   episerver:tracking.IgnoreDNT = true. See Do Not Track (Wikipedia) and Turn "Do not track" on or off (Google Chrome) for more information about Do not Track (DNT).

Install EPiServer.Tracking.Core

Install the EPiServer.Tracking.Core nuget package from episerver nuget source to your site.

Prepare tracking client APIs

This example uses an Alloy sample site and its Start Page

  1. Create custom tracking data.
    class MyCustomTrackingData
    {
        public string Value1 { get; set; }
        public string Value2 { get; set; }
        public string Value3 { get; set; }
        public UserData User { get; set; }
    }]]
  2. Declare  ITrackingService and inject it into  StartPageController using constructor dependency injection pattern.
    public class StartPageController : PageControllerBase
    {
    	private readonly ITrackingService _trackingService;
        public StartPageController(ITrackingService trackingService)
        {
    		_trackingService = trackingService;
        }
    	...
    }]]
  3. Use Track method of  ITrackingService for tracking object.
    public async Task Index(StartPage currentPage) {
    	...
    	HttpContextBase context = ControllerContext.HttpContext;
    	
    	string currentUsername = EPiServer.Security.PrincipalInfo.CurrentPrincipal.Identity.Name;
    	string email = EPiServer.Personalization.EPiServerProfile.Current.Email;
    
    	var userInformation = new Dictionary<string, string>();
    	userInformation.Add("Website", $"http://a-website.com");
    	userInformation.Add("Facebook", $"http://facebook.com/a-fakeid");
    	var userData = new UserData
    	{
        	Email = currentUsername,
        	Name = email,
        	Info = userInformation
    	};
    	try
    	{
        	var myPayload = new MyCustomTrackingData
        	{
            	Value1 = "Home Value 1",
            	Value2 = "Home Value 2",
            	Value3 = "Home Value 3",
            	User = userData
        	};
        	var trackingData = new TrackingData
        	{
            	EventType = "StartPage",
            	PageTitle = currentPage.MetaTitle, //or Title on QuickSilver site
            	Value = "sample-value",
            	PageUri = context.Request.Url.AbsoluteUri,
            	Payload = myPayload,
            	User = userData,
            	Scope = "myScope" // Optional, default is episerver:profiles.Scope setting.
        	};
        	await _trackingService.Track(trackingData, context);
    	}
    	catch (Exception ex)
    	{
    	    throw ex;
    	}
    }]]

    Another example, which sends a page view in the Payload; this is the recommended way of sending page views. Episerver Advance needs the Payload for page views to be structured in this way, to make recommendations work:

    public async Task Index(StartPage currentPage) {
    	...
    
            var local = currentPage as ILocale;
    var language = (currentPage as ILocale)?.Language;

    var siteDefinitionResolver = ServiceLocator.Current.GetInstance<ISiteDefinitionResolver>();
    var site = siteDefinitionResolver.GetByContent(currentPage.ContentLink, true);

    var contentLoader = ServiceLocator.Current.GetInstance<IContentLoader>();
    var ancestors = contentLoader.GetAncestors(currentPage.ContentLink).Select(c => c.ContentGuid).ToArray();
    var trackingData = new TrackingData<dynamic> { EventType = "epiPageView", PageTitle = currentPage.Name, Value = currentPage.ContentLink.ToString(), Payload = new { Epi = new
    {
    contentGuid = currentPage.ContentGuid,
    Language = language.Name,
    SiteId = site.Id,
    Ancestors = ancestors
    } } };

    var trackingService = ServiceLocator.Current.GetInstance<ITrackingService>(); trackingService.Track(trackingData, ControllerContext.RequestContext.HttpContext); }

Note: When you need to track your site, this code should be in every page. You also could use TrackingAttribute in Episerver.Tracking.PageView.

EPiServer.Tracking.PageView

EPiServer.Tracking.PageView is a package that sends page views in a recommended structure. You do not need to use the package page tracking because you can structure the Payload in the recommended way in a normal call to the ITrackingService:

    	    Payload = new
    	    {
        	Epi = new 
{
contentGuid = currentPage.ContentGuid,
Language = language.Name,
SiteId = site.Id,
Ancestors = ancestors
} }

Also ensure that EventType = "epiPageView" is set for page views.

Install EPiServer.Tracking.PageView

  1. Install EPiServer.Tracking.PageView  NuGet package from the Episerver NuGet source to your site.
  2. Add TrackingAttribute to your controller, and the page will be tracked.
    [PageViewTracking]
    public ActionResult Index(StartPage currentPage)
    {}
     
    [ValidateInput(false)]
    [PageViewTracking]
    public ViewResult Index(SearchPage currentPage, string q)
    {}

Install EPiServer.Profiles.Client

  1. Install the EPiServer.Profiles.Client NuGet package from Episerver NuGet source to your site by entering the following command at the Package manager prompt (PM>).
    PM> install-package episerver.profiles.client
  2. Open web.config, fill tracking baseUrl and subscriptionKey values in appsetting section.
    <add key="episerver:profiles.TrackingApiBaseUrl" value="ChangeThis" />
    <add key="episerver:profiles.TrackingApiSubscriptionKey" value="ChangeThis" />
  3. Make sure that episerver:tracking.Enable configuration is set to true.
  4. Optionally, specify episerver:profiles.Scope = <default_scope_you_want_to_send>. The default Scope cannot include special characters such as: + - _ \ / # < > ...
  5. Set correct episerver:profiles.TrackingApiBaseUrl  as your Tracking URL and episerver:profiles.TrackingApiSubscriptionKey as your subscription key. Now you can verify your tracking data in Insight UI.

Configure Tracking

Scope

In  web.config, go to the <appSettings> section, and change value of ProfileStoreTrackingEnable to true. Also add a new key episerver:profiles.Scope. 

Keep the scope values lowercased.

<add key="episerver:profiles.ProfileStoreTrackingEnabled" value="true" /> 
<add key="episerver:profiles.Scope" value="defaultscope" /> 

TrackID

TrackID provides a way to define TrackEvent uniqueness on a specific ClientID and Scope, regardless of other values. This means that if two TrackEvents have the same TrackID, ClientID and Scope, they will be treated as equal.

If TrackID is duplicated, the TrackEvent will be skipped from processing silently, meaning no error messages will inform to user.

If TrackID is not specified, then TrackEvent behaves normally and TrackID is left empty on that TrackEvent.

Comments