Aller au contenu principal

Web SDK Integration Guide

This tutorial explains how to integrate the new and enhanced Rokt Web SDK into a website for advertisers who want to collect data about conversions, user attributes, and user behavior to improve ad relevance.

Your dedicated account representative will help configure your account for the Web SDK. They will provide you with both the API key required to initialize the SDK and additional resources needed to render the most relevant experiences for your customers.

remarque

The below instructions will require development resources to complete. If you require additional assistance, please reach out to your Rokt account manager.

remarque

Work with your Rokt account manager to first implement the SDK in a development environment. This allows you to thoroughly test and troubleshoot your integration before releasing it in a production environment.

First-Party Domain Configuration

Rokt recommends using a first-party domain when integrating the SDK into your site. This ensures that the Rokt SDK uses your own domain when making calls to Rokt's API, providing your customers with a seamless experience and minimizing the risk of blocked content.

To learn how to configure a first-party domain for your SDK integration, see First Party Domain Integration.

1. Initialize the Rokt SDK

To initialize the SDK, copy and paste the SDK initialization script into your site.

Every site is different, but Rokt recommends including the SDK script on every page. This ensures the lowest offer delivery latency and the highest user identification accuracy.

  • Single-page Applications (SPA): If your website is an SPA, insert the initialization script into the <head> of the main index.html page, or the primary location where the rest of your content is rendered.
  • Multi-page Applications (MPA): If your website is an MPA and you use a template-base rendering system (most common), place the initialization script in the primary shared layout file. If you don’t use a template-based rendering system, place the script in each HTML file of your website.

Note that although each page may include the script, due to browser caching, the SDK would load from cache by default rather than being loaded upon each page load of your website.

SDK Initialization Script

attention
  • Replace "YOUR_API_KEY" with the API key provided by your dedicated Rokt team.
  • Set DOMAIN to the subdomain you created during your first-party domain configuration.
<script type="text/javascript">

// Enter your Rokt API key
const API_KEY = "YOUR_API_KEY";

// If you configured a first-party domain, set it as the value of DOMAIN instead of the default apps.rokt-api domain
const DOMAIN = "https://apps.rokt-api.com";

// Set your SDK configuration settings
window.mParticle = {
config: {
// Specify the data environment with isDevelopmentMode:
// Set isDevelopmentMode to true if you are still testing your integration.
// Set isDevelopmentMode to false if your integration is ready for production data.
isDevelopmentMode: true,
// Identify the current user:
// If you have the user's email address, include it in an object called `userIdentities` within `identifyRequest` as shown below.
identifyRequest: {
userIdentities: {
// If you're using an un-hashed email address, set it in 'email'.
email: 'j.smith@example.com',
// If you're using a hashed email address, set it in 'other' instead of `email`.
other: 'sha256 hashed email goes here'
},
}
},
};

// Load the SDK
(function(e) { window.mParticle = window.mParticle || {}; window.mParticle.EventType = { Unknown: 0, Navigation: 1, Location: 2, Search: 3, Transaction: 4, UserContent: 5, UserPreference: 6, Social: 7, Other: 8, Media: 9 }; window.mParticle.eCommerce = { Cart: {} }; window.mParticle.Identity = {}; window.mParticle.Rokt = {}; window.mParticle.config = window.mParticle.config || {}; window.mParticle.config.rq = []; window.mParticle.config.snippetVersion = 2.5; window.mParticle.ready = function(e) { window.mParticle.config.rq.push(e); }; ["endSession", "logError", "logBaseEvent", "logEvent", "logForm", "logLink", "logPageView", "setSessionAttribute", "setAppName", "setAppVersion", "setOptOut", "setPosition", "startNewSession", "startTrackingLocation", "stopTrackingLocation"].forEach(function(e) { window.mParticle[e] = function() { var t = Array.prototype.slice.call(arguments); t.unshift(e); window.mParticle.config.rq.push(t); }; }); ["setCurrencyCode", "logCheckout"].forEach(function(e) { window.mParticle.eCommerce[e] = function() { var t = Array.prototype.slice.call(arguments); t.unshift("eCommerce." + e); window.mParticle.config.rq.push(t); }; }); ["identify", "login", "logout", "modify"].forEach(function(e) { window.mParticle.Identity[e] = function() { var t = Array.prototype.slice.call(arguments); t.unshift("Identity." + e); window.mParticle.config.rq.push(t); }; }); ["selectPlacements","hashAttributes","setExtensionData"].forEach(function(e) { window.mParticle.Rokt[e] = function() { var t = Array.prototype.slice.call(arguments); t.unshift("Rokt." + e); window.mParticle.config.rq.push(t); }; }); var t = window.mParticle.config.isDevelopmentMode ? 1 : 0, n = "?env=" + t, a = window.mParticle.config.dataPlan; if (a) { var o = a.planId, r = a.planVersion; o && (r && (r < 1 || r > 1e3) && (r = null), n += "&plan_id=" + o + (r ? "&plan_version=" + r : "")); } var i = window.mParticle.config.versions, s = []; i && Object.keys(i).forEach(function(e) { s.push(e + "=" + i[e]); }); var c = document.createElement("script"); c.type = "text/javascript"; c.async = !0; window.DOMAIN = window.DOMAIN || 'https://apps.rokt-api.com'; c.src = DOMAIN + "/js/v2/" + e + "/app.js" + n + "&" + s.join("&"); var l = document.getElementsByTagName("script")[0]; l.parentNode.insertBefore(c, l); })(API_KEY);
</script>

