JavaScript API Library

Part of the onsite JavaScript library, these functions offer an easy alternative to using traditional server-to-server integrations to connect with the API.

Include these easily configurable JavaScript functions on your site, allowing the user's browser to communicate directly with the system to perform actions including signing up a user, adding an item to a cart, making a purchase, or a custom event. These functions are fully compatible with popular tag managers including Google Tag Manager, allowing for quick and easy implementation. Note that each of these functions are capable of initiating Lifecycle Optimizer flows for the user in response to the action that they represent. These JS calls offer a subset of the many capabilities of the API. If you have sufficient development resources, it is recommended that you consider coding a server-side API integration, as AJAX requests from the browser introduce the possibility of occasional dropped calls due to latency. However, the success/error responses provided by these functions offer the opportunity to compensate for any such issues that may arise. It's simple to get up and running. Use a tag manager or copy and paste the following script tag into your site.

Copy
<script src="https://ak.sail-horizon.com/spm/spm.v1.min.js"></script><script>Sailthru.init({ customerId: <yourId> });</script>

For details about setting up this latest JavaScript for all other functions, please see Personalization Engine Setup. Note that these simple integration functions are also available for our clients using v0.0.4 of the script tag.

userSignUp

Add a user by email address, or modify data for an existing user. You can optionally add or update Natural List membership(s), user var data, and an acquisition source.

  • The function will update an existing user profile if the email address already exists as a user profile key.
  • Recent pageviews, recorded to a cookie while the user was browsing anonymously, are automatically passed into the function to build the new or existing user's interest profile.
  • The response will contain the user's unique identifier, which the JavaScript will set as the sailthru_hid cookie to identify the user for current and future browsing sessions. This function can be used to easily drop the cookie for known users once your system has identified them (for example, when the user logs in to your site).
  • This function does not support the optout_email parameter. To opt users back in, instead make a User API call or another method described in the Allowing Users to Opt Back In documentation.

The capabilities of userSignUp can alternatively be performed with the User API.

Alternatively, you can use the userSignUpConfirmedOptIn function, which sends a confirmation email and only adds the user to a specified list after the user clicks a confirmation link within the email.

Usage

Copy
Sailthru.integration("userSignUp",
{
  "email" : "<user id>",
  "lists" : { <list1> : <membership>, <list2> : <membership> },
  "vars" : { <var key and value> },
  "source" : <string>,
  "onSuccess": <response>,
  "onError": <response>});

Parameters

  • email - Required
  • lists - Natural lists to add the user. Required if vars or source not specified
    • Use key-value pairs, with listName as key.
    • Value of 1 to add to the list.
    • Value of 0 to remove from the list.
  • vars - Required if lists or source not specified
  • source - acquisition source name (e.g. "Facebook campaign") - Optional
  • onSuccess - JavaScript function that is called on a successful submission - Optional
  • onError - JavaScript function that is called when the function fails - Optional

Example

Copy
Sailthru.integration("userSignUp"
{ "email" : "user@example.com",
  "lists" : {
    "Main List" : 1, // list to add user to (must exist in Sailthru account)
    "Anonymous" : 0 // list to remove user from (must exist in Sailthru account)
  },
  "vars" : {
    "sign_up_date" : "2018-08-20",
    "first_name" : "Bob"  },
  "source" : "web",
  "onSuccess" : function() {
    alert('Thank you for signing up for our list');
   },
  "onError" : function() {
    alert('We encountered an issue signing you up. Please try again');
   }
});

GDPR Note To avoid tracking anonymous users who opt-out of anonymous user tracking, delete the sailthru_content cookie, or the sailthru_cid cookie if using older Horizon JS, before making the userSignUp call. That way no anonymous user data is being tracked. Initiate the following JavaScript before the user sign up call:

Copy
document.cookie='sailthru_content=; path=/'

For Horizon JavaScript:

Copy
document.cookie='sailthru_cid=; path=/'

userSignUpConfirmedOptin

