メインコンテンツまでスキップ

Cordova Plugin Integration Guide

This page explains how to implement the Rokt Ecommerce Cordova SDK+. The SDK+ passes user and transaction data to Rokt on configured screens so Rokt can render relevant experiences, such as offers on confirmation screens. Your Rokt account manager will provide the key and secret required to initialize the SDK+.

ヒント

Work with your Rokt account manager to first implement the SDK+ in a development environment so you can thoroughly test before going live.

1. Add the Rokt SDK+ to Your Cordova App1. Add the Rokt SDK+ to Your Cordova App への直接リンク

Install the mParticle Cordova SDK+ and the Rokt kit plugin:

cordova plugin add @mparticle/cordova-sdk
cordova plugin add @mparticle/cordova-rokt-kit

2. Initialize the Rokt SDK+2. Initialize the Rokt SDK+ への直接リンク

Insert the following initialization snippet in the relevant native entry point for each platform. The mParticle SDK+ must be initialized before any other SDK+ API calls. Replace your-key and your-secret with the key and secret provided by your Rokt team.

You can find a full example in the example app.

iOSiOS への直接リンク

AppDelegate initialization (iOS)
#import "AppDelegate.h"
#import "MainViewController.h"
#import "mParticle.h"

@implementation AppDelegate

- (BOOL)application:(UIApplication*)application didFinishLaunchingWithOptions:(NSDictionary*)launchOptions
{
MParticleOptions *mParticleOptions = [MParticleOptions optionsWithKey:@"your-key"
secret:@"your-secret"];
// Specify the data environment:
// Set it to MPEnvironmentDevelopment if you are still testing your integration.
// Set it to MPEnvironmentProduction if your integration is ready for production data.
// The default is MPEnvironmentAutoDetect which attempts to detect the environment automatically.
mParticleOptions.environment = MPEnvironmentDevelopment;

// Identify the current user:
// If you do not have the user's email address, you can pass in a null value
MPIdentityApiRequest *request = [MPIdentityApiRequest requestWithEmptyUser];

// Preferred: pass the customer's raw, unhashed email address in 'email'.
// If you can only provide a SHA-256-hashed email, set it in 'other' instead of email — do not pass both.
request.email = @"j.smith@example.com";
// [request setIdentity:@"sha256 hashed email goes here" identityType:MPIdentityOther]; // only if raw email unavailable

mParticleOptions.identifyRequest = request;
mParticleOptions.onIdentifyComplete = ^(MPIdentityApiResult * _Nullable apiResult, NSError * _Nullable error) {
if (apiResult) {
// If the user is identified, set additional user attributes
[apiResult.user setUserAttribute:@"example attribute key" value:@"example attribute value"];
}
};

[[MParticle sharedInstance] startWithOptions:mParticleOptions];

self.viewController = [[MainViewController alloc] init];
return [super application:application didFinishLaunchingWithOptions:launchOptions];
}

@end

AndroidAndroid への直接リンク

MainActivity initialization (Android)
import com.mparticle.MParticle;
import com.mparticle.MParticleOptions;

public class MainActivity extends CordovaActivity
{
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);

// Enable Cordova apps to be started in the background
Bundle extras = getIntent().getExtras();
if (extras != null && extras.getBoolean("cdvStartInBackground", false)) {
moveTaskToBack(true);
}

// Set by <content src="index.html" /> in config.xml
loadUrl(launchUrl);

// Identify the current user:
// If you do not have the user's email address, you can pass in a null value
IdentityApiRequest identifyRequest = IdentityApiRequest.withEmptyUser()
// Preferred: pass the customer's raw, unhashed email via .email().
// If you can only provide a SHA-256-hashed email, remove .email() and use .userIdentity(Other) instead — do not pass both.
.email("j.smith@example.com")
// .userIdentity(MParticle.IdentityType.Other, "SHA-256 hashed email") // only if raw email unavailable
// If you can only provide a SHA-256-hashed mobile number, use 'other2' instead of MobileNumber — do not pass both.
// .userIdentity(MParticle.IdentityType.Other2, "SHA-256 hashed mobile number") // only if raw mobile unavailable
.userIdentity(MParticle.IdentityType.MobileNumber, "+13125551515")
.customerId("cust_10482")
.build();

MParticleOptions options = MParticleOptions.builder(this)
.credentials(
"your-key", // The key provided by your Rokt account manager
"your-secret" // The secret provided by your Rokt account manager
)
// Specify the data environment with environment:
// Set it to Development if you are still testing your integration.
// Set it to Production if your integration is ready for production data.
// The default is AutoDetect which attempts to detect the environment automatically.
.environment(MParticle.Environment.Development)
.identify(identifyRequest)
.build();

