JavaScript API

Initialize the Library

Paste this HTML script tag within the <head> tag of your page, replacing WRITE_KEY and ENDPOINT with the write key and endpoint generated by the integration you created.

<script type="text/javascript">
(function(r,t){var e=window;var n=e[t];if(!n){n=e[t]=[]}var a=["identify","page","track","flush","setSessionId","setUserId","setConfig","user.set","user.setOnce","user.unset","user.increment"];function s(r){var e=r.split(".");var a=e[0];var s=n;if(e.length===2){s=n[a]=n[a]||{};a=e[1]}s[a]=function(){var t=[r];t.push.apply(t,Array.prototype.slice.call(arguments));n.push(t);return n};s[a].toString=function(){return"".concat(t,".").concat(r," (stub)")}}for(var i=0;i<a.length;i++){var u=a[i];s(u)}n.init=function(e){var a=r.createElement("script");a.type="text/javascript";a.async=true;a.setAttribute("data-fp-lib-name",t);a.src=typeof FANPLAYR_CUSTOM_LIB_URL!=="undefined"?FANPLAYR_CUSTOM_LIB_URL:"https://cdn.fanplayr.com/cdp/fanplayr-latest.min.js";var s=r.getElementsByTagName("script")[0];s.parentNode.insertBefore(a,s);n["_config"]=e;n["_snippetVersion"]="1.0.4"};return n})(document,"fp360");

fp360.init({
  writeKey: "WRITE_KEY",
  endpoint: "ENDPOINT",
  debug: true
});
</script>

Once the above code has run, the fp360 object will be available globally in your JavaScript.

The debug flag is useful during implementation, but it is recommended to remove it for production use.

Track Events

Once you have the Fanplayr 360 library on your page you can track an event by calling fp360.track with the event name and properties.

fp360.track("Product Viewed", {
  "MyCustomAttribute": "My Custom Attribute",
  "$product": {
    "name": "Red Shoes"
  }
});

Tracking calls can include Semantic Data. If you are sending custom attributes you should always send simple key / value pairs, but Semantic Data may include objects.

The example above uses a $product Semantic Object.

Handling Sessions

// Set a session identifier
fp360.setSessionId("<SESSION IDENTIFER>");

// Set a primary user identifer
fp360.setUserId("<USER IDENTIFIER>");

Sessions will automatically end after 45 minutes from last event sent with a given session identifier.

User IDs set here are different than User Identity, and in general you will not have to handle any of this stuff yourself.

Track Pages

The page call lets you record whenever a user sees a page of your website, along with any optional properties about the page.

fp360.page({
  type: "home",
  name: "My Page Title"
});

Any value can be provided for type but if you use one of the following it may be used to add functionality to Insights.

  • "home"

  • "category"

  • "product"

  • "cart"

  • "search"

  • "blog"

  • "checkout"

Managing User Identity

Primary identity

By default Fanplayr 360 generates a unique identifier (UUID) for the user and stores it in LocalStorage in the browser. You can override this identifier by providing your own unique value for the user.

fp360.setUserId("UNIQUE_USER_ID");

Secondary identifiers

Users may interact with your business using multiple devices and unless you provide a consistent primary identifier for the user with the setUserId method, they will appear as different users on each device.

If you're unable to provide a primary identifier immediately at the start of each page view, an alternative is to provide secondary identifiers which Fanplayr 360 uses to link primary identifiers together. These are provided as "key" and "value" pairs using the identify method.

For example, an email address or customer loyalty number can be good secondary identifiers because they should remain unique to the user across different devices and systems within your business:

fp360.identify('email', 'user@example.com')

The example above associates a secondary identifier with the current user. Whenever Fanplayr 360 sees two users (primary identities) with any of the same secondary identifiers, it will link those users together so that all events and attributes are associated with the same user profile.

It is OK to call this multiple times. For example you may want to call this on every page view to simplify implementation. The JavaScript library takes care of only sending data if this changes.

If you use email or phone as the identifier then these will be automatically added as semantic user attributes $email and $phone. Additionally, these identifiers will be automatically mapped to the identifiers: $email and $phone.

All user identities are automatically considered to be Medium PII. Learn more about PII here.

Managing User Profile

Attributes can be set on users directly using the user.set call. You can also set information only if it has not already been set using the user.setOnce call, remomve properties using the user.unset call, and increment a counter using the user.increment call.

Setting an attribute

fp360.user.set({
  $firstName: "John",
  $lastName: "Doe",
  favoriteColor: "red"
})

In this example we are tracking two semantic attribute, those starting with a $. These are used within our system to add extra functionality.

You can also set a single attribute attribute at a time:

fp360.user.set("favoriteColor", "green")

Set once

If you want to set an attribute only if it does not yet exist you can:

fp360.user.setOnce({
  $firstName: "Jan",
  favoriteColor: "purple"
})

Or a single item at a time:

fp360.user.setOnce("favoriteColor": "purple"})

Expiry

