WebSDK Usage

Table of contents

  1. Introduction
  2. Usage
  3. Events
  4. SDK standard event methods
    1. logIn
    2. item
    3. viewItem
    4. selectItem
    5. addToCart
    6. emptyCart
    7. viewCategory
    8. viewSearch
    9. Custom Events
  5. User
  6. Validation and Troubleshooting

Introduction

This is a guide to using Wunderkind's Client Side JavaScript SDK.

The SDK is part of Wunderkind’s smart-tag and gets attached to the window when Wunderkind's smart-tag loads. You do not need to install any npm package or include an extra script.

The SDK can be accessed at window.wunderkind.sdk. Event methods can be found at window.wunderkind.sdk.events. While the SDK can be accessed off the window, we strongly recommend using the function described in the Usage section below to avoid race condition related issues.

Usage

Wrapper function

The Wunderkind Web SDK loads with smart-tag and is attached to the window as part of the wunderkind window object.

We recommend using the following function to access the SDK to avoid any issues due to race conditions between when your site loads, events fire, and when smart-tag loads with the Web SDK.

function wunderkindSDK(eventName, payload) {
 var sdk = window.wunderkind &&
   window.wunderkind.sdk &&
   window.wunderkind.sdk.events;


 if (sdk) {
   if (sdk[eventName]) {
     return sdk[eventName](payload);
   }
   // console.log('wunderkindSDK Event method not found:', eventName); // Optionally log the error
   return;
 }


 try {
   var items = JSON.parse(localStorage.getItem('wknd_web_sdk_preloaded_events'));
 } catch (e) {
   // console.log('wunderkindSDK Error parsing preloaded events:', e); // Optionally log the error
 }


 if (Object.prototype.toString.call(items) !== '[object Array]') {
   items = [];
 }
 items.push({ eventName: eventName, payload: payload });
 localStorage.setItem('wknd_web_sdk_preloaded_events', JSON.stringify(items));
}

The wrapper function will help to cache any calls to the methods under window.wunderkind.sdk.events triggered before the Web SDK is loaded. You can trigger events by invoking the above function:


wunderkindSDK('addToCart', data);

All required and optional properties are passed to the SDK event methods directly via an object. Please note that when taking this approach, the required properties must match exactly as written. Any custom properties can be attached as an addition.

Event listener

Depending on how the Wunderkind tag is placed on the page and where your own JavaScript code runs, there might be scenarios when the Web SDK is not available. To address this, we advise that you add an event listener for the event onWunderkindWebSDKLoaded attached to the browser's window object.

function useWkndWebSDK() {
  // Safely call Wunderkind SDK methods here
}

// Is Wunderkind SDK loaded?
if (window.wunderkind && window.wunderkind.sdk) {    
  // Wunderkind SDK is loaded, use it  
  useWkndWebSDK();
} else {  
  // Not yet loaded; wait for the "onWunderkindWebSDKLoaded" event  
  window.addEventListener('onWunderkindWebSDKLoaded', function () {    
    // Wunderkind SDK is loaded, now we can use it  
    useWkndWebSDK();  
  }, false);
}

Events

The SDK exposes methods that dispatch Wunderkind standard events and also offer the ability to dispatch custom events to the Wunderkind platform.

All SDK event methods are asynchronous but they do not need to be awaited. They can be treated as fire and forget. The full list of event methods are:

  • logIn
  • item
  • viewItem
  • selectItem
  • addToCart
  • emptyCart
  • viewCategory
  • viewSearch
  • customEvent

SDK standard event methods

Each method and its properties are defined in the following sections. NOTE: All values are strings unless otherwise denoted.

logIn

This event should be passed on every page view when:

  • A signed-in user starts a session
  • A user signs in during their session
  • A user signs up during their session

At least one of the following properties should be provided:

  • email(string): a valid plain text email
  • emailHash(string): a valid SHA256 hashed email address
  • espemailid(string): an ESP email ID