The initialization script includes the following configuration settings:

isDevelopmentMode

In the example above, isDevelopmentMode is set to true. This allows you to test your SDK integration by collecting "development" data. When you are ready to go live with your integration, set isDevelopmentMode to false to collect and send production data to Rokt.

identifyRequest

The SDK allows you to identify the current user by including their email address (either raw or hashed) at the time the SDK is initalized. Rokt recommends using your customer's raw (unhashed) email address for the identifier.

2. Identify the User

During initialization, the SDK submits an identifyRequest to Rokt using either the user's raw or hashed email address (whichever you can provide) to identify the current user.

If you can't provide the user's email address when the SDK is initialized, you should identify the user as soon as they provide their email address by calling the identify method.

If you are providing an un-hashed email address, use:

const identifyRequest = { 
userIdentities: {
email: 'j.smith@example.com'
}
};
mParticle.Identity.identify(identifyRequest);

If you are providing a hashed email address, use:

const identifyRequest = { 
userIdentities: {
other: 'sha256 hashed email goes here'
}
};
mParticle.Identity.identify(identifyRequest);

3. Set User Attributes

If you have identified the current user, you can set descriptive user attributes that will be automatically included when you log an event.

To set user attributes, run the following after the SDK has initialized and you have identified the user:

// To retrieve the current user, call getCurrentUser. This will only succeed if you have identified the user during SDK initialization or by calling the identify method.
const currentUser = mParticle.Identity.getCurrentUser();

// Once you have successfully set the current user to a const called `currentUser`, you can set user attributes with:
currentUser.setUserAttribute("user-attribute-name", "user-attribute-value");
// Note: all user attributes (including list attributes and tags) must have distinct names.

// Rokt recommends setting as many of the following user attributes as possible:
currentUser.setUserAttribute("firstname", "John");
currentUser.setUserAttribute("lastname", "Doe");
// Phone numbers can be formatted either as '1234567890', or '+1 (234) 567-8901'
currentUser.setUserAttribute("mobile", "3125551515");
currentUser.setUserAttribute("age", "33");
currentUser.setUserAttribute("gender", "M");
currentUser.setUserAttribute("city", "Brooklyn");
currentUser.setUserAttribute("state", "NY");
currentUser.setUserAttribute("zip", "123456");
currentUser.setUserAttribute("dob", "yyyymmdd");
currentUser.setUserAttribute("title", "Mr");
currentUser.setUserAttribute("language", "en");
currentUser.setUserAttribute("value", "52.25");
currentUser.setUserAttribute("predictedltv", "136.23");

// To set a list attribute, set the value of the attribute to an array of strings. For example:
currentUser.setUserAttribute("favorite-genres", ["documentary", "comedy", "romance", "drama"]);

// To remove a user attribute, call removeUserAttribute and pass in the attribute name. All user attributes share the same key space.
currentUser.removeUserAttribute("attribute-to-remove");

4. Track Page Views

Advertisers should track views for each page through the conversion funnel by calling the logPageView method as soon as possible when each page is loaded.

mParticle.logPageView(
// Page name
"page view",
// An object containing attributes describing the page
{
"url": window.location.toString(),
"product": "Example Product Name",
// Add any other page specific attributes as key/value pairs
"custom-attribute-name": "custom-attribute-value"
}
);

The web SDK’s logPageView method takes two arguments:

  • Page Name: a string for the name of the page being loaded
  • Custom Attributes: an object of key/value pairs containing information about the page

The page name field should be set to a generic page name. For example, an ecommerce website could have hundreds of product detail pages. To log these correctly, you should use a generic name (e.g. "Product Detail Page") and then log the url and other attributes of the page as attributes.

5. Track Conversions

