Singular SDK Integration for Cordova

 

The Singular SDK is available as a plug-in for Cordova. The instructions below show you how to integrate Singular into your Cordova app.

Prerequisites

  • This article assumes you have a functional Cordova app.
  • To initialize the SDK, you need your Singular SDK Key and SDK Secret. You can get them in the Singular platform at "Developer Tools > SDK Integration > SDK Keys".

Adding the Singular Plugin

To add the Singular plugin to your Cordova project, run the following:

cordova plugin add singular_cordova_sdk

Ionic

If you are using Ionic:

  1. Install the Singular SDK plugin:

    $ ionic cordova plugin add singular_cordova_sdk
  2. In your main ts file, declare a window variable:

    declare var cordova;
  3. Now you can use the Singular plugin directly from Cordova:

    import {Component} from '@angular/core';
    import {Platform} from '@ionic/angular';
    declare var cordova;
    ...
    
    export class HomePage {
    constructor(public platform: Platform) {
    this.platform.ready().then(() => {
    
        // Add code to initialize the Singular SDK here
    
    }); 
    }}

Initializing the SDK (Required)

The Singular SDK initialization code should be called every time your app is opened. It is a prerequisite to all Singular attribution functionality. It also sends a new user session to Singular (sessions are used to calculate user retention).

To initialize the Singular SDK:

  1. Create a SingularConfig object. The object contains your Singular SDK Key and Secret.
  2. Configure optional settings if you want your app to support deep links and/or SKAdNetwork (see Adding Deep Linking Support and Adding SKAdNetwork Support below).
  3. META Install Referrer Attribution Support

    Required SDK configuration to enable "Meta Install Referrer" attribution:

    1. Provide your Facebook App Id in the Singular Configuration Object.
      // To enable META Install Referrer
      singularConfig.withFacebookAppId("INSERT YOUR FACEBOOK APP ID HERE");
    Where can I find an app's Facebook App ID?
  4. Initialize the SDK using the SingularConfig object.

Code example (with optional settings commented out):

// Create the configuration object
var singularConfig = new
cordova.plugins.SingularCordovaSdk.SingularConfig("<SDK KEY>", "<SDK SECRET>");

/*
// Optional: Enable deep linking (requires additional setup steps, see guide)
var linkHandler = function(data){
var deeplink = data.deeplink;
var passthrough = data.passthrough;
var isDeferred = data.isDeferred;
// Add link handling logic here
}
singularConfig.withSingularLink(linkHandler);
*/

/*
// To enable META Install Referrer
singularConfig.withFacebookAppId("INSERT YOUR FACEBOOK APP ID HERE");
*/
/* // Optional: Enable SKAdNetwork (in Managed Mode, see guide for more options) singularConfig.withSkAdNetworkEnabled(true); */ // Initialize Singular cordova.plugins.SingularCordovaSdk.init(singularConfig);

Sending the User ID to Singular (Optional)

You may send your internal User ID to Singular using a Singular SDK method.

Note: If you use Singular's Cross-Device solution, you must collect the User ID across all platforms.

  • The User ID can be any identifier and should not expose PII (Personally Identifiable Information). For example, you should not use a User's email address, username, or phone number. Singular recommends using a hashed value unique only to your first-party data.
  • The User ID value passed to Singular should also be the same internal User ID you capture across all platforms (Web/Mobile/PC/Console/Offline).
  • Singular will include the User ID in user-level exports, ETL, and Internal BI postbacks (if configured). The User ID is first-party data, and Singular does not share it with other parties.
  • The User ID value, when set with the Singular SDK Method, will persist until it is unset using the unsetCustomUserId method or until the app is uninstalled. Closing or restarting the app does not unset the User ID.

To set the User ID, use the setCustomUserId method. To unset it (for example, if the User "logs out" of the account), call unsetCustomUserId.

Note: If multiple Users use a single device, we recommend implementing a logout flow to set and unset the User ID for each login and logout.

If you already know the user ID when the app opens, call setCustomUserId before initializing the Singular SDK. This way, Singular can have the User ID from the first Session. However, the User ID is typically unavailable until the User registers or performs a login. In that case, call setCustomUserId after the registration flow is complete.

SingularCordovaSdk.setCustomUserID Method
Description Send the user ID to Singular.
Signature SingularCordovaSdk.setCustomUserId(String customUserId)
Usage Example
SingularCordovaSdk.setCustomUserId('CustomUserId');
SingularCordovaSdk.unsetCustomUserID Method
Description Unset the user ID that has been sent to Singular.
Signature SingularCordovaSdk.unsetCustomUserId()
Usage Example
SingularCordovaSdk.unsetCustomUserId();