MParticle.start(options);
}
}

When inserting the initialization snippet, you will see customizable fields for:

  1. Entering your Rokt key and secret.

    Set your-key and your-secret to the key and secret values provided by your Rokt account manager.

  2. Setting your data environment.

    Set environment to MPEnvironmentDevelopment (iOS) or MParticle.Environment.Development (Android) while testing to route data to the Development environment, and MPEnvironmentProduction / MParticle.Environment.Production to send live customer activity to Production.

  3. Identifying your user and setting attributes.

    In identifyRequest, pass the user's raw, un-hashed email. For hashed emails and other identifiers, see Supported User Identifiers. Once identified, use the callback to set additional user attributes — see User Attributes for the recommended list.

    注記

    Always include identifyRequest in the initialization snippet. If you don't have the user's email at initialization, omit the email assignment — the SDK+ will still initialize, and you can identify the user later via 3. Identify the User. See Error Handling for how to handle identify failures — without error handling you may see data consistency issues at scale.

3. Identify the User3. Identify the User への直接リンク

Call the identify method 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 event data is attributed to the correct user.

Supported User IdentifiersSupported User Identifiers への直接リンク

Show supported user identifiers
FieldTypeDescription
emailstringPass the customer's raw, unhashed email address.
mobilestringPass the customer's phone number in E.164 format.
customeridstringPass your internal customer/account identifier. Send on every screen for logged-in users.
otherstringPass a SHA-256-hashed email. Only use when the raw email cannot be provided — do not pass both email and other. (Android path only.)
other2stringPass a SHA-256-hashed mobile number. Only use when the raw mobile number cannot be provided — do not pass both mobile and other2. (Android path only.)
emailSha256stringPass a SHA-256-hashed email. Only use when the raw email cannot be provided — do not pass both email and emailSha256. (iOS path only.)
mobileSha256stringPass a SHA-256-hashed mobile number. Only use when the raw mobile number cannot be provided — do not pass both mobile and mobileSha256. (iOS path only.)

To identify the user:

  1. Create an identifyRequest object to contain the user's identifiers. You should integrate the user's raw, unhashed email address into the email field.

  2. To set additional user attributes, create an identifyTask callback. If the identifyRequest succeeds, then any user attributes you set inside the callback are assigned to the identified user.

  3. After creating the identifyRequest and the callback, send them to Rokt using the identify method.

    For example, to identify a user named Jane Smith with the email address j.smith@example.com, mobile number +13125551515, and customer ID cust_10482, you would use:

Identify Jane Smith
// 1. Create the identifyRequest object
var identifyRequest = new mparticle.IdentityRequest();
// Preferred: pass the customer's raw, unhashed email address.
// If you can only provide a SHA-256-hashed email, use setUserIdentity with 'other' instead — do not pass both.
identifyRequest.setEmail('j.smith@example.com');
identifyRequest.setUserIdentity(mparticle.UserIdentityType.Other, 'SHA-256 hashed email'); // only if raw email unavailable
// If you can only provide a SHA-256-hashed mobile number, use 'Other2' instead of 'MobileNumber' — do not pass both.
// (Called 'other2' on Android and 'mobileSha256' on iOS; both use this same field.)
identifyRequest.setUserIdentity(mparticle.UserIdentityType.Other2, 'SHA-256 hashed mobile number'); // only if raw mobile unavailable
identifyRequest.setUserIdentity(mparticle.UserIdentityType.MobileNumber, '+13125551515');
identifyRequest.setCustomerId('cust_10482');

// 2. User attributes are set using the identifyTask callback
var identifyTask = {
onSuccess: function(userID) {
var user = new mparticle.User(userID);
user.setUserAttribute('firstname', 'Jane');
user.setUserAttribute('lastname', 'Smith');
},
onError: function(errorResponse) {
console.error('Identify error: ' + JSON.stringify(errorResponse));
}
};

// 3. Call the identify method, including the identifyRequest object and identifyTask
var identity = new mparticle.Identity();
identity.identify(identifyRequest, identifyTask.onSuccess);

4. Set User Attributes4. Set User Attributes への直接リンク

Set user attributes progressively as the user navigates your app, not just at checkout. The more attributes you set, the better Rokt can resolve the customer and deliver relevant offers.

Set user attributes
var identity = new mparticle.Identity();

