Usage

Table of contents

  1. Introduction
  2. Usage
  3. Events
  4. SDK standard event methods
    1. addToCart
    2. emptycart
    3. item
    4. login
    5. selectItem
    6. viewCategory
    7. viewItem
    8. viewSearch
    9. Custom Events
  5. User
  6. Validation and Debug Mode
  7. 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 in addition.

Event listener

Depending on how the Wunderkind tag is placed on the page and where your own JavaScript code runs, it could happen that the Web SDK is not available. To address those scenarios we advise you to add an event listener for the event onWunderkindWebSDKLoaded in the 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:

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

SDK standard event methods

All SDK event methods can accept custom properties as an argument. To pass in custom properties simply pass in an object with those properties as an argument to the SDK event method, as shown in the following example.


wunderkindSDK('viewItem', { rating: '5 stars' });

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


addToCart

This event is triggered when a user adds an item to their cart.

The property item:id is required. A string representing the id of the item being added to the cart.

wunderkindSDK('addToCart', { 'item:id': 'item-12345' });

emptyCart

This event should only be triggered when a user has items in their cart and empties it. Not every time a user opens their empty cart.

This event does not require any properties. Called when the visitor clears the cart.

wunderkindSDK('emptyCart', {});

item

The minimum required properties are:

  • id string representing the id of the item.
  • imageurl a valid url with an image of the item.
  • url a valid url to the item’s page.

wunderkindSDK(
 'item',
 {
   'id': 'item-12345',
   'imageurl': 'https://www.google.com/logo.png',
   'url': 'https://www.google.com/',
 }
);

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

selectItem

Triggered when a user selects specific product attributes (e.g. color, size, etc)

  • The property item:id is required.
  • The property item:feedid should be the product's SKU
wunderkindSDK(
 'selectItem',
 {
   'item:id': 'item-12345',
   'item:feedid': 'feed-item-12345',
 }
);

viewCategory

The property items:ids is a required array of strings with the ids of the items under the viewed category.


wunderkindSDK(
 'viewCategory',
 {
   'items:ids':  ['item-98765', 'item-12345'],
 }
);

viewItem

Triggered when a user views an item or product within the app.

The property item:id is required.


wunderkindSDK(
 'viewItem',
 {
   'item:id': 'item-12345',
 }
);

viewSearch

The property items:ids is a required array of strings with the item ids of the search result.


wunderkindSDK(
 'viewSearch',
 {
   'items:ids':  ['item-98765', 'item-12345'],
 }
);


Custom Events


The Wunderkind Web SDK also allows for 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.

An example:


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

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

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

This will send an event to Wunderkind whose event name is view_denim. Conceptually this can be thought of as having an event method like:

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

The eventName will be passed to Wunderkind and extracted from the customProperties object and the remaining custom properties will be associated with the event and sent to Wunderkind.


User

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


getId

This method allows you to get a specific ids belonging to the current user or visitor. It expects as a parameter 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 on 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

The expected response will have the following shape:

{
  "external_id": "string",
  "external_id_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 uid2Id = await wunderkind.sdk.user.getId('wknd');

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

Validation and 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 that you 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 that you are trying to use the Web SDK from a State or Country that is not configured. Maybe you are using a VPN or working from a different location, if that’s not the case and your current location is expected to work, reach out to your Wunderking representative to debug or update the configuration.