Web SDK+ Integration Guide
This page explains how to implement the Rokt Ecommerce Web SDK+. The SDK+ passes user and transaction data to Rokt on configured pages so Rokt can render relevant experiences, such as offers on confirmation pages.
Work with your Rokt account manager to first implement the SDK+ in a development environment so you can thoroughly test before going live.
First-Party Domain ConfigurationDirect link to First-Party Domain Configuration
Using a first-party domain when integrating the SDK+ into your site 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+Direct link to 1. Initialize the Rokt SDK+
Include the SDK+ initialization script on every page of your site. Browser caching means the SDK+ loads from cache on subsequent pages rather than re-fetching.
- Single-page app (SPA)
- Multi-page app (MPA)
Insert the script into the head of your main index.html, or wherever your content is rendered.
Place the script in your primary shared layout file. If you don't use a template-based rendering system, add it to each HTML file.
SDK+ Initialization ScriptDirect link to SDK+ Initialization Script
<script type="text/javascript">
// Enter your Rokt API key
const API_KEY = "YOUR_API_KEY";
// Enter your custom subdomain if you are using a first-party domain configuration (optional)
const ROKT_DOMAIN = "https://apps.rokt-api.com";
window.mParticle = {
config: {
// Set the data environment:
// 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 do not have the user's email address, you can pass in a null value
identifyRequest: {
userIdentities: {
// If you're using an un-hashed email address, set it in 'email' (preferred).
email: 'j.smith@example.com',
// If you're using a hashed email address, set it in 'email_sha256' instead of 'email'.
email_sha256: 'sha256 hashed email goes here',
// Customer phone number in E.164 format.
mobile_number: '+13125551515',
// If you're using a hashed mobile number, set it in 'mobile_sha256' instead of 'mobile_number'.
mobile_sha256: 'sha256 hashed mobile goes here',
// Partner's internal customer/account identifier (if the user is logged in).
customerid: 'cust_10482'
}
},
// If the user is identified with their email address, set additional user attributes.
identityCallback: function(result) {
if (result.getUser()) {
result.getUser().setUserAttribute('attribute_key', 'attribute_value');
}
}
}
};
// 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.8; 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","hashSha256","setExtensionData","use","getVersion","terminate","onShoppableAdsReady"].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.ROKT_DOMAIN = ROKT_DOMAIN || 'https://apps.rokt-api.com'; mParticle.config.domain = ROKT_DOMAIN.split('//')[1]; c.src = ROKT_DOMAIN + "/js/v2/" + e + "/app.js" + n + "&" + s.join("&"); c.onerror = function() { var u = ["https://apps.","rokt","ecommerce",".com"].join(""); window.ROKT_DOMAIN = u; mParticle.config.domain = u.split("//")[1]; var d = document.createElement("script"); d.type = "text/javascript"; d.async = !0; d.src = u + "/js/v2/" + e + "/app.js" + n + "&" + s.join("&"); var f = document.getElementsByTagName("script")[0]; f.parentNode.insertBefore(d, f); }; var l = document.getElementsByTagName("script")[0]; l.parentNode.insertBefore(c, l); })(API_KEY);
</script>
When inserting the initialization script into your site, you will see customizable fields for:
-
Entering your Rokt API key.
Set
API_KEYto the Rokt API key provided by your Rokt account manager. -
Entering a custom first-party domain.
Follow the instructions in First-Party Domain Configuration, and set
ROKT_DOMAINto your custom subdomain. Routing the Rokt SDK+ through your own domain reduces the risk of ad blockers and browsers from blocking ads or data. -
Setting your data environment.
Set
isDevelopmentModetotruewhile testing to route data to the Development environment, andfalseto send live customer activity to Production. -
Identifying your user and setting attributes.
In
identifyRequest, pass the user's raw, un-hashed email in theemailfield. Includemobile_numberandcustomeridwhen available — more signals improve identity resolution. Once identified, use theidentityCallbackto set additional user attributes. For a list of recommended attributes, see User attributes.identityCallback// The identityCallback determines if the identifyRequest was successful.
identityCallback: function(result) {
if (result.getUser()) {
// If the user was identified, set additional user attributes with setUserAttribute.
result.getUser().setUserAttribute('attribute_key', 'attribute_value');
}
}noteAlways include
identifyRequestin the initialization script. If you don't have the user's email at initialization, setemailtonull— the SDK+ will still initialize, and you can identify the user later via 2. Identify the User.
2. Identify the UserDirect link to 2. Identify the User
Call mParticle.Identity.identify with a fresh identifyRequest any time the user provides their email address after the SDK+ has initialized (for example, when they log in, create an account, or make a purchase). This ensures that event data is attributed to the correct user.
Supported User IdentifiersDirect link to Supported User Identifiers
Show supported user identifiers
| Field | Type | Description |
|---|---|---|
email | string | Raw, unhashed email address. |
email_sha256 | string | SHA-256 hashed email. Use instead of email when only the hashed form is available. |
mobile_sha256 | string | SHA-256 hashed mobile number. Use instead of mobile_number when only the hashed form is available. |
mobile_number | string | Phone number in E.164 format (e.g. +13125551515). |
customerid | string | Internal customer/account identifier. Send on every page for logged-in users. |
To identify the user:
-
Create an
identifyRequestobject to contain the user’s identifiers. You should integrate user's raw, unhashed email address into theemailfield. -
To set additional user attributes, create an
identityCallback. If theidentifyRequestsucceeds, then any user attributes you set inside the callback are assigned to the identified user. -
After creating the
identifyRequestand theidentityCallback, send them to Rokt using themParticle.Identity.identifymethodFor example, to identify a user named Jane Smith with the email address
j.smith@example.com, mobile number+13125551515, and customer IDcust_10482, you would use:Identify Jane Smith// 1. Create the identifyRequest object
const identifyRequest = {
userIdentities: {
email: 'j.smith@example.com',
// If you are passing a hashed email address, set it inside the 'email_sha256' field instead of 'email'.
email_sha256: 'SHA-256 hashed email address',
mobile_number: '+13125551515',
// If you are passing a hashed mobile number, set it inside the 'mobile_sha256' field instead of 'mobile_number'.
mobile_sha256: 'SHA-256 hashed mobile number',
customerid: 'cust_10482'
}
};
// 2. User attributes are set using identityCallback
const identityCallback = function(result) {
if (result.getUser()) {
result.getUser().setUserAttribute('firstname', 'Jane');
result.getUser().setUserAttribute('lastname', 'Smith');
}
};
// 3. Call the identify method, including the identifyRequest object and identityCallback
mParticle.Identity.identify(identifyRequest, identityCallback);
3. Set User AttributesDirect link to 3. Set User Attributes
Set user attributes progressively as the user navigates your site, not just at checkout. The more attributes you set, the better Rokt can resolve the customer and deliver relevant offers.
Call setUserAttribute() as soon as information is known about the user, rather than waiting until checkout. Earlier attribute collection gives Rokt more signal to work with for preloading, improving both the speed and relevance of the placement rendered on the confirmation page.
// To retrieve the current user, call getCurrentUser.
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("firstname", "Jane");
currentUser.setUserAttribute("lastname", "Smith");
currentUser.setUserAttribute("mobile_number", "+13125551515");
currentUser.setUserAttribute("birthyear", 1990);
currentUser.setUserAttribute("gender", "F");
// Address attributes (collect the billing address at checkout)
currentUser.setUserAttribute("billingaddress1", "123 Main St");
currentUser.setUserAttribute("billingaddress2", "Apt 4B");
currentUser.setUserAttribute("billingcity", "Brooklyn");
currentUser.setUserAttribute("billingstate", "NY");
currentUser.setUserAttribute("billingzipcode", "11201");
currentUser.setUserAttribute("country", "US");
// Lifecycle and loyalty attributes
currentUser.setUserAttribute("customertype", "logged_in");
currentUser.setUserAttribute("newcustomer", false);
currentUser.setUserAttribute("loyaltytier", "gold");
currentUser.setUserAttribute("loyaltyid", "LOY-7781");
currentUser.setUserAttribute("customersegment", "vip");
// Marketing attribution
currentUser.setUserAttribute("utmsource", "google");
currentUser.setUserAttribute("utmmedium", "cpc");
currentUser.setUserAttribute("utmcampaign", "spring_sale");
// 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");
User AttributesDirect link to User Attributes
Set as many of the following as you can collect:
Show all user attributes
| Field | Type | Description |
|---|---|---|
firstname | string | Customer's first name. Used for personalization. |
lastname | string | Customer's last name. Used for personalization. |
mobile_number | string | Phone number formatted as 1112345678 or +1 (222) 345-6789. Used for identity resolution and relevance. |
birthyear | integer | Customer's birth year (e.g. 1990). Preferred date-of-birth field. Alternates: dob (yyyymmdd), age. Used for eligibility and relevance. |
dob | string | Date of birth, yyyymmdd. Alternate to birthyear. Used for eligibility and relevance. |
age | integer | Customer's age. Alternate to birthyear. Used for eligibility and relevance. |
gender | string | Customer's gender. For example, M, F, Male, or Female. Used for relevance. |
title | string | Honorific. For example, Mr, Mrs, Ms. Used for personalization. |
language | string | ISO 639-1 language code associated with the purchase. Used for relevance. |
billingaddress1 | string | Street address (e.g. 123 Main St). Used for identity resolution and relevance. |
billingaddress2 | string | Apartment/unit (e.g. Apt 4B). Used for identity resolution. |
billingcity | string | Billing city. Used for relevance. |
billingstate | string | Billing state / province / region. Used for relevance and eligibility. |
billingzipcode | string | Full ZIP or postcode (US preference is ZIP+4). Used for identity resolution and relevance. |
country | string | ISO 3166-1 alpha-2 country code (e.g. US, GB, AU). Used for eligibility and relevance. |
newcustomer | boolean | Whether this is a first-time buyer (true / false). Used for relevance. |
customertype | string | Whether the user is authenticated (guest / logged_in). Used for relevance. |
loyaltytier | string | Partner loyalty program tier. Used for relevance and eligibility. |
loyaltyid | string | Loyalty program member ID. Used for identity resolution. |
predictedltv | decimal | Predicted total lifetime value, typically produced by a partner machine-learning model. Used for relevance. |
subscriptionstatus | string | Subscription state if applicable (active, trial, churned, paused, none). Used for relevance and eligibility. |
customersegment | string | Partner internal segmentation (e.g. vip, at_risk, new, reactivated). Used for relevance. |
acquisitionchannel | string | How the customer was originally acquired. Used for relevance. |
utmsource | string | Marketing attribution source. Used for relevance. |
utmmedium | string | Marketing attribution medium. Used for relevance. |
utmcampaign | string | Marketing attribution campaign. Used for relevance. |
utmcontent | string | Marketing attribution content variant. Used for relevance. |
utmterm | string | Marketing attribution term / keyword. Used for relevance. |
referrer | string | Referring URL — intent signal. Used for relevance. |
All user attributes (including list attributes and tags) must have distinct names.
4. Track Funnel EventsDirect link to 4. Track Funnel Events
Track page views, account lifecycle events, commerce events, and custom events so Rokt can maintain identity continuity and understand where each customer is in their journey.
Page ViewsDirect link to Page Views
Call logPageView() after the SDK+ has initialized to log page navigation.
Page view event attributesDirect link to Page view event attributes
Show page view event attributes
| Field | Type | Description |
|---|---|---|
screenname | string | Last segment of the URL path (e.g. /products/shoes → shoes). Defaults to home if the path is empty. |
pagetype | string | Type of page being viewed: home, PLP, PDP, cart, checkout, confirmation. |
url | string | Full URL of the current page. |
title | string | Page title (from document.title). |
sitesection | string | Top-level site section (e.g. mens, womens, support). |
referringpage | string | Referring URL captured from document.referrer. |
Example page view eventDirect link to Example page view event
// Wait for the SDK+ to be fully loaded before logging the event
window.mParticle.ready(function() {
mParticle.logPageView(
// Event name: "page view" identifies the type of event being logged
"page view",
{
// Capture the last segment of the URL path as the screen name,
// e.g., "/products/shoes" → "shoes". Defaults to "home" if the path is empty.
"screenname": location.pathname.split("/").filter(Boolean).pop() || "home",
// Type of page being viewed. Examples: home, PLP, PDP, cart, checkout, confirmation.
"pagetype": "PDP",
// Record the full URL of the current page (including protocol, path, query, and hash)
"url": window.location.toString(),
// Page title (from document.title)
"title": document.title,
// Top-level site section (e.g. "mens", "womens", "support")
"sitesection": "mens",
// Capture the URL of the page that referred the user to this one,
// if available. This helps track user navigation between pages or sites.
"referringpage": document.referrer
}
);
});
Account Lifecycle EventsDirect link to Account Lifecycle Events
Log account lifecycle events when the user signs up, logs in, or logs out so Rokt can maintain identity continuity across sessions and devices. Signup and login lifecycle events accept an attribute called method you can use to specify the method with which the user either signed up or logged in.
Supported lifecycle event typesDirect link to Supported lifecycle event types
Show lifecycle event types
| Lifecycle Event Type | When to trigger | Supported method values |
|---|---|---|
sign_up | New account created | email, social, guest |
login | User logs in | email, social, sso |
logout | User logs out | Not applicable. |
Example lifecycle eventsDirect link to Example lifecycle events
// Signup event
mParticle.logEvent("sign_up", mParticle.EventType.Other, { method: "email" });
// Login event
mParticle.logEvent("login", mParticle.EventType.Other, { method: "email" });
// Logout event
mParticle.logEvent("logout", mParticle.EventType.Other);
Commerce EventsDirect link to Commerce Events
Commerce events carry product-level details for the user's journey. Trigger a separate commerce event for each product action the customer takes.
Investing in full commerce event coverage is one of the highest-leverage things you can do during your integration. Each event tells Rokt something different about where the customer is in their journey: a product view signals exploration, an add-to-cart signals consideration, a checkout start signals purchase intent, and a completed purchase confirms conversion. With a richer signal, Rokt can personalize offers more effectively, measure placement performance accurately, and attribute conversions to the right touchpoints. Doing this work during your initial integration also avoids a retrofit later. The signal compounds over time: each event Rokt receives adds context used to sharpen personalization, improve attribution accuracy, and better resolve and segment your customer base on future visits.
Three event types (product listing page, or PLP, impressions; cart page views; and site searches) are logged using dedicated methods and are covered in the sub-sections below. All other commerce events use the logProductAction method — see Standard commerce events.
Product listing page (PLP) or category page viewDirect link to Product listing page (PLP) or category page view
PLP and category page views do not use logProductAction. Instead, log each visible product as a product impression using mParticle.eCommerce.logImpression. Pass all products visible on the page in a single call, and set the Name field of the impression object to the name of the list or category the customer is viewing (for example, "Mens Running Shoes" or "Search Results"). Rokt uses this value as list_name to understand which collection the customer was browsing before they viewed or added a product.
// Create a product per visible item; set Position to its 1-indexed rank in the list.
var product = mParticle.eCommerce.createProduct('Product A', 'SKU-001', 29.99, null, null, 'Shoes', 'BrandX', 1);
mParticle.eCommerce.logImpression(
{ Name: 'Mens Running Shoes', Products: [product] }, // Name becomes list_name
{ currency: 'USD' }
);
Cart page viewDirect link to Cart page view
Cart page views do not have a native ProductActionType. To log a cart page view, call mParticle.logEvent with the event name set to "view_cart" and the event type set to mParticle.EventType.Other. Pass the full contents of the cart as event attributes, including the cartitems array as a real JSON array — do not stringify it.
mParticle.logEvent(
"view_cart",
mParticle.EventType.Other,
{
cartitemcount: 2,
totalprice: 149.99,
currency: "USD",
couponcode: "SUMMER20",
cartitems: [
{ cartitemid: "SKU-001", productsku: "SKU-001", productname: "Product A", itemprice: 99.99, quantity: 1 }
]
}
);
Site searchDirect link to Site search
Site searches do not have a native ProductActionType. To log a search, call mParticle.logEvent with the event name set to "search" and the event type set to mParticle.EventType.Search. At minimum, include the searchstring the customer entered and the number of results returned.
mParticle.logEvent(
"search",
mParticle.EventType.Search,
{ searchstring: "blue running shoes", resultcount: 24 }
);
Standard commerce eventsDirect link to Standard commerce events
Standard commerce events are logged with logProductAction, using a ProductActionType that identifies the customer action (viewing a product, adding to cart, starting checkout, completing a purchase, etc.). The sections below list the supported action types, describe the cartitems array shape, and walk through assembling the event.
Commerce-event attributes use flatcase (e.g. cartitems, productsku, itemprice). The createProduct method and transactionAttributes object use PascalCase (e.g. Name, SKU, Id). Both conventions appear in the sub-sections below.
Product action typesDirect link to Product action types
Show all product action types
| Customer action | Product action type | Product-level fields | Transaction-level fields |
|---|---|---|---|
| Product detail page viewed | ViewDetail | sku, name, price | currency, list_name (if arrived from a PLP) |
| Item added to cart | AddToCart | sku, quantity, price | currency, couponCode |
| Item removed from cart | RemoveFromCart | sku, quantity | currency |
| Checkout flow initiated | Checkout | Full cartitems array | totalprice, cartitemcount, currency, couponCode |
| Shipping step completed | CheckoutOption with option = "shipping" | Full cartitems array | shippingmethod, zipcode, country, totalprice, currency |
| Payment step completed | CheckoutOption with option = "payment" | Full cartitems array | paymenttype, payment_method, paymentServiceProvider, ccbin, totalprice, currency |
| Order confirmed | Purchase | Full cartitems array | transactionId, totalprice, tax, shipping, couponCode, currency, cartitemcount |
| Order refunded | Refund | sku, quantity for the refunded line(s) | transactionId, totalprice, currency |
Order-level coupons belong on transactionAttributes.Coupon. When a single order has multiple SKUs with different promos, attach per-line coupons to the product object as a custom attribute named couponcode.
Cart itemsDirect link to Cart items
cartitems is a JSON array of cart-line objects, one per line in the cart. The same structure is used by createProduct / ProductAction.products[], by commerce events that carry cart contents (view_cart, Checkout, Purchase), and by the selectPlacements cartItems attribute — the field list below applies in all of these contexts.
Show all cart item fields
| Field | Type | Description |
|---|---|---|
cartitemid | string | Stable partner-side cart-line identifier. Usually equals productsku when there is one line per SKU; use a unique value if you allow multiple lines for the same SKU (e.g. gift-wrap variants). |
productsku | string | Product SKU / stock identifier. |
productname | string | Product display name. |
productcategory | string | Product category / taxonomy leaf. |
productbrand | string | Product brand. |
productvariant | string | Variant identifier (size, color, etc.). |
itemprice | decimal | Per-unit price at event time. |
unitprice | decimal | Per-unit list price pre-discount. Omit if equal to itemprice. |
quantity | integer | Units in this line. |
currency | string | ISO 4217 code. Omit if matches the top-level currency. |
couponcode | string | Coupon applied to this line (if any). Order-level promos belong in transactionAttributes.Coupon. |
productposition | integer | 1-indexed rank of the product within a list or search results. |
Do not send cart items as comma-separated strings or as a stringified JSON blob. Send a real JSON array so the fields stay typed.
Example cart itemsDirect link to Example cart items
[
{
"cartitemid": "SKU-001",
"productsku": "SKU-001",
"productname": "Product A",
"productcategory": "Electronics",
"productbrand": "BrandX",
"itemprice": 99.99,
"quantity": 1
},
{
"cartitemid": "SKU-002",
"productsku": "SKU-002",
"productname": "Product B",
"productcategory": "Accessories",
"itemprice": 24.99,
"quantity": 2
}
]
1. Define the productDirect link to 1. Define the product
Call mParticle.eCommerce.createProduct with the attributes below, plus an optional trailing object of custom key/value attributes. Pass attributes in the order shown; use null for any value you don't have.
Show product attributes
| Field | Type | Description |
|---|---|---|
Name | string | The name of the product being purchased. |
SKU | string | The stock keeping unit for the product. |
Price | decimal | The price of the product. |
Quantity | integer | The number of units. |
Variant | string | The specific product version, if you offer variants. For example: size or color. |
Category | string | The category that the product belongs to. |
Brand | string | The brand name for the product. |
Position | integer | 1-indexed rank of the product in a list or search results page. Set this when logging PLP impressions so Rokt can use it as position context. |
Coupon code | string | The coupon code for the product. |
Example product definitionDirect link to Example product definition
var product1 = mParticle.eCommerce.createProduct(
'Double Room - Econ Rate', // Name
'econ-1', // SKU
100.00, // Price
4, // Quantity
'variant', // Variant
'room', // Category
'lodge-o-rama', // Brand
'banner', // Position
null, // Coupon code
// Add any optional custom attributes in an object of key/value pairs
{
'ocean-view': true,
'balcony': false
}
);
Alternatively, you can call createProduct with just the first three positional arguments (Name, SKU, Price) and set the remaining fields afterward by assigning to properties on the returned object — for example, product.Category = 'Shoes'. See the multi-product example below.
2. Summarize the transactionDirect link to 2. Summarize the transaction
Create a transactionAttributes object for Purchase, Checkout, and CheckoutOption events, and pass null for all other event types. Include Shipping and Coupon when applicable — order-level coupons belong here, not on individual products.
Show transaction attributes
| Field | Type | Description |
|---|---|---|
Id | string | Order / transaction identifier. |
Revenue | decimal | Order-level total price. |
Tax | decimal | Total tax on the order. |
Shipping | decimal | Shipping cost on the order. |
Coupon | string | Order-level coupon code applied. |
Example transaction summaryDirect link to Example transaction summary
var transactionAttributes = {
Id: 'ORDER-12345', // transactionId
Revenue: 149.99, // totalprice (order-level)
Tax: 12.50, // tax
Shipping: 5.99, // shipping
Coupon: 'SUMMER20' // couponCode (order-level promo)
};
3. Log the commerce eventDirect link to 3. Log the commerce event
Call mParticle.eCommerce.logProductAction with a ProductActionType from the table above. Use customAttributes for any event-level custom fields.
Example commerce eventDirect link to Example commerce event
mParticle.eCommerce.logProductAction(
// The type of product action being logged. In this example, the type is "Purchase"
mParticle.ProductActionType.Purchase,
// The array containing the product definitions you already created in Step 1.
[product1],
// Custom attributes describing the commerce event
customAttributes = {
'sale': true
},
// This space is for specifying custom flags for mParticle by Rokt integrations. Rokt Ecommerce customers can ignore this section by entering 'null'.
null,
// The transactionAttributes object you already created in Step 2.
transactionAttributes
);
Multi-product exampleDirect link to Multi-product example
For orders with multiple cart lines, wrap all product definitions in a single array. This example uses the post-create assignment pattern from Step 1 to set fields like Category and Brand, plus product-level custom attributes like unitprice and per-line couponcode.
const product1 = mParticle.eCommerce.createProduct('Product A', 'SKU-001', 99.99, 1);
product1.Category = 'Electronics';
product1.Brand = 'BrandX';
product1.Variant = 'red-L';
product1.Attributes = {
unitprice: 109.99, // list price before any line discount
couponcode: 'LINE10' // per-line promo
};
const product2 = mParticle.eCommerce.createProduct('Product B', 'SKU-002', 24.99, 2);
product2.Category = 'Accessories';
mParticle.eCommerce.logProductAction(
mParticle.ProductActionType.Purchase,
[product1, product2],
{ channel: 'web' }, // event-level custom attributes
null, // custom flags (Rokt Ecommerce can use null)
{
Id: 'ORDER-12345',
Revenue: 149.97,
Tax: 12.50,
Shipping: 5.99,
Coupon: 'SUMMER20'
}
);
The same structure applies to every ProductActionType — swap Purchase for the action that matches the customer behavior you're logging. See the Product action types table for the full list.
Custom EventsDirect link to Custom Events
Track custom events with logEvent, passing an event name, event type, and attributes object.
Custom event attributesDirect link to Custom event attributes
Show custom event attributes
| Field | Type | Description |
|---|---|---|
event_name | string | A name identifying the event (e.g. 'search', 'video_play'). |
event_type | EventType | Categorizes the event. Supported values: Navigation, Location, Search, Transaction, UserContent, UserPreference, Social, Other. Defaults to Unknown if omitted. |
attributes | object | Key-value pairs of custom data describing the event. Any string keys and values are supported. |
Example custom eventDirect link to Example custom event
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'
}
);
Ready to CheckoutDirect link to Ready to Checkout
Fire a custom Ready to Checkout event at the point in the checkout flow where the customer has entered their payment details and is about to confirm the order — but before they click Place Order or Buy Now. This helps Rokt optimize the selection process so that offers are displayed as quickly as possible on the following page.
Trigger the event once all of the following conditions are met:
- The cart is finalized (items and quantities confirmed).
- A shipping method has been selected.
- A payment method has been entered or selected.
- The user is on the final review/payment screen, prior to order submission.
Include any final attributes that were not available earlier in the session (for example, payment_method_type, which is typically only known at this stage).
window.mParticle.ready(function() {
mParticle.logEvent(
'Ready to Checkout',
mParticle.EventType.Transaction,
{
'checkout_ready': 'true',
'payment_method_type': 'credit_card',
'shipping_address_verified': 'true',
'shipping_method': 'express',
'cart_item_count': '3',
'cart_total': '430.00',
'currency': 'USD',
},
);
});
5. Show a PlacementDirect link to 5. Show a Placement
Call selectPlacements on every payment and confirmation page you want Rokt to render content on. Include one of the following page identifiers to specify the page type and whether it's for testing or production:
stg.rokt.conf: A confirmation page in a staging (or testing) environment.prod.rokt.conf: A confirmation page in a production environment.stg.rokt.payments: A payments page in a staging (or testing) environment.prod.rokt.payments: A payments page in a production environment.
Placement AttributesDirect link to Placement Attributes
Include all of the following attributes when inserting overlay, embedded, or interstitial placements.
Attributes passed in selectPlacements override any earlier values set via setUserAttribute. Always supply the most recent value.
Show all placement attributes
| Field | Type | Description |
|---|---|---|
email | string | Customer email address (unhashed). Used for identity resolution and Shoppable Ads order confirmation. |
firstname | string | Customer first name. Used for personalization and Shoppable Ads order fulfillment. |
lastname | string | Customer last name. Used for personalization and Shoppable Ads order fulfillment. |
mobile_number | string | Customer mobile number (E.164 format, e.g. +13125551515). Used for identity resolution and Shoppable Ads. |
confirmationref | string | Order / confirmation reference number. Used for relevance, deduplication, and Shoppable Ads order reconciliation. |
currency | string | Transaction currency (ISO 4217, e.g. USD, GBP, AUD, JPY). Used for relevance and Shoppable Ads. |
country | string | ISO 3166-1 alpha-2 country code. Used for eligibility and relevance. |
language | string | Customer's preferred language (ISO 639-1, e.g. en, de, fr). Used for relevance. |
totalprice | decimal | Total cart value including tax and shipping. Used for relevance. |
amount | decimal | Cart subtotal before tax and shipping. Distinct from totalprice. Required for Pay+ on the payments page; also used by Shoppable Ads. |
cartItems | array | Structured array of cart-line objects. See Cart items. Used for relevance. |
couponcode | string | Promo code applied, if any. Used for relevance. |
newcustomer | boolean | Whether this is a first-time buyer. Used for relevance. |
customertype | string | Whether the user is authenticated (guest / logged_in). Used for relevance. |
value | decimal | Customer cumulative purchase value. Used for relevance. |
subscriptionstatus | string | Subscription state if applicable (active, trial, churned, paused, none). Used for relevance and eligibility. |
customersegment | string | Partner internal segmentation (vip, at_risk, new, reactivated). Used for relevance. |
paymenttype | string | Payment method selected (credit_card, paypal, apple_pay, gift_card). Used for Pay+ eligibility and Shoppable Ads payment method prioritization. |
paymentServiceProvider | string | Comma-separated list of payment methods accepted on the page (e.g. "cardpayment,paypal"). Accepted values: applepay, googlepay, paypal, venmo, affirm, afterpay, klarna, alipay, amazonpay, cardpayment, rakutenpay. Must be camelCase. Used for Pay+ eligibility. |
ccbin | string | Credit card BIN (first 6 digits). Used for relevance. |
billingaddress1 | string | Billing street address. Used for identity resolution and relevance. |
billingaddress2 | string | Billing apartment/unit. Used for identity resolution. |
billingcity | string | Billing city. Used for relevance. |
billingstate | string | Billing state / region. Used for relevance. |
billingzipcode | string | Billing ZIP / postcode. Used for identity resolution, relevance, and Shoppable Ads. |
shippingmethod | string | Shipping method selected (standard, express, next_day). Used for relevance. |
shippingname | string | Full recipient name on the shipping address. Used for Shoppable Ads order fulfillment. |
shippingaddress1 | string | Shipping street address. Used for relevance and Shoppable Ads order fulfillment. |
shippingcity | string | Shipping city. Used for relevance and Shoppable Ads order fulfillment. |
shippingstate | string | Shipping state / region. Used for relevance and Shoppable Ads order fulfillment. |
shippingzipcode | string | Shipping ZIP / postcode. Used for relevance and Shoppable Ads order fulfillment. |
shippingcountry | string | Shipping country (ISO 3166-1 alpha-2). Used for relevance and Shoppable Ads order fulfillment. |
billingname | string | Full cardholder name on the billing address. Used for identity resolution and payment validation. |
partnerpaymentreference | string | Non-guessable identifier used to look up the customer's vaulted payment method. Required for Shoppable Ads card forwarding; if absent, card forwarding is unavailable. |
last4digits | string | Last 4 digits of the card used on the primary transaction. Displayed to the customer for confirmation during Shoppable Ads. |
plcc | string | "yes" or "no" — whether the customer has a private-label credit card with the partner. Used for Pay+ relevance. |
discountamount | decimal | Order-level discount applied (e.g. 10.00). Used for Pay+ relevance. |
prescreen | string | "yes" or "no" — whether the customer has pre-qualified for a credit offer. Used for Pay+ relevance. |
adsExperience | string | Pass "shoppable" when targeting a Shoppable Ads experience. Must be camelCase. |
Do not send cart items as comma-separated strings or as a stringified JSON blob. Send a real JSON array so the fields stay typed. For the full cart-item field reference, see Cart items under Commerce Events.
Overlay PlacementsDirect link to Overlay Placements
Overlay placements render on top of your confirmation page in a Rokt-managed container, requiring no changes to your page's DOM. Overlay placements can be used for standard Thanks Ads and Shoppable Ads.
To insert an overlay placement, call selectPlacements once the confirmation page loads:
window.mParticle.ready(async function () {
const selection = await window.mParticle.Rokt.selectPlacements({
identifier: "yourPageIdentifier",
attributes: {
// Identity
"email": "j.smith@example.com", // Customer email address used at checkout
"firstname": "Jenny", // Customer first name
"lastname": "Smith", // Customer last name
"mobile_number": "+13125551515", // Customer mobile / cell number
// Transaction
"confirmationref": "54321", // Order / confirmation reference number
"currency": "USD", // Transaction currency, ISO 4217
"country": "US", // ISO 3166-1 alpha-2 country code
"language": "en", // ISO 639-1 2-letter language code
"totalprice": 149.99, // Current cart total
"couponcode": "SUMMER20", // Promo code applied, if any
// Customer context
"newcustomer": false, // Whether this is a first-time buyer
"customertype": "logged_in", // guest / logged_in
"value": 2340.00, // Historical cumulative purchase value
"subscriptionstatus": "active", // active, trial, churned, paused, none
"customersegment": "vip", // Partner internal segmentation
// Payment (include paymenttype and paymentServiceProvider for Pay+)
"paymenttype": "credit_card", // credit_card, paypal, apple_pay, gift_card
"paymentServiceProvider": "cardpayment", // cardpayment, paypal, applepay, etc.
"ccbin": "411112", // First 6 digits of credit card
// Billing address
"billingaddress1": "123 Main St",
"billingaddress2": "Apt 4B",
"billingcity": "Brooklyn",
"billingstate": "NY",
"billingzipcode": "11201",
// Shipping
"shippingmethod": "express", // standard, express, next_day
"shippingaddress1": "175 Varick St",
"shippingcity": "New York",
"shippingstate": "NY",
"shippingzipcode": "10014",
"shippingcountry": "US",
// Cart contents — send a real JSON array, not a stringified blob.
// See the Cart items reference under Commerce Events for the full field list.
"cartItems": [
{
"cartitemid": "SKU-001",
"productsku": "SKU-001",
"productname": "Product A",
"productcategory": "Electronics",
"productbrand": "BrandX",
"itemprice": 99.99,
"quantity": 1
},
{
"cartitemid": "SKU-002",
"productsku": "SKU-002",
"productname": "Product B",
"productcategory": "Accessories",
"itemprice": 24.99,
"quantity": 2
}
]
}
});
});
Embedded PlacementsDirect link to Embedded Placements
Embedded placements render inline at a fixed position in your page that you control (for example, above the payment options on a cart page). Both Thanks and Pay+ use embedded placements, but Pay+ must use embedded placements.
To insert an embedded placement, add a <div> with the container ID provided by your Rokt account manager at the position where you want the placement to render:
<div id="rokt-{container-name}"></div>
Next, call selectPlacements with the corresponding page identifier:
window.mParticle.ready(async function () {
const selection = await window.mParticle.Rokt.selectPlacements({
identifier: "prod.rokt.{page}", // Page identifier provided by your Rokt account manager
attributes: {
// Pass the same attribute set described in Placement Attributes above
}
});
// For SPA navigations, close the placement when the customer leaves the page.
if (selection) {
selection.close();
}
});
Coordinate with your Rokt account manager to choose the container name and page identifier.
If you are using Pay+, you must close your placement after the user navigates away to prevent it from lingering on back-navigation.
Pay+ requires that your existing confirmation-page selectPlacements call already passes paymenttype along with the rest of the attributes listed in Placement Attributes. Without paymenttype on the confirmation page, Rokt cannot attribute share-of-wallet correctly. Validate your confirmation-page integration with your Rokt account manager before enabling Pay+ in production.
Interstitial PlacementsDirect link to Interstitial Placements
Interstitial placements are rendered between the payment and confirmation pages, allowing customers to purchase additional products. Interstitial placements are used by Shoppable Ads.
Interstitial placements require two pieces on the confirmation page: the <rokt-thank-you> wrapper that defines what to swap out, and a selectPlacements call that requests the offer.
First, wrap your confirmation page content within the <rokt-thank-you> tag. Rokt strips the wrapped content when an offer is available and renders the full-screen experience in its place. If no offer is eligible, the wrapped content renders normally.
<body>
<!-- Your header -->
<rokt-thank-you id="rokt-thank-you">
<!-- Your confirmation page content -->
</rokt-thank-you>
<!-- Your footer -->
</body>
Then call selectPlacements with the confirmation-page identifier so Rokt can evaluate eligibility and render the offer:
window.mParticle.ready(async function () {
await window.mParticle.Rokt.selectPlacements({
identifier: "prod.rokt.conf", // use stg.rokt.conf in test environments
attributes: {
// Pass the same attribute set described in Placement Attributes above
}
});
});
The <rokt-thank-you> wrapper also emits lifecycle events you can subscribe to for custom behavior. See Subscribe to Interstitial Lifecycle Events.
If your site embeds Rokt inside a cross-origin iframe, add allow="payment" to the iframe element so payment APIs work inside the Interstitial experience.
<rokt-thank-you> attributesDirect link to rokt-thank-you-attributes
The <rokt-thank-you> element accepts the following optional attributes to customize loading behavior.
Show <rokt-thank-you> attributes
| Attribute | Description | Default |
|---|---|---|
loader | Optional URL to a loading-indicator GIF displayed while Rokt selects a placement for the confirmation page. Supply your own asset to override the default. | Rokt loading indicator |
fallback-timeout | Duration in milliseconds before placement selection times out and the native confirmation page renders. | 5000 |
partner-opt-in | Force-enable the Interstitial experience. Usage: <rokt-thank-you partner-opt-in>. | — |
partner-opt-out | Force-skip the Interstitial experience. Usage: <rokt-thank-you partner-opt-out>. | — |
6. Subscribe to Placement EventsDirect link to 6. Subscribe to Placement Events
The SDK+ emits events throughout the placement lifecycle. Subscribe to these events to run custom logic when a placement is ready, when a customer engages with a placement, or when an interstitial placement wrapper transitions between states.
Subscribe to Placement Lifecycle EventsDirect link to Subscribe to Placement Lifecycle Events
By subscribing to a placement event you can receive notifications that are triggered when a placement is ready or when a customer engages with an offer.
window.mParticle.ready(async function () {
const selection = await window.mParticle.Rokt.selectPlacements({
// add attributes
});
// Listen for when the placement becomes interactive/ready to display
selection.on('PLACEMENT_INTERACTIVE').subscribe(() => {
// Logic to run after Placement has become interactive
});
// Listen for when user engages positively or negatively with an offer
selection.on('OFFER_ENGAGEMENT').subscribe(function () {
// Logic to run after offer is engaged with
});
});
Subscribe to Interstitial Lifecycle EventsDirect link to Subscribe to Interstitial Lifecycle Events
The <rokt-thank-you> element used by the interstitial format emits lifecycle events you can subscribe to for custom behavior. Register listeners with window.mParticle.Rokt.onShoppableAdsReady() — this callback fires as soon as the element is ready, so listeners registered before mParticle.ready() are never missed.
Show <rokt-thank-you> lifecycle events
| Event | Emitted when |
|---|---|
THANK_YOU_ELEMENT_LOADING_INITIATED | The <rokt-thank-you> element enters its loading state. |
THANK_YOU_ELEMENT_COMPLETE | The <rokt-thank-you> element renders the partner confirmation content. |
// Register listeners before mParticle.ready() so events are never missed.
window.mParticle.Rokt.onShoppableAdsReady(() => {
window.RoktThankYouElement.on('THANK_YOU_ELEMENT_LOADING_INITIATED').subscribe(() => {
// Triggered when the Thank You element enters its loading state
});
window.RoktThankYouElement.on('THANK_YOU_ELEMENT_COMPLETE').subscribe(() => {
// Triggered when the Thank You element renders the partner confirmation
});
});
window.mParticle.ready(() => {
// Standard mParticle initialization continues here
});
7. AppendixDirect link to 7. Appendix
Close a PlacementDirect link to Close a Placement
In single-page apps, call .close() on the placement object after the user navigates away so the placement doesn't linger on back-navigation.
// Closes the placement called 'selection'
selection.close();
If you are using Pay+, you must close your placement after the user navigates away.
Additional Functionality via ExtensionsDirect link to Additional Functionality via Extensions
Some features require extensions. Enable them by calling mParticle.Rokt.use() before selectPlacements(). For example, to display upsell placements on a Thank You page, enable the ThankYouJourney extension first:
window.mParticle.ready(async function() {
// Enable the necessary extension prior to selecting placements
await window.mParticle.Rokt.use("ThankYouJourney");
const selection = await mParticle.Rokt.selectPlacements({
identifier: "yourPageIdentifier",
attributes: {
"email": "j.smith@example.com"
// Any additional user attributes you want to pass to Rokt
},
});
})
Passing Additional Integration Launcher OptionsDirect link to Passing Additional Integration Launcher Options
Configure optional behavior by setting window.mParticle.config.launcherOptions in the initialization script:
// Include this as part of the initialization script in step 1 above
window.mParticle.config.launcherOptions = {
noFunctional: true,
noTargeting: true,
// See all optional launcher options that can be set below
};
Manage customer cookie preferencesDirect link to Manage customer cookie preferences
Use these options to respect customer opt-out preferences by disabling functional or targeting cookies.
| Parameter | Type | Default |
|---|---|---|
noFunctional | boolean | false |
Set to true to prevent Rokt from using first-party tracking IDs when the customer has opted out of functional cookies. Functional cookies power first-party personalization and advanced checkout features like Upsells.
| Parameter | Type | Default |
|---|---|---|
noTargeting | boolean | false |
Set to true to prevent Rokt from using cross-site tracking IDs for the session when the customer has opted out of targeting cookies. Functional identifiers remain active unless noFunctional is also set to true.
For a more detailed discussion, see Cookie Consent Flags.
Measure page load performance in single-page appsDirect link to Measure page load performance in single-page apps
Provide the timestamp of when a virtual page loads so Rokt can accurately measure performance in SPAs and detect anomalies that could impact the customer experience.
| Parameter | Type | Default |
|---|---|---|
pageInitTimestamp | Date | PerformanceNavigationTiming.responseStart |
When the launcher initializes on a virtual page in an SPA, pass the timestamp of when that page was initialized so Rokt can measure load performance relative to the page that triggered it.
Link customer activity with a Rokt session IDDirect link to Link customer activity with a Rokt session ID
Pass a previously generated Rokt session ID to ensure activity across different parts of the experience is tied together correctly.
| Parameter | Type | Default |
|---|---|---|
sessionId | string | — |
If you've generated a Rokt session ID from a prior backend interaction, pass it here so Rokt can pair it with front-end activity.
Customize how links open in your experienceDirect link to Customize how links open in your experience
Enable this option when you want full control over how Rokt and advertiser links open (for example, inside a WebView instead of a browser).
| Parameter | Type | Default |
|---|---|---|
overrideLinkNavigation | boolean | false |
When set to true, Rokt stops handling link openings directly and instead emits a LINK_NAVIGATION_REQUEST partner event. To distinguish Rokt and advertiser links from your own, check whether the URL contains "rokt.com".
If a LINK_NAVIGATION_REQUEST event is not consumed within 3 seconds, an error is raised — make sure an active subscription exists to process the event.
8. Test Your IntegrationDirect link to 8. Test Your Integration
To confirm the SDK+ initializes and events log correctly:
-
Open a new browser window.
-
Open your browser's developer tools panel. For most browsers, you can do this by right-clicking on your screen and clicking Inspect.
-
From the developer tools panel, go to the Network tab and type
experiencesinto the filter bar. -
Navigate to the site and page where you integrated the SDK+.
noteMake sure you open the developer tools panel before navigating to your site to ensure the
/experiencescall is recorded by the browser. -
In the Network tab of the developer tools panel, you should see at least one
/experiencesrequest. This indicates that the Web SDK+ loaded successfully. -
Click the
/experiencesrequest (it should have a status of 200). Check the Payload/Request tab to verify the data being shared with Rokt.noteDuring testing, you might see another
/experiencescall with a 204 status. Make sure you are performing the check on the call with a 200 status.
TroubleshootingDirect link to Troubleshooting
If your integration isn't working, check the Console tab in your browser's developer tools for Rokt SDK+ errors. Common issues include:
Syntax errorsDirect link to Syntax errors
Make sure you are not missing any commas in your integration code.
To check for syntax errors:
-
Go to your browser's developer tools panel and select the Console tab.
-
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.

-
Any error is indicated in the file. In particular, check that all attributes are separated by commas as shown below.
Incorrect:
email: ''
mobile_number: '',
Correct:
email: '',
mobile_number: '',
Initialization errorsDirect link to 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.