identity.getCurrentUser(function(userID) {
var currentUser = new mparticle.User(userID);

// Once you have successfully set the current user, you can set user attributes with:
currentUser.setUserAttribute('custom-attribute-name', 'custom-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('billingcity', 'Brooklyn');
currentUser.setUserAttribute('billingstate', 'NY');
currentUser.setUserAttribute('billingzipcode', '123456');
currentUser.setUserAttribute('dob', 'yyyymmdd');
currentUser.setUserAttribute('title', 'Mr');
currentUser.setUserAttribute('language', 'en');
currentUser.setUserAttribute('predictedltv', '136.23');

// You can create a user attribute to contain a list of values
currentUser.setUserAttributeArray('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 AttributesUser Attributes への直接リンク

Set as many of the following as you can collect:

Show all user attributes
FieldTypeDescription
firstnamestringCustomer's first name. Used for personalization.
lastnamestringCustomer's last name. Used for personalization.
mobilestringPhone number formatted as 1112345678 or +1 (222) 345-6789. Used for identity resolution and relevance.
ageintegerCustomer's age. Alternate to dob. Used for eligibility and relevance.
dobstringDate of birth, yyyymmdd. Alternate to age. Used for eligibility and relevance.
genderstringCustomer's gender. For example, M, F, Male, or Female. Used for relevance.
titlestringHonorific. For example, Mr, Mrs, Ms. Used for personalization.
languagestringISO 639-1 language code associated with the purchase. Used for relevance.
billingcitystringBilling city. Used for relevance.
billingstatestringBilling state / province / region. Used for relevance and eligibility.
billingzipcodestringFull ZIP or postcode (US preference is ZIP+4). Used for identity resolution and relevance.
billingaddress1stringBilling street address line 1. Used for identity resolution and relevance.
billingaddress2stringBilling street address line 2. Used for identity resolution.
countrystringISO 3166-1 alpha-2 country code (e.g. US, GB, AU). Used for eligibility and relevance.
birthyearintegerCustomer's birth year (e.g. 1990). Used for eligibility and relevance.
newcustomerbooleanWhether this is a first-time buyer. Used for relevance.
customertypestringWhether the user is authenticated (guest / logged_in). Used for relevance.
loyaltytierstringPartner loyalty program tier. Used for relevance and eligibility.
loyaltyidstringLoyalty program member ID. Used for identity resolution.
predictedltvdecimalPredicted total lifetime value, typically from a partner ML model. Used for relevance.
subscriptionstatusstringSubscription state if applicable (active, trial, churned, paused, none). Used for relevance and eligibility.
customersegmentstringPartner internal segmentation (e.g. vip, at_risk, new, reactivated). Used for relevance.
acquisitionchannelstringChannel through which the customer was acquired. Used for relevance.

All user attributes (including list attributes) must have distinct names.

5. Track Funnel Events5. Track Funnel Events への直接リンク

Track screen views, account lifecycle events, commerce events, and custom events so Rokt can maintain identity continuity and understand where each customer is in their journey.

Screen ViewsScreen Views への直接リンク

Call mparticle.logScreenEvent with the name of the screen (e.g. 'homepage', 'product detail page'). Include any additional custom attributes in the info object.

Log a screen view
mparticle.logScreenEvent('homepage', { 'custom-attribute': 'custom-value' });

Account Lifecycle EventsAccount 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 events accept a method attribute describing how the user signed up or logged in.

Supported lifecycle event typesSupported lifecycle event types への直接リンク

Show lifecycle event types
Lifecycle Event TypeWhen to triggerSupported method values
sign_upNew account createdemail, social, guest
loginUser logs inemail, social, sso
logoutUser logs outNot applicable.

Example lifecycle eventsExample lifecycle events への直接リンク

Signup, login, logout
// 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 EventsCommerce 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.

Commerce events are logged with mparticle.logCommerceEvent, using a product action type 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 and walk through assembling the event.

Product action typesProduct action types への直接リンク

Show all product action types
Customer actionProduct action type
Product detail page viewedmparticle.ProductActionType.ViewDetail
Product clickedmparticle.ProductActionType.Click
Item added to cartmparticle.ProductActionType.AddToCart
Item removed from cartmparticle.ProductActionType.RemoveFromCart
Item added to wishlistmparticle.ProductActionType.AddToWishlist
Item removed from wishlistmparticle.ProductActionType.RemoveFromWishlist
Checkout flow initiatedmparticle.ProductActionType.Checkout
Checkout option selectedmparticle.ProductActionType.CheckoutOption
Order confirmedmparticle.ProductActionType.Purchase
Order refundedmparticle.ProductActionType.Refund

Tracking a commerce event requires three steps:

1. Define the product1. Define the product への直接リンク

Create a product object with the product's name, SKU, and price. Set additional fields as needed.

Define a product
var product = mparticle.eCommerce.createProduct(
'Double Room - Econ Rate', // Name
'econ-1', // SKU
100.00, // Price
4 // Quantity
);
product.Category = 'room';
product.Brand = 'lodge-o-rama';
product.Variant = 'standard';
product.Attributes = {
'ocean-view': 'true',
'balcony': 'false'
};

2. Summarize the transaction2. Summarize the transaction への直接リンク

Create a transactionAttributes object for Purchase, Checkout, and CheckoutOption events. Include shipping and coupon code when applicable — order-level coupons belong here, not on individual products.

Summarize the transaction
var transactionAttributes = {
Id: 'ORDER-12345',
Revenue: 149.99,
Tax: 12.50,
Shipping: 5.99,
Coupon: 'SUMMER20'
};

3. Log the commerce event3. Log the commerce event への直接リンク

Call mparticle.eCommerce.logProductAction with a product action type from the table above, the product array, optional custom attributes, and the transaction attributes.

Log a Purchase commerce event
mparticle.eCommerce.logProductAction(
mparticle.ProductActionType.Purchase,
[product],
{ 'sale': 'true' },
null,
transactionAttributes
);

The same structure applies to every product action type — swap Purchase for the action that matches the customer behavior you're logging. See the Product action types table for the full list.

Custom EventsCustom Events への直接リンク

Track custom events using mparticle.logEvent, passing an event name, event type, and optional custom attributes.

Supported custom event typesSupported custom event types への直接リンク

Show custom event types
TypeUse for
mparticle.EventType.NavigationUser navigation flows and screen transitions within your app.
mparticle.EventType.LocationLocation-based interactions and movements.
mparticle.EventType.SearchSearch queries and search-related actions.
mparticle.EventType.TransactionFinancial transactions and purchase-related activity.
mparticle.EventType.UserContentUser-generated content like reviews, comments, or posts.
mparticle.EventType.UserPreferenceUser settings, preferences, and customization choices.
mparticle.EventType.SocialSocial media interactions and sharing activities.
mparticle.EventType.OtherAnything that doesn't fit the categories above.

Example custom eventExample custom event への直接リンク

Log a custom event
mparticle.logEvent(
'Video Watched',
mparticle.EventType.Navigation,
{ 'category': 'Destination Intro', 'title': 'Paris' }
);

6. Show a Placement6. Show a Placement への直接リンク

Call mparticle.Rokt.selectPlacements on every payment and confirmation screen you want Rokt to render content on. Include one of the following page identifiers to specify the screen type and whether it's for testing or production:

  • stg.rokt.conf: A confirmation screen in a staging (or testing) environment.
  • prod.rokt.conf: A confirmation screen in a production environment.
  • stg.rokt.payments: A payments screen in a staging (or testing) environment.
  • prod.rokt.payments: A payments screen in a production environment.

Placement AttributesPlacement Attributes への直接リンク

Pass these attributes in the attributes map of selectPlacements. Always supply the most recent value — attributes passed here override any earlier setUserAttribute calls.

Show all placement attributes
FieldTypeDescription
emailstringCustomer email (unhashed). Used for identity resolution.
firstnamestringCustomer first name. Used for personalization.
lastnamestringCustomer last name. Used for personalization.
mobilestringCustomer mobile number in E.164 format. Used for identity resolution.
confirmationrefstringOrder / confirmation reference number. Used for relevance and deduplication.
currencystringTransaction currency (ISO 4217, e.g. USD, GBP, AUD). Used for relevance.
countrystringISO 3166-1 alpha-2 country code. Used for eligibility and relevance.
languagestringCustomer's preferred language (ISO 639-1). Used for relevance.
totalpricedecimalTotal cart value including tax and shipping. Used for relevance.
amountstringCart subtotal before tax and shipping. Distinct from totalprice. Used for relevance.
couponCodestringPromo code applied to the order, if any. Used for relevance.
newcustomerbooleanWhether this is a first-time buyer. Used for relevance.
customertypestringguest or logged_in. Used for relevance.
valuedecimalCustomer's cumulative purchase value (e.g. "2340.00"). Used for relevance.
subscriptionstatusstringSubscription state if applicable (active, trial, churned, paused, none). Used for relevance and eligibility.
customersegmentstringPartner internal segmentation (e.g. vip, at_risk, new, reactivated). Used for relevance.
paymenttypestringPayment method selected (credit_card, paypal, apple_pay, etc.). Used for Pay+ eligibility.
paymentServiceProviderstringPayment services offered on the page (apple_pay, paypal, card). Used for Pay+ eligibility.
ccbinstringCredit card BIN (first 6 digits). Used for relevance.
billingnamestringBilling name. Used for identity resolution.
billingaddress1stringBilling street address. Used for identity resolution and relevance.
billingaddress2stringBilling apartment / unit. Used for identity resolution.
billingcitystringBilling city. Used for relevance.
billingstatestringBilling state or province. Used for relevance.
billingzipcodestringBilling ZIP / postcode. Used for identity resolution and relevance.
shippingmethodstringShipping method selected (standard, express, next_day). Used for relevance.
shippingnamestringShipping name. Used for relevance.
shippingaddress1stringShipping street address. Used for relevance.
shippingcitystringShipping city. Used for relevance.
shippingstatestringShipping state or province. Used for relevance.
shippingzipcodestringShipping ZIP or postcode. Used for relevance.
shippingcountrystringShipping country (ISO 3166-1 alpha-2). Used for relevance.
cartItemsstringJSON-serialized array of cart items. Used for relevance.
adsExperiencestringPass "shoppable" when deliberately targeting a Shoppable Ads experience. Used on iOS only.

Overlay PlacementsOverlay Placements への直接リンク

Overlay placements render on top of your confirmation screen in a Rokt-managed container, requiring no changes to your app's existing layout.

To insert an overlay placement, call selectPlacements once the confirmation screen loads:

Overlay placement
var attributes = {
// Identity
'email': 'j.smith@example.com',
'firstname': 'Jenny',
'lastname': 'Smith',
'mobile': '+13125551515',

// Transaction
'confirmationref': '54321',
'currency': 'USD',
'country': 'US',
'language': 'en',
'totalprice': '149.99',
'couponCode': 'SUMMER20',

// Customer context
'newcustomer': 'false',
'customertype': 'logged_in',
'value': '2340.00',
'subscriptionstatus': 'active',
'customersegment': 'vip',

// Payment (include paymenttype and paymentServiceProvider for Pay+)
'paymenttype': 'credit_card',
'paymentServiceProvider': 'card',
'ccbin': '411112',

// Billing address
'billingaddress1': '123 Main St',
'billingcity': 'Brooklyn',
'billingstate': 'NY',
'billingzipcode': '11201',

// Shipping
'shippingmethod': 'express',
'shippingaddress1': '175 Varick St',
'shippingcity': 'New York',
'shippingstate': 'NY',
'shippingzipcode': '10014',
'shippingcountry': 'US'
};

var config = {
colorMode: mparticle.Rokt.ColorMode.LIGHT
};

mparticle.Rokt.selectPlacements(
'RoktExperience',
attributes,
config
);

Embedded PlacementsEmbedded Placements への直接リンク

Embedded placements render inline at a fixed position in your app that you control (for example, above the payment options on a cart screen). Both Thanks and Pay+ use embedded placements, but Pay+ must use embedded placements.

To insert an embedded placement, pass the embedded view identifier in your selectPlacements call:

Embedded placement
var attributes = {
'email': 'j.smith@example.com',
'firstname': 'Jenny',
'lastname': 'Smith',
'billingzipcode': '90210',
'confirmationref': '54321'
};

var config = {
colorMode: mparticle.Rokt.ColorMode.LIGHT
};

mparticle.Rokt.selectPlacements(
'RoktExperience',
attributes,
config,
'RoktEmbedded1' // The embedded view identifier
);
Pay+

For Pay+ placements, include paymenttype and paymentServiceProvider in the selectPlacements call on each screen. paymentServiceProvider communicates what payment methods are available on the payment screen; paymenttype communicates what method the user paid with.

Interstitial PlacementsInterstitial Placements への直接リンク

Interstitial placements are rendered between the payment and confirmation screens, allowing customers to purchase additional products. Interstitial placements are used by Shoppable Ads.

注記

Interstitial placements are supported on iOS only in the Cordova SDK+. The Android path of this plugin does not support interstitial placements. Do not invoke interstitial placement logic on Android.

Apple Pay setup required

To enable Shoppable Ads with Apple Pay on iOS, your native iOS project must have RoktPaymentExtension registered in AppDelegate after MParticle.start and before selectPlacements. Follow the Apple Pay iOS setup guide to create a merchant ID, configure your Xcode project, and register the payment extension.

On iOS, interstitial placements use the selectShoppableAds method exposed through the Rokt kit. The iOS native layer handles the interstitial UI; your JavaScript code triggers it and listens for the resulting events.

To implement an interstitial placement on iOS, call selectShoppableAds from your confirmation screen logic. Pass the same comprehensive attributes you use for overlay placements:

Interstitial placement (iOS only)
// Guard: only invoke on iOS
if (cordova.platformId === 'ios') {
var attributes = {
// Identity
'email': 'j.smith@example.com',
'firstname': 'Jenny',
'lastname': 'Smith',
'mobile': '+13125551515',

// Transaction
'confirmationref': '54321',
'currency': 'USD',
'country': 'US',
'language': 'en',
'totalprice': '149.99',
'amount': '137.50',
'couponCode': 'SUMMER20',

// Customer context
'newcustomer': 'false',
'customertype': 'logged_in',
'value': '2340.00',

// Payment
'paymenttype': 'credit_card',
'paymentServiceProvider': 'card',
'ccbin': '411112',

// Billing address
'billingaddress1': '123 Main St',
'billingcity': 'Brooklyn',
'billingstate': 'NY',
'billingzipcode': '11201',

// Shipping (required for Shoppable Ads fulfillment)
'shippingaddress1': '175 Varick St',
'shippingcity': 'New York',
'shippingstate': 'NY',
'shippingzipcode': '10014',
'shippingcountry': 'US'
};

var config = {
colorMode: mparticle.Rokt.ColorMode.LIGHT
};

mparticle.Rokt.selectPlacements(
'RoktExperience',
attributes,
config
);
}
注記

If your app does not have shipping address details (for example, for ticket or digital goods purchases), pass billing address details instead. Rokt will provide a UI for the customer to confirm or edit their shipping address before completing the purchase.

Optional FunctionsOptional Functions への直接リンク

FunctionPurpose
mparticle.Rokt.close()Auto-close overlay placements.

Additional ConfigurationAdditional Configuration への直接リンク

Pass optional parameters such as a config object to customize the placement UI (e.g. dark/light mode, caching).

selectPlacements with config
var config = {
colorMode: mparticle.Rokt.ColorMode.LIGHT,
cacheConfig: {
cacheDurationInSeconds: 1200,
cacheAttributes: {
'email': 'j.smith@example.com',
'orderNumber': '123'
}
}
};

mparticle.Rokt.selectPlacements(
'RoktExperience',
attributes,
config
);
注記

If you want to update the identifier RoktExperience or embedded identifier RoktEmbedded1 with a different value, contact your Rokt account manager to ensure Rokt placements are configured consistently.

Events APIEvents API への直接リンク

The SDK+ provides placement lifecycle events you can subscribe to. Use the onEvent callback in your selectPlacements call to respond to load state, engagement, and failures.

Subscribe to placement events
mparticle.Rokt.selectPlacements(
'RoktExperience',
attributes,
config,
null,
function(event) {
// Handle placement events
if (event && event.eventType) {
console.log('Rokt event: ' + event.eventType);
}
}
);

Standard eventsStandard events への直接リンク

Show all standard events
EventDescriptionParams
ShowLoadingIndicatorTriggered before the SDK+ calls the Rokt backend.
HideLoadingIndicatorTriggered when the SDK+ receives a success or failure from the Rokt backend.
PlacementInteractiveTriggered when a placement has been rendered and is interactable.placementId: String
PlacementReadyTriggered when a placement is ready to display but has not rendered content yet.placementId: String
OfferEngagementTriggered when the user engages with the offer.placementId: String
PositiveEngagementTriggered when the user positively engages with the offer.placementId: String
FirstPositiveEngagementTriggered when the user positively engages with the offer for the first time.placementId: String, fulfillmentAttributes: Object
OpenUrlTriggered when the user presses a URL that is configured to be sent to the partner app.placementId: String, url: String
PlacementClosedTriggered when a placement is closed by the user.placementId: String
PlacementCompletedTriggered when the offer progression reaches the end and no more offers are available to display. Also triggered when cache is hit but the retrieved placement will not be displayed as it has previously been dismissed.placementId: String
PlacementFailureTriggered when a placement could not be displayed due to some failure or when no placements are available to show.placementId: String (optional)
CartItemInstantPurchaseTriggered when the catalog item purchase is initiated by the user (iOS only).placementId: String, cartItemId: String, catalogItemId: String, currency: String, description: String, linkedProductId: String, totalPrice: Number, quantity: Number, unitPrice: Number

7. Appendix7. Appendix への直接リンク

Appendix A: App ConfigurationAppendix A: App Configuration への直接リンク

Applications can pass configuration settings through the config object so the SDK+ uses your app's custom configuration instead of system defaults.

ColorMode objectColorMode object への直接リンク

ValueDescription
LIGHTApplication is in Light Mode
DARKApplication is in Dark Mode
SYSTEMApplication defaults to System Color Mode
selectPlacements with ColorMode
var config = {
colorMode: mparticle.Rokt.ColorMode.LIGHT
};

mparticle.Rokt.selectPlacements(
'RoktExperience',
attributes,
config
);

CacheConfig objectCacheConfig object への直接リンク

ParameterDescription
cacheDurationInSecondsOptional duration in seconds for which the Rokt SDK+ should cache the experience. Maximum allowed value is 90 minutes; default is 90 minutes if not provided or invalid.
cacheAttributesOptional attributes to be used as cache key. If null, all attributes sent in selectPlacements will be used as the cache key.
Cache for 1200 seconds
// Cache the experience for 1200 seconds, using email and orderNumber as the cache key.
var config = {
cacheConfig: {
cacheDurationInSeconds: 1200,
cacheAttributes: {
'email': 'j.smith@example.com',
'orderNumber': '123'
}
}
};

mparticle.Rokt.selectPlacements(
'RoktExperience',
attributes,
config
);

EdgeToEdgeDisplay (Android only)EdgeToEdgeDisplay (Android only) への直接リンク

Controls whether the Rokt overlay respects Android's edge-to-edge display mode. This configuration applies to the Android path only; iOS does not use this flag.

ValueDescription
true (default)Application supports edge-to-edge display mode
falseApplication does not support edge-to-edge display mode

The Cordova SDK+ does not currently expose EdgeToEdgeDisplay as a JavaScript config option. If your Android app opts out of edge-to-edge display and the overlay renders incorrectly, configure it in your native Android code:

EdgeToEdgeDisplay (native Android — RoktConfig)
import com.mparticle.rokt.RoktConfig

val roktConfig = RoktConfig.Builder()
.edgeToEdgeDisplay(false) // set to false if your app does not use edge-to-edge
.build()

Pass roktConfig to selectPlacements in your native Android layer, or raise this with your Rokt account manager if you need Cordova-level support.

Appendix B: Native UI ComponentsAppendix B: Native UI Components への直接リンク

The Cordova SDK+ uses native Rokt UI components rendered by the underlying iOS and Android SDK+s. There is no Cordova-specific declarative UI component (equivalent to Jetpack Compose or SwiftUI). The placement UI is managed entirely by the native layer and surfaced through the selectPlacements API.

Appendix C: Error HandlingAppendix C: Error Handling への直接リンク

The IDSync API is intended to be central to your app's state and is designed to be fast and highly-available. Similar to how your app may prevent users from logging in, logging out, or modifying their state without an internet connection — treat these APIs as gating operations to maintain a consistent user state. The SDK+ will not retry API calls automatically, but provides callback APIs so you can do so according to your business logic.

If you do not implement error handling, you may see data consistency issues at scale.

The Cordova SDK+'s mparticle.Identity.identify() callback pattern surfaces errors through the onError handler. Inspect the errorResponse object to determine the appropriate action:

IDSync error handling
var identifyTask = {
onSuccess: function(userID) {
// IDSync succeeded — proceed with the identified user
console.log('Identify success, userID: ' + userID);
},
onError: function(errorResponse) {
if (errorResponse && errorResponse.httpCode !== undefined) {
if (errorResponse.httpCode === -1) {
// Device is likely offline (maps to UNKNOWN_ERROR on Android,
// MPIdentityErrorResponseCodeClientNoConnection on iOS) — retry the request
} else if (errorResponse.httpCode === 429) {
// Throttled — retry with exponential backoff
} else if (errorResponse.httpCode >= 500) {
// Server-side error — check the mParticle status page
} else {
// Inspect errorResponse for implementation issues (e.g. 400 invalid request, 401 auth error)
console.error('Identity error: ' + JSON.stringify(errorResponse));
}
}
}
};

var identity = new mparticle.Identity();
identity.identify(identifyRequest, identifyTask.onSuccess);

iOS error codesiOS error codes への直接リンク

On iOS, the native SDK+ maps failures to MPIdentityErrorResponseCode values. The Cordova bridge surfaces these as the httpCode in the JavaScript error response. Key codes to handle:

CodeMeaningAction
MPIdentityErrorResponseCodeClientNoConnectionDevice offline or no networkRetry the request
MPIdentityErrorResponseCodeClientSideTimeoutTCP connection timed outRetry the request
MPIdentityErrorResponseCodeRequestInProgressAnother IDSync request already in flightInspect implementation; retry if infrequent
MPIdentityErrorResponseCodeRetrySDK+-level retry signalRetry the request
429 (HTTP)Rate-limited by mParticle serversRetry with exponential backoff
400 (HTTP)Invalid request bodyInspect errorResponse — typically an implementation issue
401 (HTTP)Authentication errorVerify your API key

Android error codesAndroid error codes への直接リンク

On Android, the native SDK+ returns IdentityApi.UNKNOWN_ERROR for client-side failures (device offline, client-side timeout, invalid requests). A 429 response maps to IdentityApi.THROTTLE_ERROR. Both signal the appropriate retry strategy:

  • UNKNOWN_ERROR (device offline or client-side issue): retry the request once connectivity is restored.
  • THROTTLE_ERROR / 429: retry with exponential backoff. This can indicate a user "hotkey" or a higher-than-expected IDSync volume — inspect your implementation if it occurs frequently.

Appendix D: Passing Session ID from Web to NativeAppendix D: Passing Session ID from Web to Native への直接リンク

When a user journey spans both web and native platforms, you can maintain a consistent Rokt session by passing the session ID from the Web SDK+ to the Cordova SDK+. This is useful for hybrid flows where users complete an action in a WebView (such as a payment page) and return to the native app for confirmation.

Getting the session ID from Web SDK+Getting the session ID from Web SDK+ への直接リンク

After calling selectPlacements, the session ID is available on the selection context:

Retrieve sessionId from the selection context
const selection = await launcher.selectPlacements({
identifier: "checkout",
attributes: {
email: "user@example.com",
// ... other attributes
}
});

const sessionId = await selection.context.sessionId;

Pass the session ID to your native app using a deep link:

Deep-link to native app
const deepLink = `myapp://confirmation?sessionId=${encodeURIComponent(sessionId)}`;
window.location.href = deepLink;

Setting the session IDSetting the session ID への直接リンク

Extract the session ID from the deep link and pass it to the mParticle SDK+ before calling selectPlacements.

Set sessionId in Cordova
// Extract the sessionId from your deep link handler and set it before selectPlacements
var sessionId = getSessionIdFromDeepLink(); // Your deep link parsing logic

if (sessionId) {
mparticle.Rokt.setSessionId(sessionId);
}

// Then proceed with selectPlacements
mparticle.Rokt.selectPlacements('RoktExperience', attributes, config);

NotesNotes への直接リンク

  • Call setSessionId before selectPlacements to ensure the session is used.
  • Empty strings are ignored and will not update the session.
  • Always URL-encode the session ID when passing as a query parameter.

8. Test Your Integration8. Test Your Integration への直接リンク

To confirm the SDK+ initializes and events log correctly:

  1. Enable verbose SDK+ logging before initialization so you can see what's being sent.
  2. Build and run your app against a development key with the environment set to Development on both platforms.
  3. Trigger selectPlacements on the screen where the placement should render and confirm the placement loads.
  4. Verify events appear in your mParticle workspace's Live Stream, and confirm the identifyRequest call succeeds.

iOS verbose loggingiOS verbose logging への直接リンク

Enable verbose SDK+ logging (iOS)
[MParticle sharedInstance].logLevel = MPILogLevelVerbose;

Android verbose loggingAndroid verbose logging への直接リンク

Enable verbose SDK+ logging (Android)
MParticleOptions options = MParticleOptions.builder(this)
.credentials("your-key", "your-secret")
.environment(MParticle.Environment.Development)
.logLevel(MParticle.LogLevel.VERBOSE)
.build();

TroubleshootingTroubleshooting への直接リンク

If the placement doesn't render or events don't appear, check the native device logs (Xcode console for iOS, Android Logcat for Android) for Rokt SDK+ errors. Common issues:

Initialization errorsInitialization errors への直接リンク

  • Confirm the key and secret match the values from your Rokt account manager on both iOS (your-key / your-secret in optionsWithKey:secret:) and Android (.credentials("your-key", "your-secret")).
  • Confirm MParticle.start (Android) and [[MParticle sharedInstance] startWithOptions:options] (iOS) run before any selectPlacements or logEvent call.

Identity errorsIdentity errors への直接リンク

If the identify callback fires with an error, see Error Handling for the error codes and retry guidance. Without error handling you may see data consistency issues at scale.

Placement not renderingPlacement not rendering への直接リンク

  • Confirm the placement identifier (e.g. RoktExperience) matches what your Rokt account manager configured.
  • For embedded placements, confirm the embedded view identifier (e.g. RoktEmbedded1) matches the layout configuration.
  • Check that the attributes map contains at least email, firstname, lastname, billingzipcode, and confirmationref.
この記事は役に立ちましたか?