Sometimes you may want to set an attribute on a user that only lasts until a specific date and time. You can do this by sending in a JavaScript Date object, a timestamp representing number of milliseconds since the epoch, or a string in the format YYYY-MM-DD HH:mm:ss.

You can set on multiple attributes at a time, the following examples all map to the same date and time:

// js date object
fp360.user.set({
  favoriteColor: "red"
}, { expires: new Date("2022-01-01 12:23:01")  })

// timestamp
fp360.user.set({
  favoriteColor: "red"
}, { expires: 1641057781000  })

// relative time
fp360.user.set({
  favoriteColor: "red"
}, { expires: "1day"  })

Or for a single attribute:

fp360.user.set("favoriteColor", "red", { expires: "5min" })

For relative times you can use an integer followed by any of the following - although only the first letter actually needs to be supplied:

  • second(s)

  • minute(s)

  • hour(s)

  • day(s)

  • week(s)

  • year(s)

For example for "3 minutes" from now you could set expires to "3m", "3 minutes" etc.

Removing an attribute

You can remove multiple attribute on a user by sending the keys in as an array:

fp360.user.unset(["favoriteColor", "$firstName"])

Or a single attribute by just the key:

fp360.user.unset("favoriteColor")

Incrementing an attribute

Incrementing an attribute can be used to add counts directly to a user.

fp360.user.increment("numberOfGoodChoices")

If the attribute does not yet exist on a user profile, it will be set to 1.

If an attribute with the name already exists, and it is not an integer, the value will also be set to 1. This is true even if the value is a string of "1" rather than the actual value of 1. Also float values such as 10.5 will be reset to 1 on the first increment call.

You can also increment an attribute by more than 1:

fp360.user.increment("numberOfGoodChoices", 10)

Tracking user consent is very important to keep in compliance with regulation such as GDPR and CCPA, and is good practice to keep your users happy. We offer extensive support for granular consent tracking.

Adding user consent requires at minimum a type such as "email" or "phone" and a value such as "person@example.com".

fp360.consent.set("email", "person@example.com");

The above would simply say that a user has consented to to be contacted by your company via email at a given email address. It does not say for what purpose or specific topics they may be interested in.

Adding a Purpose

fp360.consent.set("email", "person@example.com", {
  purpose: [
    {
      type: "marketing",
    },
    {
      type: "transactional"
    }
  ]
});

The above code would indicate that the user has given permission to be contacted via email, at a specific address, for the purpose of both "marketing" and "transactional" (emails such as order confirmations).

Adding Topics

Sometimes your users may only want to be contacted for specific purposes, or about certain products. You can indicate this using:

fp360.consent.set("email", "person@example.com", {
  purpose: [
    {
      type: "marketing",
      topics: ["Men's Clothing", "Men's Accessories"]
    }
  ]
});

The above code would indicate that a user has given permission to be contacted via email, at a specific address, for the purpose of "marketing" but only about the topics "Men's Clothing" or "Men's accessories.

Setting consent for a type / value that already exists will overwrite current purpose and topics - make sure you always set with all of these properties on each call.

Removing users' consent is easy and only requires a type and value.

fp360.consent.unset("email", "person@example.com");

Flushing the message queue

Fanplayr 360 queues and batches events and other data that is tracked to optimize tracking calls and reduce the network request load for your website visitors.

In some cases you may need to know when all messages have been tracked so that you can allow navigation to other pages. For example, you may be tracking an event to represent a form submission and want to wait for the tracking to complete before navigating the user to another part of the website. In this case, use the flush API:

fp360.track("Contact Form Submitted", {
  email: "me@domain.com",
  message: "Helloworld!"
});

fp360.flush(function() {
  // Fanplayr 360's events have been successfully tracked and the user can
  // be navigated to another page.
});

Use with Fanplayr Targeting

Fanplayr 360 can be easily configured to track data which is already being captured by your Fanplayr Targeting integration. This works as follows:

  1. In Browser: FP 360 is configured to wait for FP Targeting to assign the user and session identifiers it manages. FP 360 tracking APIs (tracking events, managing user data etc) can be invoked at any time and these calls will be automatically queued until FP Targeting has synchronized user and session identifiers.

  2. After FP Targeting session expiry: During processing of a completed FP Targeting session, Fanplayr's servers will automatically translate page views, orders and other events that occurred into the equivalent events and operations within FP 360.

Step 1: Configure Fanplayr 360

Update your FP 360 initialization snippet to disable automatic starting of the browsing session by setting autoStartSession to false. This instructs the library to wait until the setSessionId and setUserId methods are called by Fanplayr Targeting.

fp360.init({
  writeKey: "WRITE_KEY",
  endpoint: "ENDPOINT",
  autoStartSession: false
});

Step 2: Enable identity synchronization in Fanplayr Targeting

There is currently no user-accessible control to enable identity synchronization within the Fanplayr Targeting potal. Please contact your Customer Success manager and request that this feature be enabled on your account.

Once this is complete, Fanplayr Targeting will automatically synchronize user and session identifiers with your Fanplayr 360 JavaScript integration.

Last updated