Optional: Custom User ID Device Mapping

Important: This advanced Enterprise feature is only available in exceptional cases. Please consult with one of Singular’s Solution Engineers before implementing it.

Singular can receive additional mobile event tracking data via a server-to-server integration. To utilize this feature, you must map the User ID to Singular’s Mobile Device tracking identifier.

Note: Call this method as soon as possible after initializing the Singular SDK or once you have the User ID.

SingularCordovaSdk.setDeviceCustomUserId Method
Description Sets the Custom User Id the same as login and maps it to Singular’s tracking identifier.
Signature SingularCordovaSdk.setDeviceCustomUserId(String customUserId)
Usage Example
SingularCordovaSdk.setDeviceCustomUserId('CustomUserId');

Tracking Events (Non Revenue)

In addition to sending user sessions to Singular (through initializing the SDK), you can also send user events. Data about in-app events helps Singular analyze the performance of your user acquisition campaigns and measure KPIs.

For example, your organization may want to collect data about user logins, registrations, tutorial completions, or leveling up in a gaming app.

To send events to Singular, use the eventWithArgs method. Give the event a name and add any attributes you want to track.

// Example: Report an event called View Product with event attributes
cordova.plugins.SingularCordovaSdk.eventWithArgs(
  'ViewProduct', // Event name
  {
    // Event attributes
    productID:"123",
    productCategory:"Outerwear"
  }
)

Tracking Revenue

To let Singular track how much revenue your app makes from in-app purchases, report IAP events to Singular.

We recommend using the eventWithArgs method and passing the IAP object as an event attribute. Singular uses the IAP object to validate the purchase and detect fraudulent purchases so they do not skew your revenue metrics (see the In-App Purchase Validation FAQ).

If you are using the https://github.com/j3k0/cordova-plugin-purchase library, you can use the following code:

store.when('product123 verified', onProductVerified);
product.verify();

function onProductVerified(product){
  const iap = new cordova.plugins.SingularCordovaSdk.SingularIAP(product);
  cordova.plugins.SingularCordovaSdk.eventWithArgs('IAP_EVENT', iap)
}

Sending Custom Revenue

If you cannot send the IAP object to Singular, an alternative is to use the customRevenue method, which accepts an event name, a currency code, and the purchase amount.

Example:

cordova.plugins.SingularCordovaSdk.customRevenue(
  customEventName, // E.g. "purchase"
  currencyCode, // E.g. "USD"
  purchaseAmount // E.g. 3.2
);

Note: Pass currency as a three-letter ISO 4217 currency code, e.g., "USD," "EUR", "INR".

Hybrid Event Tracking (Advanced)

Singular recommends sending all events and revenue through the Singular SDK integrated into your app. However, Singular can collect events and revenue from other sources.

Any event NOT sent from the Singular SDK must comply with Singular's Server-to-Server Event documentation requirements and provide the matching device identifier to correctly attribute an event.

Important:

Discrepancies will occur if device identifiers used on Server-to-Server event requests do not have a matching device identifier in Singular. Be aware of the following possibilities:

  • If an event request is received "before" the Singular SDK has recorded the device identifier, from an App Session, then the event request will be considered the "first session" for the unknown device, and Singular will attribute the device as an organic attribution.
  • If the Singular SDK did record a device identifier, but the Singular SDK identifier differs from the device identifier specified in the Server-to-Server Event request then the event will be attributed incorrectly.

Hybrid Event Tracking Guides

Sending Events from an Internal Server

Singular can collect data about revenue from your Server to help analyze the performance and ROI of your campaigns.

Requirements:

  • From an in-app Registration or Login Event, capture and pass the device identifiers and store this data with the User ID on your server. Because device identifiers may change for a user, be sure to update the identifiers when a user generates an app session. This guarantees the server-side event will be attributed to the correct device.
  • Server-side events are platform specific and should only be sent with the device identifier matching the device platform (e.g., IDFA or IDFV for iOS devices).
  • You can use the Singular Internal BI postback mechanism to push an event in real time to your internal endpoint so that you can update the data set on the server side. See the Internal BI Postback FAQ.
  • Review the "Tracking Revenue" section in the Server-to-Server Integration guide for details.