wunderkindSDK(
 'logIn',
 {
   email: '[email protected]',
   emailHash: '4206568eb3da183b6b300163c2c00592f06a0ff87a2b808409038c9ab2ab7f97',
   espemailid: 'item-12345',
 }
);

item

This event should be triggered when a user views an item.

The required fields are:

  • id(string): the id of the item - each unique product page should have a distinct item id
  • imageurl(string): a valid url with an image of the item
  • url(string): a valid url to the product page, stripped of any extra parameters
  • copy(string): the item name as it should be displayed in emails
  • category(string): the item type (e.g., "shirts") or a collection to associate the item with (e.g., "best sellers")
  • instock (boolean): a true/false value indicating if the item is fully (all skus) in or out of stock

Additional properties can be added to track custom metadata, such as ratings or star values. They should follow the same syntax as above, example below.

  • excluded (boolean): an optional true/false value indicating if the item should be excluded from all Wunderkind emails
  • rating_number(string): example: "5"
  • brand(string): example: example: "Polo Brand"
wunderkindSDK(
 'item',
	{
   id: 'item-12345',
   copy: 'Polo',
   category: 'Shirts',
   url: 'https://www.clientname.com/polos/item-12345',
   imageurl: 'https://www.clientname.com/logo.png',
   instock: 'true'
 }
);

viewItem

This event should be triggered when a user views an item. The required fields are:

  • item:id(string): must match the id included in the item event
  • item:itemgroupid* (string): the overall item group id that represents a collection of SKUs - may or may not be the same as item:id, since item:itemgroupid must correspond to the group id in the product feed *Only needed if the client is running group-level catalog modules
wunderkindSDK(
 'viewItem',
 {
   'item:id': 'item-12345',
   'item:itemgroupid': 'group-item-12345'
 }
);

selectItem

This event should be triggered when a user selects specific product attributes (e.g., color, size, etc). The required fields are:

  • item:id(string): must match id included in the item event & item:id included in the view item event
  • item:feedid(string): the selected variant’s unique SKU, that must correspond to the SKU in the product feed
  • item:itemgroupid(string): the overall item group id that represents a collection of SKUs - may or may not be the same as item:id, as item:itemgroupid must correspond to the group id in the product feed

wunderkindSDK(
 'selectItem',
 {
   'item:id': 'item-12345',
   'item:itemgroupid': 'group-item-12345',
   'item:feedid': 'feed-item-12345'
 }
);

addToCart

This event should be triggered when a user adds an item to the cart. The required field is:

  • item:id(string): the id of the item being added to cart
wunderkindSDK('addToCart', { 'item:id': 'item-12345' });

emptyCart

This event should only be triggered when a user has items in the cart and empties it, not every time a user opens an empty cart. This event does not require any properties. It should be called when the user clears the cart.

wunderkindSDK('emptyCart', {});

viewCategory

This event should be triggered when a user lands on a category page. The required fields are:

  • items:ids(string[]): array of comma-separated item ids for items visible on the category page
  • page:url(string): valid url for current category page, stripped of any extra parameters

wunderkindSDK(
 'viewCategory',
 {
   'items:ids': ['item-98765', 'item-12345'],
   'page:url': 'https://www.clientname.com/collections/mens-polos'
 }
);

viewSearch

This event should only be set up if the client is running a separate Search Abandonment email series. Otherwise, the client should utilize the view category event for search pages.

If the client is running a Search Abandonment email series, then this event should be triggered when a user lands on a search page. The required fields are:

  • items:ids(string[]): array of comma-separated item ids for items visible on the search page
  • page:url(string): valid url for current search page - query params must be included to ensure user sees same items upon clickthrough
wunderkindSDK(
 'viewSearch',
 {
   'items:ids':  ['item-98765', 'item-12345'],
   'page:url': 'https://www.clientname.com/search?query=mens-polos'
 }
);