Request that an opt-in confirmation email is sent to a user before they are added to a specified list. If the user does not already exist then the user is added to your account. In any case, the user will not be added to the list until they confirm via the link in the confirmation email. Recent pageviews, recorded to a cookie while the user was browsing anonymously, are automatically passed into the function to build the new or existing user's interest profile. In conjunction, you can create Lifecycle Optimizer flow that is initiated when the user finally enters the target list. The capabilities of userSignUpConfirmedOptin can alternatively be performed with the User API.

Usage

Copy
Sailthru.integration("userSignUpConfirmedOptIn", {
   "id" : "<user id>",
   "key" : "<user id type>",
   "source" : "<acquisition source>",
   "template" : {
       "name" : "<confirmed opt-in template name>",
       "vars" : {
           "<var name 1>": "<var value 1>",
           "<var name 2>": "<var value 2>"       },
   "vars" : { "<var name 1>": "<var value 1>" },
   "onSuccess" : <response>,
   "onError" : <response>   }
});

Parameters

  • email - Required
  • id - alternate user identifier - Required if email not included
  • key - type of specified id - Required if email not included; supported keys are email, extid, fb, sms, twitter; for more details, see key details in the User API documentation
  • name - Confirmed opt-in template to send - Required
  • vars - Template vars; vars accessible within the opt-in template - Optional
  • source - acquisition source name (e.g. "Facebook campaign") - Optional
  • source - acquisition source name (e.g. "Facebook campaign") - Optional
  • vars - User var names and values to add/update - Optional
  • onSuccess - JavaScript function that is called on a successful submission - Optional
  • onError - JavaScript function that is called when the function fails - Optional

Example

Copy
Sailthru.integration('userSignUpConfirmedOptIn', {
    "id" : "user@example.com",
    "key" : "email",
    "source" : "Twitter campaign",
    "template" : {
        "name" : "twitter_welcome",
        "vars" : {
            "name": "Mike",
            "source_tweet": "https://twitter.com/sailthru/status/829425076672069632"        }
    },
    "vars" : {
        "sign_up_date" : "2018-08-20",
        "first_name" : "Mike"    },
    "onSuccess" : function () {
    alert('Thank you for signing up for our list');
    },
    "onError" : function () {
    alert('We encountered an issue signing you up. Please try again');
    }
});

addToCart

Call this function each time a user adds an item to their cart or removes an item from their cart. Each time the cart contents changes, submit an array of all cart items.

Notes:
  • To remind a user about an abandoned cart, use Lifecycle Optimizer to power an abandoned-cart reminder flow that uses onsite inactivity after the cart addition to trigger the reminder. Both methods are described here. All parameters available for a purchase in the Purchase API are available with this function, as well. Required parameters are email and either URL or SKU. 
  • The email parameter is not required if the sailthru_hid cookie is present on the user profile. 

Usage:

Copy
Sailthru.integration("addToCart", { "email": "<user email>", "items": [{ "url": <url>, "qty": <quantity>, "title": "<title>" }], });

Parameters

  • email - Required
  • items - Required
    • url - Required
    • qty - Quantity of item - Required
    • title - Required
    • sku - Optional
    • images - Optional
    • vars - Item-specific vars for purchase - Optional
    • price - Pass as an integer in cents. For example, pass $50.00 as 5000 - Optional
  • onSuccess - JavaScript function that is called on a successful submission - Optional
  • onError - JavaScript function that is called when the function fails - Optional

Example

