Last modified May 17, 2023 by Shelly Wolfe

Roku

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 native Roku SDK enables your app to use all of these features on the Roku OTT platform. This guide contains all the information you need to integrate the SDK into your Roku TV channel.

Requirements

  • The Swrve Roku SDK supports Roku firmwares versions 9.2 and later.
  • The App ID and API Key for your Swrve app. This information is available on the Integration Settings screen (on the Settings menu, select Integration settings).

Installing the SDK

Step 1: Download the SDK from the GitHub public repository or download a .zip file of the latest Roku SDK.

Step 2: Copy the SwrveSDK folder into your project’s source/ folder, at the same level as your Main file.

Step 3: Copy the SwrveComponents folder into your components/ folder.


SDK Setup

Step 1: Set up the Swrve config object. Replace <Your ID> and <Your Key> with your app ID and API key.

  • Option 1: Set up the config directly in the SwrveNode.brs file.
  • Option 2: Don’t make any changes to SwrveNode.brs file and instead use the configuration parameter to set the config values directly in your scene. For example:
    function init()
       m.SwrveNode = m.top.findNode("SwrveNodeId")
       cfg = {
        	 appID: "your id",
             apiKey: "your key",
        }
       m.SwrveNode.configuration = cfg
       m.SwrveNode.startSwrve = true
    end function

Note: For additional configuration parameters, see below.

Step 2: If you haven’t already done so, in your Main.brs file, create a global instance from the screen element:

Example:

Sub RunUserInterface(args as Dynamic)
    screen = CreateObject("roSGScreen")
    port = CreateObject("roMessagePort")
    screen.SetMessagePort(port)    
   
    m.global = screen.getGlobalNode()  
    m.global.id = "GlobalNode"     
       
    scene = screen.CreateScene("HomeScene")
    m.scene = scene    
    screen.Show()
End Sub

Step 3: In your Main Scene XML file, add the following script tags inside the component tag:

<script type="text/brightscript" uri="pkg:/source/SwrveSDK/SwrveSDK.brs" />
<script type="text/brightscript" uri="pkg:/source/SwrveSDK/SwrveResourceManager.brs" />
<script type="text/brightscript" uri="pkg:/source/SwrveSDK/SwrveUtils.brs" />
<script type="text/brightscript" uri="pkg:/source/SwrveSDK/SwrveConstants.brs" />
<script type="text/brightscript" uri="pkg:/source/SwrveSDK/SwrveStorageManager.brs" />
<script type="text/brightscript" uri="pkg:/source/SwrveSDK/SwrveProduct.brs" />
<script type="text/brightscript" uri="pkg:/source/SwrveSDK/SwrveReward.brs" />

Step 4:  Add the SwrveNode as the last child to your Main Scene XML file.

<SwrveNode id="SwrveNodeId"/>

Step 5: To start the Swrve client, in your Main Scene.brs file, add the following code to the init function.

m.SwrveNode = m.top.findNode("SwrveNodeId")
m.SwrveNode.startSwrve = true

Step 6: To use the Swrve help functions from a scene graph component, in the component’s XML, add the following script tags:

<script type="text/brightscript" uri="pkg:/source/SwrveSDK/SwrveSDK.brs" />
<script type="text/brightscript" uri="pkg:/source/SwrveSDK/SwrveResourceManager.brs" />
<script type="text/brightscript" uri="pkg:/source/SwrveSDK/SwrveUtils.brs" />

Step 7: You can use the SwrveSDK class directly or create an instance of it as follows:

m.swrveSDK = SwrveSDK()

For example:

m.swrveSDK = SwrveSDK()

payload = { key1: "value1" }
m.swrveSDK.SwrveEvent( "simple_event", payload)

Or

payload = { key1: "value1" }
SwrveSDK().SwrveEvent( "simple_event", payload)

Configuration parameters

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.
Parameter Presence Description
apiKey Required The API key for your Swrve app.
appID Required Your Swrve app ID.
logLevel Optional
Used for debug logs, level ranges are:
  • off – 0
  • error – 1
  • warn – 2
  • info – 3
  • debug – 4
  • verbose – 5 or higher
newSessionInterval Optional Interval after which a new launch is considered as a new session. Default is 30 seconds. For information on how to change the default setting, see How do I configure the new session interval?
stack Optional String used to target EU or US data storage. The default endpoint is us. Specify eu if your app uses European data storage.
appVersion Optional By default Swrve will read the application version for roAppInfo.
By default, the Swrve Roku SDK enables you to track important metrics and run in-app message campaigns. To make use of additional Swrve features, complete the following sections as required.

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, set a callback for the identify API:

SwrveSetIdentifyExternalIDCallback(callback as String)

For example:

SwrveSDK().SwrveSetIdentifyExternalIDCallback("identifyCallbackResponse")
function identifyCallbackWithResponse(callbackWrapper as object)
        data = callbackWrapper.getdata()
end function

Then call the identify API with your external user ID:

SwrveIdentifyExternalID(external_user_id as String)

For example:

SwrveSDK().SwrveIdentifyExternalID("external_user_id")

The data returned is an associative array with two key-value properties:

status: string value which can have the following properties

  • new_external_id – Identify successful with first occurrence of that external_user_id on that app recorded in Swrve.
  • existing_external_id_with_matching_swrve_id – Identify successful with the same user ID on an already identified third party external user ID.
  • existing_external_id – Identify successful with different user with a different user ID originally identified with.
  • Other error messages – In the case of a network failure or invalid parameter, we will forward the message to you so you may take the appropriate action.

swrve_id: which is the swrve_user_id

  • If we haven’t identified the user before, it will return the swrve_id sent up.
  • If we have, it will return the swrve_id on record for that user.

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 message campaigns.

In-app message deeplinks

When creating in-app messages in Swrve, you can configure message buttons to direct users to perform a custom action when clicked. For example, you might configure a button to direct the app user straight to the app store to provide a rating. At present, Roku does not support the concept of URL schemes or opening a URL, so if you want to use deeplinks in your in-app messages, you need to implement your own custom callback.

For Roku, the main scene of your channel owns the in-app message screen object, so you must use the main scene to set a custom callback function, as shown below.

SwrveSetCustomCallback(callback as String)

For example:

SwrveSDK().SwrveSetCustomCallback("customActionCallback")

Next, declare and define your custom callback method:

Function customActionCallback(callbackWrapper as Object)
    'callbackWrapper.GetData() will contain the string with the 
    'deeplink of the action that 
    'was selected, such as roku://LinkToSpecificPage.
End function

In-app message custom button focus

When creating in-app messages in Swrve, you can override custom focus options for in-app message buttons.

For Roku, the main scene of your channel owns the in-app message screen object, so you must use the main scene to set a custom button focus callback function, as shown below.

SwrveSetCustomButtonFocusCallback("customButtonFocusCallback")

For example:

SwrveSDK().SwrveSetCustomButtonFocusCallback("customButtonFocusCallback")

Next, declare and define your custom callback method:

function customButtonFocusCallback(callback as Object)
    'as an example we scale the focused button here and remove the default focus white background image
    buttonData = callback.GetData()
    for each button in buttonData.buttons
       'remove default background
        button.focusBitmapUri = " " 
        if button.hasFocus()
            button.scale = [1.11,1.11] 
        else
            button.scale = [1,1]
        endif
    end for
end function

Sending events

The Swrve SDK automatically sends certain events and also lets you 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 from your Brightscript file, use the following structure:

SwrveEvent(eventName as String, payload as Object)

Return: void

Parameters

  • eventName – Name of the event. Can’t contain spaces or be nil.
  • payload – Optional and has to be an associative array (dictionary) object.
payload = { key1: "value1" }
SwrveSDK().SwrveEvent("Simple_event", payload)

Requirements for sending custom events:

  • Do not send the same named event with different case. For example, if you send registration.start, then ensure you never send Registration.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, Registration.Start.ServerID-ABDCEFG
    • Do not add timestamps to event names. For example, Registration.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

As shown in the above example, 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 and for audience filtering.
  • 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.

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.

payload = { time: "300" } 
SwrveSDK().SwrveEvent("registration.start", payload)

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 Roku, the Swrve SDK only supports string values.

SwrveUserUpdate(attributes as Object)

Return: void

Parameters

  • attributes – Associative array of custom attributes.
SwrveSDK().SwrveUserUpdate({"myAttribute" : "12" })

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().SwrveUserUpdate({"premium" : "true", "level" : "12", "balance": "999"})

Example of single date-typed user property

Use the roDateTime object to send a date-time string (ISO) user property; for example, the current date at the time of a user purchase:

date = CreateObject("roDateTime")
SwrveSDK().SwrveUserUpdateWithDate("last_purchase", 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.

SwrvePurchaseEvent(quantity as Integer, itemName as String, cost as Float, currency as String)

Return: void

Parameters

  • quantity – Quantity purchased, as integer.
  • itemName – Name of the item purchased.
  • cost – Cost for a single item.
  • currency – Currency name, as set up on the Swrve Dashboard.

Example

SwrveSDK().SwrvePurchaseEvent(1, "purchased_item", "99", "gold")

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

SwrveSDK().SwrveCurrencyGiven("gold", 25)

In-app purchase events

If your app has in-app purchases (IAPs), send the IAP event when a user purchases something with real money. For Roku, Swrve does not currently validate in-app purchases.

Notify Swrve when an in-app purchase occurs as follows:

SwrveProduct(name as String, ID as String, cost as Float, quantity as Integer)

Return: a product object (as associative array)

Parameters

  • name – Name of the product.
  • ID – Identifier of the product.
  • cost – Cost for a single item.
  • quantity – Quantity of this product purchased.

AddSwrveReward(rewardsObject as Object, type as String, name as String, amount as Float)

Return: void

Parameters

  • rewardsObject – Name of the reward.
  • type – Identifier of the reward.
  • name – Name given to the specific reward.
  • amount – Quantity rewarded.

SwrveIAPWithoutReceipt(product as Object, rewards as Object, localCurrency as String)

Return: void

Parameters

  • product – Product object you created.
  • rewards – Rewards dictionary you created.
  • localCurrency – Virtual currency as a string.

Example

In your Scene XML file, add the following script tags inside the component tag:

<script type="text/brightscript" uri="pkg:/source/SwrveSDK/SwrveProduct.brs" /> 
<script type="text/brightscript" uri="pkg:/source/SwrveSDK/SwrveReward.brs" />

In your Scene .brs file:

product = SwrveProduct("purchased_item1234", "purchased_item1234", 0.2, 1)
rewards = SwrveReward()
rewards = rewards.AddSwrveReward(rewards, "currency", "gold", 25)
rewards = rewards.AddSwrveReward(rewards, "item", "bundle_item02", 200)
SwrveSDK().SwrveIAPWithoutReceipt(product, rewards, "currency")

Shutting down the SDK

The Swrve Roku SDK includes the following method to let you completely shut down the SwrveSDK, clearing all temporary data and shutting off listeners. In case of shutdown, any events that are not sent are saved to persistent storage and sent to Swrve the next time the same user starts a new session.

SwrveSDK().SwrveShutdown()

Resource A/B testing

Integrating Swrve’s resource A/B testing functionality lets you 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, complete the following:

Step 1: In your component, set up an observer and your callback function to receive notifications that the SDK has received and processed new campaigns or resources:

SwrveSetNewResourcesCallback("OnNewResources")

Step 2: Call the resource manager from anywhere:

resource = SwrveSDK().SwrveGetResourceManager().SwrveResource("resource_name")

You can then get a resource from the manager using the SwrveResource method.

Step 3: Add the following callback function:

Function OnNewResources()
     if getSwrveNode().resourcesAndCampaigns
        resource = SwrveSDK().SwrveGetResourceManager().SwrveResource("resource_name")
     end if
End Function

SwrveResource("resource_name") returns the associated resource with the resource name in parameters. Use the following attribute methods to return a resource defined in the Swrve Dashboard.

Method Attribute Value
Attribute as String attributeAsString(“AttributeName”,”defaultValue”) Default is an empty string.
Attribute as Integer attributeAsInt(“AttributeName”, defaultValue as Int) Default is 0.
Attribute as Float attributeAsFloat(“AttributeName”, defaultValue as Float) Default is 0.0.
Attribute as Boolean attributeAsBoolean(“AttributeName”, defaultValue as Boolean) Default is false.
Attribute as Color attributeAsColour(“AttributeName”, defaultValue as String) Default is 0xFFFFFF.

If you want to view the old and new values when resources change, you can add a callback function as follows:

Step 1: Make a call to Swrve from your components:

SwrveSDK().SwrveGetUserResourcesDiff("OnResourcesDiff")

Step 2: Set up the callback function:

Function OnResourcesDiff()
'Usable object is getSwrveNode().resourcesDiffObjectReady
End Function

Result:

The result is an array that contains two entries: old and new dictionaries of resources.

{
    "new": {
        "myResource1": {
            "labelText": "New Value",
        },
        "myResource2": {
            "labelText": "New Value",
        }
    },
    "old": {
        "myResource1": {
            "labelText": "Previous Value",
        },
        "myResource2": {
           "labelText": "Previous Value",
        }
    }
}

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 Roku SDK to the current version, see the Roku SDK upgrade guide for upgrade instructions.