Sending Events from a Revenue Provider
Third-party providers like RevenueCat or adapty can provide Purchase and Subscription Revenue to Singular.

Follow the links below for details on how to enable these partners.

Sending Events from Segment

To enable Segment to send events to Singular, in parallel with the Singular SDK, you must add a "Cloud-Mode" Destination in Segment. Follow our guide HERE.

Tracking Ad Revenue Attribution

You can use the Singular plugin to set up ad revenue attribution (see the Ad Revenue Attribution FAQ).

To set up ad revenue attribution:

  1. Add the appropriate code snippet to get ad revenue information from the mediation platform you use for ad revenue data. See code snippets in our Android SDK documentation.

Note: Pass currency as a three-letter ISO 4217 currency code, e.g., "USD," "EUR", "INR".

Report ad revenue events to Singular using the following code
  1. Initialize the SingularAdData object with the relevant data
  2. Report the data to Singular
Javascript
const adData = new cordova.plugins.SingularCordovaSdk.SingularAdData(
   mediationPlatform,
   currencyCode, // e.g., "USD"
   revenueAmount)

cordova.plugins.SingularCordovaSdk.adRevenue(adData);

Adding Deep Linking Support

Deep links are links that open the app on the user's phone and send the user directly to a specific page or user experience instead of just the app's main widget.

Deep links are usually used in retargeting campaigns, aimed at users who already have the app on their phone but may not have engaged with it for a while.

Singular supports deep linking through Singular Links (see the Singular Links FAQ).

To use Singular Links in your app:

  1. Follow the instructions in Singular Links Prerequisites.
  2. For Android, add this code to the main activity:

    import singular_cordova_sdk.SingularCordovaSdk;
    
    @Override
    public void onNewIntent(Intent intent) {
      SingularCordovaSdk.handleNewIntent(intent);
    }

    For iOS, add this code to your AppDelegate:

    #import "SingularCordovaSdk.h"
    
      - (BOOL)application:(UIApplication*)application
      didFinishLaunchingWithOptions:(NSDictionary*)launchOptions
      {
         self.viewController = [[MainViewController alloc] init];
         [SingularCordovaSdk setLaunchOptions: launchOptions];
         return [super
      application:application didFinishLaunchingWithOptions:launchOptions];
      }
    
      - (BOOL)application:(UIApplication *)application
      continueUserActivity:(NSUserActivity *)userActivity
      restorationHandler:(void (^)(NSArray<id> * _Nullable))restorationHandler{
       [SingularCordovaSdk startSessionWithUserActivity:userActivity];
       return
      YES;
      }
  3. Before initializing the Singular SDK in your code, add .withSingularLink to the Singular config object and specify your link handler function:

    var singularConfig = new
      cordova.plugins.SingularCordovaSdk.SingularConfig("<SDK KEY>", "<SDK SECRET>");
    
    var linkHandler = function(data){
      var deeplink = data.deeplink;
      var passthrough = data.passthrough;
      var isDeferred = data.isDeferred;
      // Add link handling logic here
    }
    
    singularConfig.withSingularLink(linkHandler);
    
    cordova.plugins.SingularCordovaSdk.init(singularConfig);

Adding SKAdNetwork Support

The Singular plugin supports the SKAdNetwork framework. You can enable SKAdNetwork tracking for your app using the configuration options below.

Managed Mode (Recommended)

In managed mode, Singular manages the SKAdNetwork conversion value for you automatically, based on a conversion model of your choice that you can set up in the Singular platform.

To learn more, see Understanding Singular's Conversion Value Management and the SKAdNetwork Model Configuration FAQ. For a step-by-step guide to using SKAdNetwork with Singular, see How to Get Started with SKAdNetwork.

To enable SKAdNetwork in managed mode, use the following code:

var singularConfig = new
  cordova.plugins.SingularCordovaSdk.SingularConfig("<SDK KEY>", "<SDK SECRET>");

// Enable SKAdNetwork (in managed mode by default)
singularConfig.withSkAdNetworkEnabled(true);

cordova.plugins.SingularCordovaSdk.init(singularConfig);

Manual Mode

If you already have your own strategy and tools for managing the SKAdNetwork conversion value, you can use SKAdNetwork in manual mode.

To enable SKAdNetwork in manual mode, use the following code:

var singularConfig = new
  cordova.plugins.SingularCordovaSdk.SingularConfig("<SDK KEY>", "<SDK SECRET>");

// Enable SKAdNetwork
singularConfig.withSkAdNetworkEnabled(true);