Copy
Sailthru.integration("addToCart", {
  "email": "user@example.com",
  "items": [{
    "url": "http://example.com/item/12345",
    "qty": 1,
    "sku": 123456789
    "title": "Great Boots",
    "price": 13900,
    "images": {"full": "http://example.com/image/12345.png"}, 
    "vars" : {"discount": 123
  }],
   "vars" : {"free_shipping": "yes"
 });

purchase

Call this function each time a user completes a purchase, submitting an array of all purchased items. This will cancel any scheduled cart reminder email, and decrement stock levels if they are synced with the system. App purchase attribution is not available for the Javascript API. You can configure a Lifecycle Optimizer flow to initiate each time a purchase is sent using this function. Just set the Entry to Purchase Made. All parameters available for a cart update in the Purchase API are available for use with this function, as well. The "channel" parameter for purchases is handled via the JS library and will automatically be set to "online". Required parameters are email and URL or SKU.

Usage

Copy
Sailthru.integration("purchase", {
  "email": "<user email>"
  "items": [{
    "url": <url>,
    "qty": <quantity>  }],
 });

Parameters

  • email - Required
  • items - Required
    • url or sku - Required
    • qty - Quantity of item - Optional
    • title - Required
    • images - Optional
    • vars - Item-specific vars for purchase - Optional
    • price - Optional
  • For additional optional parameters, see the Purchase API POST call.
  • onSuccess - JavaScript function that is called on a successful submission - optional
  • onError - JavaScript function that is called when the function fails - optional

The email parameter is not required if the sailthru_hid cookie is present on the user profile. 

Example

Copy
Sailthru.integration("purchase", {
    "email": "user@example.com",
    "items": [{
            "url": "http://example.com/item/12345",
            "sku": 123456789
            "qty": 1,
            "title": "Great Boots",
            "price": 13900,
            "images": {"full": "http://example.com/image/12345.png"}, 
            "vars" : {"discount": 123
            
        }],
    "tenders": [
            {
                "price":"13900",
                "title":"Amex"            }
        ],
    "purchase_keys": {
        "extid":"123"    },
    "vars" : {"free_shipping": "yes"
});

customEvent

Trigger a custom event call to add/update a user var, send an email, initiate a Lifecycle Optimizer flow, or other event. The schedule_time parameter is not supported. The trigger time defaults to 'now'.

Usage

Identify user by email

Copy
Sailthru.integration('customEvent', {
    "name" : "<eventName>"
    "email" : "<userEmailAddress>",
    "vars" :
    {
        "<varKey1>": "<varValue1>",
        "<varKey2>": "<varValue2>"    }
});

Identify user by id and key

Copy
Sailthru.integration('customEvent', {
    "name" : "<eventName>",
    "id" : "<userIdentifier>",
    "key" : "<userIdentifierType>",
    "vars": {
        "<varKey1>": "<varValue1>",
        "<varKey2>": "<varValue2>"    }
});

Parameters

  • event - the name of the event you want triggered in the system - Required
  • email - user's email address - Required if ID/key object not included
  • id - alternate user identifier - Required if email not included
  • key - type of specified id - Required if email not included; must match a key type available via User API
  • vars{} - event var names to be sent with the event. These can be inspected at the event level by Lifecycle Optimizer, for example - Optional
  • onSuccess - JavaScript function that is called on a successful submission - Optional
  • onError - JavaScript function that is called when the function fails - Optional

Example

Copy
Sailthru.integration("customEvent", {
    "name" : "share"
    "email" : "avi@example.com",
    "vars": {
        "latest_share_source": "facebook",
        "shared_item": "http://example.com/item/123"    }
});

Sailthru.integration("customEvent", {
    "name": "Like"    "id": "15551234567",
    "key": "sms",
    "vars": {
        "firstname": "Jack",
        "environment": "mobile"    }
});

getCurrentUser

If a sailthru_hid cookie is present in the browser, representing the identification of a known user profile in your account, this function returns the hashed email address of the user. This allows your site or additional third-party services to recognize the user. By default, a SHA256 hash is returned, but the option to instead receive an MD5 hash is also available. This function requires that your site has included the latest version of the JavaScript, which is located at https://ak.sail-horizon.com/spm/spm.v1.min.js.

  • If the cookie exists and the user is identified, your provided onSuccess function is called. An object containing the user's email hash is passed to this function.
  • If the cookie exists but an unexpected error occurs, the onError function is called.
  • If the cookie does not exist, no call is sent and no response is received.

Usage

To request SHA256 hash

Copy
Sailthru.integration('getCurrentUser', {
 onError: function(response) {<function>},
 onSuccess: function(response) {<function>}
 });

To request MD5 hash

Copy
Sailthru.integration('getCurrentUser', {
 {'hash' : "md5"},
 onError: function(response) {<function>},
 onSuccess: function(response) {<function>}
 });

Parameters

  • hash - Hashing algorithm; sha256 or md5. md5 is used if neither is specified - Optional
  • onSuccess - JavaScript function that is called after a successfully submitted getCurrentUser call - Recommended
  • onError - JavaScript function that is called if the getCurrentUser call is made (sailthru_hid cookie exists) but it encounters an error - Optional

Example Call

A common use case for a hashed email address is to pass the hashed email to a third party service for email address matching, for example if you are using DMP or programmatic advertising provider. Each provider has a different set of requirements but the example below highlights how you can use the getCurrentUser function to construct a call for a remote image with additional parameters defined. This is a common technique used in the industry to pass data. Commonly known as a firing a "pixel" or a cookie match. The example below constructs an image request where providerId would receive the emailHash and partnerId would contain the hashed email. Adjust as needed for your provider.

Copy
Sailthru.integration('getCurrentUser',
{
onError: function(response) { console.log('getCurrentUser ERROR', response); },
onSuccess: function(response) { 
var img = document.createElement('img');
    var pixel_url = "https://example.com?providerId=123&partnerId=" + response.emailHash;
img.src = pixel_url;
}
});

Example Response Value Passed to onSuccess Function

Copy
{"emailHash":"b4c9a289323b21a01c3e940f150eb9b8c542587f1abfd8f0e1cc1ffc5e475514"}

Example Response Value Passed to onError Function

Copy
{"error": "Invalid horizon Id 9fc1520ffd4114dd4db35bf7c9904ecabf7286b9d7d7833967826dbb5e3eb4d9"}

gdprDoNotTrack

Opt out a user from online tracking across devices whenever a user identifies themselves

  • The function will update an existing user profile with the status 'do not track'
  • A sailthru_hid cookie is set so the 'Do Not Track' designation is retained indefinitely on the user's browser client
  • All cookies used for tracking purposes are purged and will not be created for 'Do Not Track' users

The following cookies are removed and not created for 'Do Not Track' users:

  • sailthru_content - content viewed
  • sailthru_pc - personalized content clicked on
  • sailthru_bid - source email, used for purchase attribution
  • sailthru_sid - sailthru identifier
  • sailthru_cid - content viewed
  • sailthru_rid - Concierge and Scout clicked personalized content
  • sailthru_recommendation_hidden - Concierge close designation

The system does retain and record data after a user has chosen to opt out of tracking, however that data contains no identifiable information about the user. Data exchanged after the 'Do Not Track' designation has been set includes general engagement metrics (like the number of page views) and anonymous personalization calls.

Usage

Copy
Sailthru.track('gdprDoNotTrack', {
  onSuccess: <function>,
  onError: <function>});

Parameters No parameters required. The gdprDoNotTrack function will identify the user from the sailthru_hid cookie or create one automatically, should the user not be known.

cookiesDoNotTrack

Suppress tracking cookies without opting out a user.
  • Onsite activity information for a user will not be available. This includes events such as pageviews and clicks.
  • User email engagement data is still available. This includes clicks that originate from an email to lead a user to a webpage.

Usage

The following snippet activates the suppression behavior.

Copy
Sailthru.track('cookiesDoNotTrack');

The following snippet deactivates the suppression behavior.

Copy
Sailthru.track('cookiesDoNotTrack',{set:false}); 

Calling cookiesDoNotTrack on click

Calling cookiesDoNotTrack on click requires a button identifier (a class or ID) and an event listener. The following sample:

  • Creates a button and adds a button ID.
  • Gets the button by ID.
  • Adds an event listener for the click event that calls the Sailthru.track function.
Copy
<button id="cdnt-button">Button Text</button><script>   const cdntButton = document.getElementById("cdnt-button");
   cdntButton.addEventListener("click", () => {
        Sailthru.track("cookiesDoNotTrack");
   });
</script>