To track a conversion, run the following code snippet on the most appropriate page that's loaded after a customer converts, such as a purchase confirmation or "thank you" page.

When pasting the code snippet into your site, make sure to:

  1. Replace the sample user attributes in the .setUserAttribute calls the actual values for your user or customer. Rokt recommends setting at least the following user attributes:
    • firstname
    • lastname
    • zipcode
    • mobile
  2. Replace the sample conversion event attributes with with actual values from your conversion event.

When logging a conversion event, you should include as many user attributes and event attributes as possible to improve Rokt's ability to optimize your campaigns.

remarque

When you initialize the Rokt SDK, it automatically captures the Rokt Click ID and Time on Site. These are included when you log a conversion event.

// Set user attributes before logging the conversion event
currentUser.setUserAttribute("firstname", "John");
currentUser.setUserAttribute("lastname", "Doe");
currentUser.setUserAttribute("zipcode", "98103");
currentUser.setUserAttribute("mobile", "3125551515");

// Log the conversion event
mParticle.logEvent(
"conversion", // The name of the event
mParticle.EventType.Transaction, // The event type
{
"conversiontype": "signup", // Type of conversion
"confirmationref": "54321", // Transaction ID / Order ID
"amount": "", // Transaction amount e.g. 300.5
"currency": "", // Transaction currency e.g. USD

// You can track your own custom event attributes!
"CUSTOM_EVENT_ATTRIBUTE_NAME" : "CUSTOM_EVENT_ATTRIBUTE_VALUE"
}
);

6. Test Your Integration

Rokt recommends testing your new integration to ensure the SDK initializes correctly, and that events are logged successfully.

  1. Open a new browser window.
  2. Open your browser's developer tools panel. For most browsers, you can do this by right-clicking on your screen and clicking Inspect.
  3. From the developer tools panel, go to the Network tab and type experiences into the filter bar.
  4. Navigate to the site and page where you integrated the SDK.
    • Note: Make sure you open the developer tools panel before navigating to your site to ensure the /experiences call is recorded by the browser.
  5. In the Network tab of the developer tools panel, you should see at least one /experiences request. This indicates that the Web SDK loaded successfully.
  6. Click the /experiences request (it should have a status of 200). Check the Payload/Request tab to verify the data being shared with Rokt.
    • Note: During testing, you might see another /experiences call with a 204 status. Make sure you are performing the check on the call with a 200 status.

Troubleshooting

The Rokt Web SDK provides contextual error reporting. If you are having trouble validating your integration, the best way to debug the issue is by using the Console tab in your browser's developer tools panel.

While you may be encountering errors unrelated to the Rokt SDK, some common Rokt SDK errors to check for are:

Syntax errors

Make sure you are not missing any commas in your integration code.

To check for syntax errors:

  1. Go to your browser's developer tools panel and select the Console tab.

  2. If the file where you placed the Web SDK has an error, it should be logged in the console. Click the file to see the code and reported error.

    Web SDK integration testing

  3. Any error is indicated in the file. In particular, check that all attributes are separated by commas as shown below.

Incorrect:

email: ''
emailsha256: '',

Correct:

email: '',
emailsha256: '',
Initialization errors
  • Make sure the SDK initialization script has been placed on the correct page.
  • If you integrated using a tag manager, make sure you configured your tag triggers so that initialization loads on the right pages, and that your selectPlacements and conversion logging tags are firing after the SDK has initialized.

Appendix

After implementing placements and page view tracking by following the instructions above, you may want to implement additional event tracking.

Track Custom Events

You can define and track custom events by calling logEvent and passing in the event name, the event type, and a JSON object containing a list of any custom attributes for the event.

The supported custom event types are:

  • Navigation
  • Location
  • Search
  • Transaction
  • UserContent
  • UserPreference
  • Social
  • Other

The event type is optional; if you omit event type, the event is simply categorized as unknown.

mParticle.logEvent(
// The event name
'event-name',
// The event type
mParticle.EventType.Other,
// Include custom event attributes to further describe the event
{
'custom-attribute-name': 'custom-attribute-value'
}
);

In addition to tracking custom events and conversion events, following are some examples of commerce events you may want to track. Speak with your account manager for help identifying the best events to track, and how to implement them in your site:

  • purchase - when a user makes a purchase or transaction.
  • sign_up - when a user signs up or registers for an event or service.
  • first_time_deposit - when a user provides a deposit.
  • subscription_started - when a user starts a subscription.
  • app_install - when a user installs an app.
  • add_payment_info- when a user adds payment details.
  • add_to_cart - when a user adds an item to their cart.
  • add_to_wishlist - when a user adds an item to their wishlist.
Cet article vous a-t-il été utile ?