Last modified January 16, 2024 by Shelly Wolfe

Smart TV

Swrve is a multi-channel customer engagement platform that provides hyper-targeting and hyper-personalization in real-time to automate relevant moments of interaction that acquire, retain and monetize customers.
The Swrve SmartTV SDK enables your app to use all of these features on the Tizen (Samsung) or webOS (LG) TV platforms. This guide contains all the information you need to integrate the SDK into your Samsung or LG TV app.

Requirements

  • If you download the SwrveSDK production bundle and include it via script tag, there are no additional dependencies.
  • If you want to compile the SDK bundle from source, you will need Node.js 8+ and Yarn 1.5+.
  • The App ID and API Key for your app. This information is available in Swrve on the Integration Settings screen (on the Settings menu, select Integration settings).

Installing the SDK

Swrve has an open source SDK repository. There are two options for downloading the latest public Swrve SmartTV SDK:

  • Install the SDK using npm (node package manager).
    Run the following command: npm install @swrve/smarttv-sdk.
  • Download the SDK from the GitHub public repository.

Initializing the SDK

Depending on your data requirements, Swrve stores all customer data and content in either our US or EU data centers. If your app uses EU data storage and URL endpoints (that is, you log into the Swrve dashboard at https://eu-dashboard.swrve.com), include the EU stack information in the example below. If you have any questions or need assistance configuring the SDK for EU data storage, please contact support@swrve.com.

To initialize the SDK, create an instance before your application starts. Replace <app_id> and <api_key> with your app ID and API key.

Using the SDK bundle with a script tag

<script src="SwrveSDK.js"></script>
<script>
    SwrveSDK.createInstance({
        appId: <app_id>,
        apiKey: "<api_key>",
        //stack: "eu", **To use the EU stack, include this in your config **//
    });
</script>

Using the SDK when installed from npm

When using ES5 modules, require the SDK as follows:

var SwrveSDK = require("swrvesdk");

SwrveSDK.createInstance({
    appId: <app_id>,
    apiKey: "<api_key>",
    //stack: "eu", **To use the EU stack, include this in your config **//
});

Or you can import it it as an ES6 module:

import SwrveSDK from "swrvesdk";

SwrveSDK.createInstance({
    appId: <app_id>,
    apiKey: "<api_key>",
    //stack: "eu", **To use the EU stack, include this in your config **//
});

If there are any application event handlers the app needs to listen to, initialize them after you create the SDK instance. When the app is not displaying an in-app message, the SDK ignores any non-SDK related interaction events and they are handled by your own application handlers. Once an in-app message is displayed, the SDK takes over and blocks event propagation so that no accidental misclicks in the application can occur.

SwrveSDK.createInstance({ ... });
document.addEventListener("keydown", onKeyPressed);
// other app initialization code
app.render();

Manage how you track user behavior

Swrve provides the identify API to help you manage how you track user activity across app sessions and multiple devices. For more information on how to identify users and then track and target them safely across multiple devices, platforms, and channels, see Tracking your users with Swrve User Identity.

External user ID

The external user ID is a non-discoverable key that identifies your user across multiple channels and platforms. To ensure app security, Swrve does not accept email or other personally identifiable information (PIIs) as the external user ID and rejects them on the server side. Before you implement the Identify service, please consult with your CSM at support@swrve.com for some guidance on best practices to follow in your integration.

The external user ID should always be unique to each user. Using a shared external user ID across users may have adverse consequences on user segmentation, reporting, audiences, and QA device behavior.

Identify pre-existing users

To find pre-existing user identities that an app has logged, either on a single device or multiple devices, call the identify API with your external user ID:

SwrveSDK.identify(<external_user_id>, (error) => {
    if(error){
       /** handle error*/
    }
    /** proceed with your application */
});

If the call fails, the user’s activity is not linked to an existing user ID in Swrve’s backend system, which might affect reporting and audiences where the user is logging in on multiple devices. We recommend not queuing or sending events until the identify call completes.


In-app messages

Swrve’s in-app messages campaigns are available as soon as you complete the basic integration described above. These features enable you to send personalized messages to your app users while they’re using your app. For more information, see Intro to in-app messages.

To test in-app messages in your app, you need to first create the campaign in Swrve. For more information, see Creating in-app messages.


Embedded campaigns

Swrve’s embedded campaigns give you complete control over how you deliver, handle, and display content on your app, while still letting you use our powerful audience targeting and event triggering system to deliver the campaign. This opens up scenarios where you can deliver JSON to your application, targeted to specific users, triggered by specific situations, like a campaign, and then use this JSON to custom render a visual in your own application code. For more information see Embedded campaigns. To implement embedded campaigns in your integration, pass the embeddedMessageConfig config object as part of inititalization. For example:

/** create your embedded callback */
const embeddedConfig = {
       embeddedCallback: (
          message: ISwrveEmbeddedMessage,
          personalizationProperties: IDictionary,
       ): void => {
          console.log(`embedded campaign with data: ${message.data} and personalization properties:     
          ${JSON.stringify(personalizationProperties)}`); 
            },
    } as ISwrveEmbeddedMessageConfig;

/** add it to your config on init */
SwrveSDK.initWithConfig({
   appId: <app_id>,
   apiKey: "<web_api_key>",
   externalUserId: "<external_user_id>",
   embeddedMessageConfig: embeddedConfig,
});

To use Swrve’s tracking, there are methods you can call within the embeddedCallback inside embeddedMessageConfig. Use these methods to send impression and click events for your own embedded campaigns and make use of Swrve’s targeting, segmentation, and goal tracking. For example:

const embeddedConfig = {
      embeddedCallback: (
         message: ISwrveEmbeddedMessage,
         personalizationProperties: IDictionary,
      ): void => {
        
         /** if you want to track an impression event */ 
         SwrveSDK.embeddedMessageWasShownToUser(message); 
                
         /** The message object returns a list of strings representing the button options. */ 
         /** In this example, we are taking out the first button from the list and sending a click event */ 
         var buttonName = message.buttons[0]; 
         SwrveSDK.embeddedMessageButtonWasPressed(message, buttonName);
       },
} as ISwrveEmbeddedMessageConfig;

Embedded campaign personalization

Swrve provides built-in personalization support for embedded campaigns. Personalization in any kind of triggered campaign uses a set of custom properties you’ve implement in your app and then configured for realtime personalization in Swrve. For information about configuring these properties, see Manage user properties or contact your CSM at support@swrve.com. Once configured, the properties are immediately available for use in your embedded campaigns.

The Swrve SDK has direct access to the most recent version of the realtime user properties values in Swrve. When your app makes an embedded campaign callback, the contents of the personalizationProperties argument in the embedded message include the realtime user properties retrieved during the process of triggering the campaign.

Since the format of embedded campaigns depends on how you configured your app (for example, you might use JSON, XML, plain text), Swrve does not parse and process your embedded campaign content. Although the campaign editor lets you select realtime properties for personalization, it is your responsibility to inject the properties as part of your embedded campaign integration. To help make this process easier for you, we have provided the getPersonalizedEmbeddedMessageData API.

const embeddedConfig = {
     embeddedCallback: (
      message: ISwrveEmbeddedMessage,
      personalizationProperties: IDictionary,
     ): void => {
        var resolvedMessageData = SwrveSDK.getPersonalizedEmbeddedMessageData(message, personalizationProperties);
     },
} as ISwrveEmbeddedMessageConfig;

Message center campaigns

Use the following call to access campaigns that have the message center flag set in the Swrve dashboard:

const campaigns = SwrveSDK.getMessageCenterCampaigns();
campaigns.forEach((campaign) => {
    // custom campaign handling
});

If you want to control when the message is shown, there is a showCampaign method. For example:

const campaigns = SwrveSDK.getMessageCenterCampaigns();
SwrveSDK.showCampaign(campaigns[0]);

In-app message button focus style

The SDK includes the functionality to control the appearance of in-app message buttons when they are in focus. To change the button focus style, provide the related CSS attributes in the config:

SwrveSDK.createInstance({
    ...
    inAppMessageButtonStyle: {
        border: "none",
    },
    inAppMessageButtonFocusStyle: {
        border: "5px solid red",
    },
});

Another approach is to use Swrve’s resource A/B testing feature to test different button focus styles. Specify a resource ID and set the attributes for the given resource in the Swrve dashboard.

SwrveSDK.createInstance({
    ...
    inAppMessageButtonStyle: "tv.demoapp.iambutton.style",
    inAppMessageButtonFocusStyle: "tv.demoapp.iambutton.focus.style",
});

Sending events

The Swrve SDK automatically sends certain events and also enables you to track user behavior by sending custom events. (For a list of default Swrve events, see Segment and audience filters, Events.) In turn, you can use app-generated events to trigger in-app messages, while both app- and server-generated events help you define segments and perform in-depth analysis.

Custom events

To send a custom event, include the below example in a method where you want to send an event to Swrve.

SwrveSDK.sendEvent("custom.event_name");

Requirements for sending custom events:

  • Do not send the same named event with different case. For example, if you send tutorial.start, then ensure you never send Tutorial.Start.
  • Use a period (.) in your event names to organize their layout in the Swrve dashboard. Each ‘.’ creates a new branch in the Event name column of the Events report, and groups your events so they are easy to locate.
  • Do not send more than 1000 unique named events.
  • Do not add unique identifiers to event names. For example, Tutorial.Start.ServerID-ABDCEFG
  • Do not add timestamps to event names. For example, Tutorial.Start.1454458885
  • Do not use the swrve.* or Swrve.* namespace for your own events. This is reserved for Swrve use only. Custom event names beginning with Swrve. are restricted and cannot be sent.

Event payloads

You can add and send an event payload with every event. This allows for more detailed reporting around events and funnels.

Notes on associated payloads:

  • The associated payload should be a dictionary of key/value pairs; it is restricted to string and integer keys and values.
  • There is a maximum cardinality of 500 key-value pairs for this payload per event. This parameter is optional, but only the first 500 payloads are displayed in the dashboard. The data is still available in raw event logs.
  • If you want to use event payloads to target your campaign audiences, you can configure up to 10 custom events with a maximum of 20 payloads per event for audience filtering purposes. For more information, see Targeting your audience by event payloads.
SwrveSDK.sendEvent("custom.event_name", {
    key1: "value1",
    key2: "value2",
});

For example, if you want to track when a user starts the registration process, it might make sense to send an event named registration.start and add a payload time that captures how much time it took the user to complete the registration.

SwrveSDK.sendEvent("registration.start", {
    time: "300",
    step: "5",
});

Custom user properties

The Swrve SDK sends certain user properties by default and also enables you to assign custom properties to update the user’s status. (For a full list of the default user properties, see Assigning user properties.) When configuring custom properties for your OTT platform, the Swrve SDK only supports string values.

For example, you could create a custom user property called premium, and then target non-premium users and premium users in your campaigns.

Example of group of user properties

SwrveSDK.sendUserUpdate({
    premium: "true",
    level: "12",
    balance: "999",
});

Example of date-typed user property

Use the Date object to send a DateTime user property; for example, the current date at the time of a user purchase:

SwrveSDK.sendUserUpdate({
    last_purchase: new Date().toISOString(),
});

Virtual economy events

To ensure virtual currency events are not ignored by the server, make sure the currency name configured in your app matches exactly the Currency Name you enter in the App Currencies section on the App Settings screen (including case-sensitive). If there is any difference, or if you haven’t added the currency in Swrve, the server will ignore the event and return an error event called Swrve.error.invalid_currency. Additionally, the ignored events are not included in your KPI reports. For more information, see Add your app.

If your app has a virtual economy, send the purchase event when users purchase in-app items with virtual currency.

var item = "some.item";
var currency = "gold";
var cost = 99;
var quantity = 1;
SwrveSDK.sendPurchaseEvent(item, currency, cost, quantity);

Send the currency given event when you give users virtual currency. Examples include initial currency balances, retention bonuses and level-complete rewards.

var givenCurrency = "gold";
var givenAmount = 99;
SwrveSDK.sendCurrencyGiven(givenCurrency, givenAmount);

Resource A/B testing

Integrating Swrve’s resource A/B testing functionality enables you to use Swrve to test how users respond to changes to the native app content. For more information about resource A/B testing, see Intro to resource A/B testing.

To get the latest version of a resource from Swrve using the Resource Manager, use the following:

var resourceManager = SwrveSDK.resourceManager()
var welcomeString = resourceManager.getAttributeAsString("new_app_config", "welcome_text", "Welcome!");

Or you can use the Swrve Resource instance API:

var resource = SwrveSDK.resourceManager().getResource("my.screen");
var welcomeString = resource.getAttributeAsString("welcome_text", "Welcome!");
var textSize = resource.getAttributeAsNumber("text_size", 14);

If you want to be notified whenever resources change, you can add a callback function as follows:

SwrveSDK.onResourcesLoaded = (resources) => {
    // Callback functionality
};

Testing your integration

After you’ve completed the above, the next step is to test the integration. For more information, see Testing your integration.


Upgrade instructions

If you’re moving from an earlier version of the Smart TV SDK to the current version, see the Smart TV SDK upgrade guide for upgrade instructions.