Custom Events

The Wunderkind Web SDK also allows for the submission of custom events. To programmatically send custom events, use the customEvent method.

The parameter for this method must be an object that has at least 1 key value pair where one of the property’s keys is eventName and whose value is the event name as a string. Custom event names should follow the SDK camelCase naming conventions unless otherwise specified.

An example:

wunderkindSDK(
 'customEvent',
 {
   eventName: 'viewDenim'
 }
);

Like all SDK event methods, custom properties can also be included by simply adding them to the object parameter:

wunderkindSDK(
 'customEvent',
 {
   eventName: 'viewDenim',
   searchQuery: 'jeans'
 }
);

User

The calls to some of the methods in this namespace cannot be cached, and you need to make sure the SDK has loaded before you call them to avoid any errors, so we advise that you add an event listener as described here.

getId

This method allows you to get specific ids belonging to the current user or visitor. The expected parameter is the name of the type of id that you want to read. The supported id types are uid2 and wknd.

Reach out to your Wunderkind representative to learn more about how to enable user ids in the Web SDK.

uid2

The expected response will have the following shape:

{
  "advertising_token": "string",,
  "identity_expires": "string",
 }

If no uid2 id is found, the promise returned by the Web SDK call will resolve to null.

Code Example:

// You can await or use a callaback
const uid2Id = await wunderkind.sdk.user.getId('uid2');

wunderkind.sdk.user.getId('uid2').then((uid2) => {
	// Do things with the uid2 id
});

wknd

To get the wknd id, you will need to pass an object to the getId call with the property external_id_type. The value of this property will be defined when your site is being onboarded.

The expected response will have the following shape:

{
  "external_id": {
    "id": "string",
    "name": "string"
  }
}

if no wknd id is found, the promise returned by the Web SDK call will resolve to null.

Code Example:

// You can await or use a callaback
const wkndId = await wunderkind.sdk.user.getId('wknd', {external_id_type: 'customer_id'});

wunderkind.sdk.user.getId('wknd', {external_id_type: 'customer_id'}).then((wknd) => {
	// Do things with the Wunderkind id
});

Validation and Troubleshooting:

Debug Mode:

The SDK comes with some validation and debugging capabilities to help ensure the correct and successful integration of the SDK.

By default, the SDK will perform some validation of arguments to SDK methods. This form of validation only checks required properties and does not check optional properties.

If any errors are found, the event will not be emitted and a value of Promise<null> will be returned.

To enable the SDK logs, you need to execute the following command from the browser console:

wunderkind.sdk.turnOnDebugging();

After executing that command and refreshing the page, you will be able to see the SDK activity in the console. The debugger flag is persisted in localStorage so remember to turn it on if you clear your browser data or if you are testing on different domains. To focus on SDK messages, you can filter your messages with the keywords: “web sdk”.

The previous image shows an example of the SDK logging. Most of the messages include the method name that was invoked, the payload that was passed to the event, and in the case of a validation error, the name of the property not passing validation and an example of the minimal valid payload. It is possible to see properties that you did not pass like “agent” which are added automatically by the SDK.

If you want to turn off the SDK logging, execute the following command in the console.

wunderkind.sdk.turnOffDebugging();

Troubleshooting "SDK outside of the supported region":

If no events are being dispatched and you see the message shown below in the console after turning on the debug mode, this means you are trying to use the Web SDK from a state or country that is not configured. This might happen if you are using a VPN or working from a different location. If that is not the case and your current location is expected to work, reach out to your Wunderking representative to debug or update the configuration.

Event Monitoring:

To caveat, the dashboard below only works for events flowing into production, so you will not see any events in this dashboard when you first set up events (as events will initially only be in Wunderkind staging). Once live in production, though, you can validate that Wunderkind is tracking events by checking Wunderkind Platform > Analytics > Event Monitoring. This dashboard has a ~2 hour reporting delay, and the times are in EST.