// Select SKAdNetwork manual mode
singularConfig.withManualSkanConversionManagement();

// Optional: define handler to track changes to the conversion value
var conversionHandler = function(updatedConversionValue){
  // Do something with updatedConversionValue
}

singularConfig.withConversionValueUpdatedHandler(conversionHandler);

// Initialize the Singular SDK
cordova.plugins.SingularCordovaSdk.init(singularConfig);

To update the conversion value use the following code:

cordova.plugins.SingularCordovaSdk.skanUpdateConversionValue(
  newConversionValue,
  function(isSuccess){
    // isSuccess == true if the update was successful
  }
)

To retrieve the current conversion value, use the following code:

cordova.plugins.SingularCordovaSdk.skanGetConversionValue(
  function(conversionValue){
    // Do something with conversionValue
  }
)

Other Options

Tracking Uninstalls

To let Singular track app uninstalls, send the APNS/FCM token to Singular using the following code:

Android:

cordova.plugins.SingularCordovaSdk.setUninstallToken(fcmToken)

iOS:

cordova.plugins.SingularCordovaSdk.setUninstallToken(apnsToken)

Creating Short Referrer Links

Use short links to transform long, parameter-filled Singular Links into shorter and more secure links that are convenient for sharing.

Typically, you will want to create short links dynamically so that your app's users can share them with friends to invite them to use the app.

To create a short link, you need:

  • A Singular Link that leads to your app download (see the Singular Links FAQ).
  • Any parameters you want to add to the link dynamically (see Tracking Link Parameters for the list of options).
  • The name and ID of the referring user, if you want to be able to track new app installs back to the user who shared the link.

To create short links use the following code:

cordova.plugins.SingularCordovaSdk.createReferrerShortLink(
    longLinkURL, 
    referrerName,
    referrerID,
    {
        // Tracking link parameters to add to the short link, e.g. "channel":"sms"
        param1: value1,
        param2: value2,
        ...
    },
    {
        onSuccess: function (shortLinkURL) {
        // Do something with shortLinkURL
        },
        onError: function (error) {
        // Handle error
        }
    }
)

Complying with Data Privacy Laws

Singular provides privacy-safeguarding functionality to help you cooperate with any partners who may be complying with consumer privacy laws such as GDPR and CCPA (California Consumer Privacy Act). These partners want to be notified if the end-user has consented to share their private information.

If you have implemented a way to ask users for consent to share their information, use the limitDataSharing method to notify Singular of the user's choice:

Use SingularCordovaSdk.limitDataSharing(false) to indicate that the user consented (opted in) to share their information.

Use SingularCordovaSdk.limitDataSharing(true) if the user did not consent.

Singular uses LimitDataSharing in "User Privacy Postbacks" as well as passing this information on to partners who require it in order to comply with relevant regulations. See "User Privacy and Limit Data Sharing" for more information.

Note: The use of the method is optional, but there may be attribution information that the partner will share with Singular only if specifically notified that the user has opted in.

SingularCordovaSdk.limitDataSharing Method
Signature SingularCordovaSdk.limitDataSharing(boolean shouldLimitDataSharing)
Description Notify Singular of user consent (opt-in) for sharing private data.
Usage Example
// User has opted into sharing data
cordova.plugins.SingularCordovaSdk.limitDataSharing(false);

Additional Methods for GDPR Compliance

The Singular SDK provides several methods to help you comply with GDPR policies and let Singular know about user consent or non-consent for tracking.

SingularCordovaSdk.trackingOptIn Method
Description Notify Singular of user consent (opt-in) for tracking.
Usage Example
cordova.plugins.SingularCordovaSdk.trackingOptIn();
SingularCordovaSdk.stopAllTracking Method
Description

Stop all tracking activities for this user on this app.

Note: Calling this method effectively disables the SDK, even after the app restarts (the state is persistent)! The only way to re-enable tracking is by calling resumeAllTracking().
Usage Example
cordova.plugins.SingularCordovaSdk.stopAllTracking();
SingularCordovaSdk.resumeAllTracking Method
Description Resume tracking for this user on this app.
Usage Example
cordova.plugins.SingularCordovaSdk.resumeAllTracking();
SingularCordovaSdk.isAllTrackingStopped Method
Description Check the tracking status for this user on this app. Returns true if tracking has been stopped using StopAllTracking() and not resumed.
Usage Example
cordova.plugins.SingularCordovaSdk.isAllTrackingStopped();