Rokt Ecommerce SDK+ Integration Guides

website·Indexed 43 days ago

https://docs.rokt.com/

Technical documentation for integrating the Rokt Ecommerce SDK+ across multiple platforms, including Web, iOS, Android, Flutter, React Native, MAUI, and Cordova. Guides cover SDK initialization using API keys and secrets, configuring custom first-party domains and data environments, user identification via identifyRequest, setting user attributes, and logging commerce events such as Purchase, Checkout, and ViewDetail.

Tokens
215.2K
Snippets
819
Records
977
Agent score
55%

What's inside Rokt

  1. Log page views with Rokt Ecommerce SDK+

    Use mParticle.logPageView to track page views. The event should include details about the current page's path, type, and referring source. For the screenname field, use the last segment of the URL path (e.g., /products/shoes becomes shoes), defaulting to home if the path is empty.
    window.mParticle.ready(function() {
    mParticle.logPageView("page_view", {
      screenname: "order-10482",
      pagetype: "confirmation",
      url: window.location.toString(),
      title: document.title,
      sitesection: "checkout",
      referringpage: document.referrer
    });
    });
  2. Identify users in the Rokt MAUI SDK+

    To identify a user, create an IdentityApiRequest object containing the user's identifiers and pass it to the appropriate MParticle.Instance.Identity method based on the user's action.

    Supported User Identifiers:

    • email: Raw, unhashed email address (Preferred).
    • mobile: Phone number in E.164 format.
    • customerid: Internal customer/account identifier. Should be sent on every screen for logged-in users.
    • Hashed Identifiers (Use only if raw values are unavailable):
      • Android: Use other for SHA-256 hashed email and other2 for SHA-256 hashed mobile.
      • iOS: Use emailSha256 for SHA-256 hashed email and mobileSha256 for SHA-256 hashed mobile.
      • Constraint: Do not pass both a raw identifier and its hashed counterpart.

    Identification Methods:

    • MParticle.Instance.Identity.Login(identifyRequest): Use when a user logs in or creates an account. Automatically logs an event for attribution.
    • MParticle.Instance.Identity.Identify(identifyRequest): Use when an email is obtained mid-session without a login transition (e.g., guest checkout).
    • MParticle.Instance.Identity.Logout(): Use when the user logs out. Automatically logs an event for attribution.
    // 1. Create the identifyRequest object
    var identifyRequest = new IdentityApiRequest();
    identifyRequest.UserIdentities = new Dictionary<UserIdentity, string>()
    {
    #if __ANDROID__
      { UserIdentity.Email, "j.smith@example.com" },
      { UserIdentity.MobileNumber, "+13125551515" },
      { UserIdentity.CustomerId, "cust_10482" }
    #elif __IOS__
      { UserIdentity.Email, "j.smith@example.com" },
      { UserIdentity.MobileNumber, "+13125551515" },
      { UserIdentity.CustomerId, "cust_10482" }
    #endif
    };
    
    // 2. Call the method matching the user action
    MParticle.Instance.Identity.Login(identifyRequest)
      .AddSuccessListener(result =>
      {
          result.User.SetUserAttribute("firstname", "Jane");
          result.User.SetUserAttribute("lastname", "Smith");
      });
  3. Initialize Rokt SDK+ on iOS

    Initialize the SDK in the AppDelegate using MParticleOptions. You must specify your API key and secret. You can optionally set the environment to .development (for testing) or .production. If using a first-party domain, configure a custom base URL via MPNetworkOptions. User identification can be handled via MPIdentityApiRequest using either a plain email or a SHA-256 hashed email.
    import mParticle_Apple_SDK
    import RoktPaymentExtension
    
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
      let options = MParticleOptions(key: "your-key", secret: "your-secret")
      options.environment = .development
    
      let networkOptions = MPNetworkOptions()
      networkOptions.customBaseURL = URL(string: "https://rkt.example.com")
      options.networkOptions = networkOptions
    
      let identifyRequest = MPIdentityApiRequest.withEmptyUser()
      identifyRequest.email = "j.smith@example.com"
      // For hashed email: identifyRequest.setIdentity("sha256 hashed email", identityType: .other)
    
      options.identifyRequest = identifyRequest
      options.onIdentifyComplete = { (result, error) in
          if let user = result?.user {
              user.setUserAttribute("example attribute key", value: "example attribute value")
          }
      }
      MParticle.sharedInstance().start(with: options)
      return true
    }
  4. Log commerce events in iOS SDK+

    Commerce events are logged using MPCommerceEvent and an MPCommerceEventAction to identify the specific customer action. Events are sent to the SDK via MParticle.sharedInstance().logEvent(event).

    Supported Action Types

    Customer actionSwift action typeObjective-C action type
    Product detail page viewed.viewDetailMPCommerceEventActionViewDetail
    Product clicked.clickMPCommerceEventActionClick
    Item added to cart.addToCartMPCommerceEventActionAddToCart
    Item removed from cart.removeFromCartMPCommerceEventActionRemoveFromCart
    Item added to wishlist.addToWishlistMPCommerceEventActionAddToWishlist
    Item removed from wishlist.removeFromWishlistMPCommerceEventActionRemoveFromWishlist
    Checkout flow initiated.checkoutMPCommerceEventActionCheckout
    Checkout option selected.checkoutOptionMPCommerceEventActionCheckoutOption
    Order confirmed.purchaseMPCommerceEventActionPurchase
    Order refunded.refundMPCommerceEventActionRefund
  5. Implement page view events for specific page types

    Depending on the customer's location in the funnel, use the following pagetype values and screenname conventions when calling mParticle.logPageView:

    • Home Page: Use pagetype: "home". Log when the customer lands on the root or home page.
    • Product Listing Page (PLP): Use pagetype: "PLP". Log on category, collection, or search-results pages.
    • Product Detail Page (PDP): Use pagetype: "PDP". Log when a customer views a single product's details.
    • Cart: Use pagetype: "cart". Log when the customer reviews items in their cart.
    • Checkout: Use pagetype: "checkout". Log during the shipping, billing, or payment entry flow.
    • Confirmation: Use pagetype: "confirmation". Log on the order confirmation page; this is the primary surface for Rokt post-transaction offers.
  6. Implement Rokt Overlay placements in MAUI

    Overlay placements render on top of the confirmation screen in a Rokt-managed container and do not require changes to the app's existing layout. To trigger an overlay placement, call SelectPlacements once the confirmation screen loads, providing a placement identifier and a dictionary of user/transaction attributes.
    using mParticle.MAUI;
    
    var attributes = new Dictionary<string, string>
    {
      // 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
      ["paymenttype"] = "credit_card",
      ["paymentServiceProvider"] = "cardpayment",
      ["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"
    };
    
    MParticle.Instance.Rokt.SelectPlacements(
      identifier: "RoktExperience",
      attributes: attributes
    );
  7. Share Rokt sessions between Web and Native platforms

    To maintain a consistent user journey across web and native environments, pass the sessionId and sessionToken between platforms.

    Web to Native:

    1. Retrieve the sessionId from the selection context after calling selectPlacements.
    2. Pass the sessionId and sessionToken to the native app via a URL-encoded deep link.
    3. In the native app (Cordova), call mparticle.Rokt.setSessionId(sessionId) before calling selectPlacements.

    Native to Web:

    1. Read the session using getSession on iOS or Android.
    2. Inject the sessionId and sessionToken into the WebView's window.mParticle.config.launcherOptions before calling mParticle.init.
    // 1. Retrieve from Web SDK+
    const selection = await launcher.selectPlacements({ identifier: "checkout", attributes: { email: "user@example.com" } });
    const sessionId = await selection.context.sessionId;
    const sessionToken = '<session-token>';
    
    // 2. Deep-link to native
    const deepLink = `myapp://confirmation?sessionId=${encodeURIComponent(sessionId)}&sessionToken=${encodeURIComponent(sessionToken)}`;
    window.location.href = deepLink;
    
    // 3. Set in Cordova
    mparticle.Rokt.setSessionId(sessionId);
    
    // 4. Seed Web SDK+ from native session
    window.mParticle = window.mParticle || { config: {} };
    window.mParticle.config.launcherOptions = { sessionId: sessionId };
    if (sessionToken) {
        window.mParticle.config.launcherOptions.sessionToken = sessionToken;
    }
  8. Identify users and set attributes in Rokt SDK+

    Use IdentityApiRequest to identify users. You can provide a raw email, a SHA-256 hashed email (using IdentityType.Other), a SHA-256 hashed mobile number (using IdentityType.Other2), a phone number in E.164 format (IdentityType.MobileNumber), or an internal customer ID.

    To set additional user attributes, use a BaseIdentityTask with a success listener to access the MParticleUser object.

    // 1. Define the identity request
    val identifyRequest = IdentityApiRequest.withEmptyUser()
        .email("j.smith@example.com")
        .customerId("cust_10482")
        .build()
    
    // 2. Define a task to set attributes upon successful identification
    val identifyTask = BaseIdentityTask()
        .addSuccessListener { identityApiResult ->
            val user = identityApiResult.user
            user.setUserAttribute("example attribute key", "example attribute value")
        }
    
    // 3. Pass both to MParticleOptions
    val options = MParticleOptions.builder(this)
        .identify(identifyRequest)
        .identifyTask(identifyTask)
        .build()
  9. Install Rokt SDK+ for Android

    The Rokt SDK+ requires a minimum Android API level of 21+ (Android 5.0 Lollipop). Add the android-rokt-kit and android-core dependencies to your Gradle configuration.
    // build.gradle.kts
    dependencies {
      implementation("com.mparticle:android-rokt-kit:6.0.0")
      implementation("com.mparticle:android-core:6.0.0")
    }
    // build.gradle
    dependencies {
      implementation "com.mparticle:android-rokt-kit:6.0.0"
      implementation "com.mparticle:android-core:6.0.0"
    }
  10. Identify users and set attributes in Rokt SDK+

    Identify users during initialization using an IdentityApiRequest.

    Identifier Guidelines:

    • Email: Use UserIdentity.Email for raw, unhashed emails (Preferred).
    • Hashed Email: Use UserIdentity.Other for SHA-256 hashed emails. Do not pass both raw and hashed emails.
    • Mobile Number: Use UserIdentity.MobileNumber for E.164 format. Use UserIdentity.Other2 for SHA-256 hashed mobile numbers. Do not pass both.
    • Customer ID: Use UserIdentity.CustomerId.

    To set additional user attributes after identification, use the IdentityStateListener callback.

    var identifyRequest = new IdentityApiRequest();
    identifyRequest.UserIdentities = new Dictionary<UserIdentity, string>()
    {
      { UserIdentity.Email, "j.smith@example.com" },
      { UserIdentity.CustomerId, "cust_10482" }
    };
    
    // Set the identify request in options
    options.IdentifyRequest = identifyRequest;
    
    // Set attributes via the listener
    options.IdentityStateListener = newUser =>
    {
      if (newUser != null)
      {
          newUser.SetUserAttribute("example attribute key", "example attribute value");
      }
    };
  11. Implement an Overlay placement

    Overlay placements render on top of the confirmation page in a Rokt-managed container and do not require DOM changes. To trigger an overlay, call selectPlacements once the confirmation page loads.
    window.mParticle.ready(async function () {
      const selection = await window.mParticle.Rokt.selectPlacements({
        identifier: "prod.rokt.conf",
        attributes: {
          email: "j.smith@example.com",
          firstname: "Jenny",
          lastname: "Smith",
          mobile_number: "+13125551515",
          confirmationref: "ORDER-10482",
          currency: "USD",
          country: "US",
          language: "en",
          totalprice: 149.99,
          couponcode: "SUMMER20",
          newcustomer: false,
          customertype: "logged_in",
          value: 2340.00,
          subscriptionstatus: "active",
          customersegment: "vip",
          paymenttype: "credit_card",
          paymentServiceProvider: "cardpayment",
          ccbin: "411112",
          cartItems: [
            { cartitemid: "SKU-001", productsku: "SKU-001", productname: "Trail Runner v3", itemprice: 129.95, quantity: 1 }
          ]
        }
      });
    });