NAV Navbar
Swift Java JavaScript Ionic

Introduction

Welcome to SmartKarrot! Look up the features and SDKs you can integrate into your apps.

  1. Usage analytics
  2. App analytics
  3. Survey and feedback
  4. Rich push notifications
  5. Custom health score ratings
  6. Financial data

There are a number of different APIs you can use to integrate with a SmartKarrot Platform. But sometimes it’s difficult to know what each API is for and when to use it. This document explains the APIs that are available.

Probably the most well-known API format/structure is the REST API. As its name implies, it uses REST as a wrapper (point-to-point call) for API operations. Probably the bulk of our API traffic is from the REST API because it has become the de facto standard for microservices across industries.

To start with, we’ve got a series of APIs, about seven of them now. While they all achieve a similar purpose – in one sense – of accessing data from your application (user & event data to measure product and customer success) or from the third-party integrations that you use, but there are some key differences among them which are worth explaining. First, it’s important to note that all of these APIs operate identically across SmartKarrot.

The seven API’s that make up the SmartKarrot Platform are:

Usage Analytics

The APIs in this section are core to SmartKarrot Platform and are used to gather User, Device & Event Information. For example, through the use of these APIs we gather information about the events that are fired by users of your application along with the user and device information so that you can get a comprehensive understanding of the stickiness of your product for your users.

App Analytics

These are a set of default information related to your users behavior that our SDK captures on your behalf. For example, if you want to know the average session length of users for a given period of time, or your app page load performance or the users that visited your app in the last thirty seconds, then our SDK captures this analytics data out of the box for you.

Survey and Feedback

If you have integrated our Survey SDK, then you can send surveys (multiple input question) and pulses (single input question) to your end users or to your Key Stakeholders for your customer accounts.

Rich Push Notifications

Same as in the case of Survey & Feedback, you can send rich push notification to your end users or key stakeholders as and when you need to.

Custom Health Score Ratings

This push API helps you to send define custom health score parameters for your customers as well as define the rating standard for this custom parameters. In a way, you get the choice out of the box to measure your customer the way you have been measuring them till date on SmartKarrot Platform. Thereby, reduces the overload of learning and behavioral change on your part.

Financial Data

The financial information about your customer (ARR, MRR, Churn etc..) all form an integral part of gauging Customer and Product Success. So at SmartKarrot, we realized the need to have an push API in place through which you can send in your customer financial information that will help you understand the different financial metrices for each customer account.

Sandbox API

This per se is not an API in itself. But SmartKarrot platform’s in built APIs gives you the capability to test things on Sandbox mode before integrating it with your production environment on SmartKarrot.

Development Quickstart

Integrating the SmartKarrot API requires only four quick steps:

  1. Get your API keys.
  2. Integrate REST API.
  3. Add our SDK to your app.
  4. Configure the SmartKarrot integration.

Step 1: Get Your API Keys (AppId)

Add an app in the Settings section and find the API keys(AppID) under App details. Every app has two API keys: one for the sandbox and one for production. The sandbox key is used for development and testing, and the production one for live transactions.

Step 2: Integrate REST API

Get REST API Key

Get REST API Key from SmartKarrot Support Team (email: support@smartkarrot.com).

API

Welcome to the SmartKarrot API! SmartKarrot offers private REST API for its SaaS services. The API make it easier to quickly configure and integrate your Web app directly with our server.

The API supports Cross-origin resource sharing (CORS).

URL

The SmartKarrot API is available at:

Environment URL
Production https://api.smartkarrot.com/v4/

Authentication

SmartKarrot uses the Basic Authentication mechanism with an API key to authenticate requests. For example, if you API key is daced09f-8ade-48dc-b1d8-506204530ce3, you can log an event with a simple HTTP POST request:

curl -v -u apikey:daced09f-8ade-48dc-b1d8-506204530ce3 -H "Content-Type: application/json" -d '{"appId": "4ed062f1-fc38-4f32-a714-b63dc5399626","platform":"iOS","deviceId": "53e11019-8034-496b-a484-fa978918873c","loginMechanism" : "AUTH","bundleId": "com.smartkarrot.tasks","lastLoggedInUserId": "f1d0c16d-f9e0-4eb4-8739-45574c43f508","userId": "8f2dfb97-fe4b-49b3-a5d5-a671335cde00","sessionId": "234240-234-234-234-234-234237B891079-A302-4DDD-8860-2672B9682A3B","status": "Active","customerAccountId": "de8327c8-ece7-427a-ba8f-e4c7809ea716"}' 'https://api.smartkarrot.com/v4/usageanalytics/user'

Data Types

The SDK uses the following data types.

Type Description
String A simple quoted string, following standard JSON rules; see the JSON spec for details.
Integer A whole number, transmitted as a JSON number.
Boolean A JSON boolean, the literal string true or false.
Array A JSON array. Each element contains a payload that will be described.
Timestamp Time in UTC stored in the ISO 8601 format with millisecond precision. (Example: 2018-09-29T09:58:44.635Z)
UUID A UUID string. Preferably a version 4 UUID. Example: f30ccccf-54a8-49bf-b3e4-6eee274810ab.
Decimal A decimal value, encoded in a JSON string. The contents will be a series of digits, followed by an optional decimal point and additional digits.

Create or Update Customer Account

Use this endpoint to create a new customer account or update an existing one.

HTTPS Request

POST /usageanalytics/customer

Sample Request

{
  "appId": "4ed062f1-fc38-4f32-a714-b63dc5399626",
  "accountId": "de8327c8-ece7-427a-ba8f-e4c7809ea716",
  "name" : "SmartKarrot",
  "base64EncodedLogoImage" : "iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAYAAABXAvmHAAAAAXNSR0IArs4c6QAAAVlpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IlhNUCBDb3JlIDUuNC4wIj4KICAgPHJ",
  "status": "Active"
}

Request Body

Parameter Type Required Description
accountId String required The customer account ID in your system.
appId String required SmartKarrot App ID.
name String required Name of system customer account.
base64EncodedLogoImage String optional Image in base64 encoded string. The image size should be less than 3 MB.
status String required Enum: Active, Inactive

Sample Output

{
  "status": "SUCCESS"
}

Response Body

Log customer account response.

Parameter Type Description
status String Enum SUCCESS, ERROR, INVALID_INPUT

Update User Status

Use this endpoint to update user data when a user is using your app. A user can be a guest user, in which case, you can generate a random UUID for the user. If a user is logged in, use this endpoint to update the user in SmartKarrot.

HTTPS Request

POST usageanalytics/user

Sample Request

{
  "appId": "4ed062f1-fc38-4f32-a714-b63dc5399626",
  "platform":"iOS",
  "deviceId": "53e11019-8034-496b-a484-fa978918873c",
  "loginMechanism" : "AUTH",
  "bundleId": "com.smartkarrot.tasks",
  "lastLoggedInUserId": "f1d0c16d-f9e0-4eb4-8739-45574c43f508",
  "userId": "8f2dfb97-fe4b-49b3-a5d5-a671335cde00",
  "sessionId": "234240-234-234-234-234-234237B891079-A302-4DDD-8860-2672B9682A3B",
  "status": "Active",
  "customerAccountId": "de8327c8-ece7-427a-ba8f-e4c7809ea716"
}

Request Body

Parameter Type Required Description
bundleId String required Client unique id.(Android Package Name, iOS Bundle Id and Web Domain Name)
loginMechanism String required Enum 'AUTH', 'GUEST', If the user is in your system then send AUTH else GUEST.
userId String required User's unique identifier.
appId String required SmartKarrot App Id.
sessionId String optional Client session Id.
deviceId String optional Client device Id.
idempotencyId String required Unique key for the request, generating v4 UUID is recommended.
platform String required Enum: iOS, Android, Web
status String required Enum: Active, Inactive
customerAccountId String required The customer account ID in your system.

Sample Output

{
  "status": "SUCCESS"
}

Response Body

Log user response.

Parameter Type Description
status String Enum SUCCESS, ERROR, INVALID_INPUT

Step 3: Add our SDK to Your App

SmartKarrot provides iOS, Android and Web (JavaScript) SDKs.

# Run Script

APP_PATH="${TARGET_BUILD_DIR}/${WRAPPER_NAME}"

# This script loops through the frameworks embedded in the application and
# removes unused architectures.
find "$APP_PATH" -name '*.framework' -type d | while read -r FRAMEWORK
do
    FRAMEWORK_EXE_NAME=$(defaults read "$FRAMEWORK/Info.plist" CFBundleExecutable)
    FRAMEWORK_EXE_PATH="$FRAMEWORK/$FRAMEWORK_EXE_NAME"
    echo "Executable is $FRAMEWORK_EXE_PATH"

    EXTRACTED_ARCHS=()

    for ARCH in $ARCHS
    do
    echo "Extracting $ARCH from $FRAMEWORK_EXE_NAME"
    lipo -extract "$ARCH" "$FRAMEWORK_EXE_PATH" -o "$FRAMEWORK_EXE_PATH-$ARCH"
    EXTRACTED_ARCHS+=("$FRAMEWORK_EXE_PATH-$ARCH")
    done

    echo "Merging extracted architectures: ${ARCHS}"
    lipo -o "$FRAMEWORK_EXE_PATH-merged" -create "${EXTRACTED_ARCHS[@]}"
    rm "${EXTRACTED_ARCHS[@]}"

    echo "Replacing original executable with thinned version"
    rm "$FRAMEWORK_EXE_PATH"
    mv "$FRAMEWORK_EXE_PATH-merged" "$FRAMEWORK_EXE_PATH"

done

iOS App

You can install the SDK using CocoaPods or as a dynamic framework.

For installing using CocoaPods, add the line pod 'SmartKarrot-Core' to your Podfile and install it with pod install. Current version of the SDKs is 5.1.0.

If you want to add the SDK as a dynamic framework, download it.

  1. Add it to your Xcode project's Embedded Binaries.
  2. Select Build Phases, add a Run Script with shell as /bin/sh and script as given in the code section.

Android App

allprojects {
  repositories {
    // add this repository at the bottom of the repositories list
    maven { 
      url "https://s3.amazonaws.com/smartkarrot-android-repo/"
    }
  }
}

The Android SDK comes as a Java library. Installing it is simple. Just add the lines to the right to your project level build.gradle file.

Then add these lines to your App's build.gradle file:

implementation 'com.smartkarrot:usageanalytics:0.0.4.6'

If you are supporting android versions before Lollipop (21), you need to add this line in your app's build.gradle file: multidexEnabled true

More info here: Enabling Multidex

Proguard Configuration

If you are using proguard in your app, add this configuration in your proguard-rules.pro file:

-keep class com.smartkarrot.** { *; }

-keepclassmembers class com.smartkarrot.** { *; }

Web - JavaScript

Add the following code in head tag of your HTML page.

<script src="https://docs.smartkarrot.com/frameworks/web/v4/UsageAnalytics.js"></script>

Angular: Declare declare var UsageAnalytics; to access UsageAnalytics from angular component.

Hybrid - Cordova/PhoneGap/Ionic Plugin

  1. Download SmartKarrot Plugin, download.

  2. Add SmartKarrot plugin to your app.

    Cordova plugin add SmartKarrot

    After adding you will see an entry in config.xml

    <plugin name="SmartKarrot" spec="SmartKarrot" />

  3. Declare the cordova plugin in the app page where this has to be used.

declare let cordova:any;

Step 4: Configure the SmartKarrot Integration

The SmartKarrot SDK must be initialized before using any of its functions.

iOS App

Import the SDK with into AppDelegate.swift file with

import UsageAnalytics

Add this to your AppDelegate.swift file

UsageAnalytics.shared.configure(appId: "app-id", customerAccountId: "customer-account-id")

If you have a user Id available for the user of your app, you can configure the user Id together with the app Id with:

UsageAnalytics.shared.configure(appId: "app-id", userId: "user-id", customerAccountId: "customer-account-id")

Android App

Add this line to the onCreate method of your activity or Application class.

For MultiLevel App: UsageAnalytics.initWithCustomerAccount(context, appId, customerAccountId)

For SingleLevel App: UsageAnalytics.init(context, "app-id")

Web - JavaScript

Add the following javascript to your HTML page to initialize the SDK.

UsageAnalytics.configure("app_api_key", "customer-account-id")

Hybrid - Cordova/PhoneGap/Ionic Plugin

The plugin has to be initialized in the code after the view is loaded i.e. in the life cycle event ionViewDidEnter

ionViewDidEnter() { this.configureSmartKarrot(); }

configureSmartKarrot() { let appId = "your-app-id"; let userId = "your-app-user-id";

var successCallBack = function (successResult) { console.log(successResult); }

var failureCallBack = function (errorResult) { console.log(errorResult); }

cordova.plugins.SmartKarrot.configure(appId, userId, successCallBack, failureCallBack); }

Replace the appId & userId with actual values

Sandbox

SmartKarrot's sandbox site is an instance of the SmartKarrot SaaS platform. It offers the full SmartKarrot functionality with certain rate control limits.

SmartKarrot supplies separate API keys for the sandbox and for production.

Sandbox app Id looks like : sandbox-3412535-ec50-47e5-b0d7-5315323534

Usage Analytics SDK

This section describes how you can send usage analytics data to SmartKarrot. SmartKarrot helps you collect three types of usage data:

  1. User information
  2. Device information
  3. Event information

The SDK caches events when an Internet connection is not available. The SDK uses a store-and-forward buffer to send events and user and device information every 120 seconds to minimize impact on power usage.

Set User Id

UsageAnalytics.shared.set(userId: "your-app-user-id", "customer-account-id")
UsageAnalytics.getInstance().setUserId("your-app-user-id", "customer-account-id");
UsageAnalytics.setUser("your-app-user-id", "customer-account-id");
cordova.plugins.SmartKarrot.setUserId(your-user-id, successCallback(), failureCallback());

SmartKarrot treats a user as a "guest" user - with an internally generated user Id, until you set a user Id. Once you set the user Id, the guest user is considered as having logged in as that user. Events logged of the guest user are transferred to the logged in user.

Reset User Id

UsageAnalytics.shared.resetUserId()
UsageAnalytics.getInstance().resetUserId();
UsageAnalytics.resetUser();
cordova.plugins.SmartKarrot.resetUserId(successCallback(), failureCallBack());

Reset the user Id when the user has logged out of the system. SmartKarrot logs events generated after the reset as a guest user.

Set User Attributes

UsageAnalytics.shared.set(value: "en-us", for: .language)
UsageAnalytics.getInstance().setUserAttribute(UserAttribute.language, "en-us");
// Using Standard UserAttribute "language".
UsageAnalytics.setUserAttribute(UsageAnalytics.UserAttribute.language, "en-us");

// Standard UserAttributes:
//
//    UsageAnalytics.UserAttribute {
//        userId,
//        name,
//        emailId,
//        mobileNumber,
//        dateOfBirth,
//        gender,
//        country,
//        language
//    }
# Using Standard UserAttribute "Language".

cordova.plugins.SmartKarrot.setUserAttribute("Language", "en-us", successCallback(), failureCallback());

# Standard UserAttributes

# UsageAnalytics.UserAttribute { userId, name, emailId, mobileNumber, dateOfBirth, gender, country, language }

# User Id (“User Id”)
# Name - (“Name”)
# Email Id - (“Email Id”)   
# Mobile Number - (“Mobile Number”)
# Date Of Birth - (“Date Of Birth”)
# Gender - (“Gender”)
# Country - (“Country”)
# Language - (“Language”)

User attributes can be the user's language preference, her zip code, city, or country. User attributes are useful in segmenting users. SmartKarrot has a set of standard user attributes:

  1. User Id
  2. Name
  3. Email Id
  4. Mobile Number
  5. Date of Birth
  6. Gender
  7. Country
  8. Language
  9. Designation
UsageAnalytics.shared.set(value: 42, for: "T-shirt Size") // Custom Attriute

UsageAnalytics.shared.set(value: "John Doe", for: UserAttribute.name) // Standard User Attribute

UsageAnalytics.shared.set(value: "HR", for: "Designation") // Standard User Attribute
UsageAnalytics.getInstance().setUserAttribute("T-shirt Size", 42);

//  Custom UserAttribute.
UsageAnalytics.setUserAttribute("T-shirt Size", 42);
# Using Custom UserAttribute "T-shirt Size".

cordova.plugins.SmartKarrot.setUserAttribute("T-shirt Size", 42, successCallback(), failureCallback());

You can set custom user attributes when your app needs a specific one. The attribute value can be a string, number (int, float or double), boolean or date.

Device Attributes

The SmartKarrot SDK automatically collects these device attributes. No action is required from your end.

  1. App Name: The display name of the app.
  2. App Bundle Identifier
  3. App Build: The build version in the iOS project settings (in the Info.plist).
  4. App Version: The app version in the iOS project settings. This is not the version in the App Store.
  5. Device Id: This is an alphanumeric string that uniquely identifies a device to the app’s vendor as provided by iOS.
  6. Device Name: This is the device name as set in the iOS device settings at General > About settings.
  7. Device Make: Set as "Apple" for iOS devices.
  8. Device Model
  9. OS: The device operating system.
  10. OS Version
  11. System Language: The language set in the iOS device settings at General > Language & Region > iPhone Language. The data collected is in the two-letter ISO 693-1 format.
  12. System Currency: The currency set in the iOS device settings at General > Language & Region > Region. The currency is derived from the region and is in the three-letter alphabetic code in the ISO 4217 format.
  13. System Region: The currency set in the iOS device settings at General > Language & Region > Region. This is typically the user's country and is in the two-letter alphabetic code in the ISO 3166-1 format.

Log Events

// Log without event attributes.
UsageAnalytics.shared.log(event: "Signed In")

// Log with event attributes.
UsageAnalytics.shared.log(event: "Screen View", with: ["Screen Name": "News List Screen"])

// Log with event attributes.
UsageAnalytics.shared.log(event: "Purchased Product", with: [
    "Module" : "Sales", // Standard Event Attribute
    "Product Id": "B01M3TD8CF", 
    "Deliver to ZIP Code": "07120-4719",
    "Quantity": 3,
    "Order Date": Date(),
    "Discount Applied": true
])
// Log without event attributes.
UsageAnalytics.getInstance().logEvent("Signed In");

// Log with event attributes.
EventParameters params = new EventParameters.Builder()
    .addParameter("Module", "Sales") // Standard Event Attribute
    .addParameter("Product Id", "B01M3TD8CF")
    .addParameter("Deliver to ZIP Code", "07120-4719")
    .addParameter("Quantity", 3)
    .addParameter("Order Date", new Date())
    .addParameter("Discount Applied", true)
    .build();
UsageAnalytics.getInstance().logEvent("Purchased Product", params);
// Log without event attributes.
UsageAnalytics.logEvent("Signed In");

// Log with event attributes.
var eventParams = {
    "Module" : "Sales", // Standard Event Attribute
    "Product Id": "B01M3TD8CF",
    "Deliver to ZIP Code": "07120-4719",
    "Quantity": 3,
    "Order Date": new Date().toISOString(),
    "Discount Applied": true
}
UsageAnalytics.logEvent("Purchased Product", eventParams); 
cordova.plugins. SmartKarrot.logEvent("Purchased Product", value, successCallback(), failureCallback())

 # Where “value” is a string and can also accept stringify(d) json object. 

You can log screen views and other events to SmartKarrot. Examples of app events are the user opening a screen, purchasing a product or logging in. The SDK automatically logs events like the user opening the app and closing it. You can add your events using our SDK.

Events may have attributes associated with them. For example, a “Purchased Product” event may have attributes like “Product Id” with a value “B01M3TD8CF” and “Deliver to ZIP Code” as “07120-4719". An event can have up to five attributes.

A good place to add the screen view event is the viewDidAppear method of the view controller.

The SDK sends events to the server in a low priority queue, so user functionality is not affected. Events are buffered and sent every 120 seconds to reduce constant network traffic. When an internet connection is not available, the SDK automatically stores and forwards events.

SmartKarrot has a standard event attribute.

  1. Module

Update Device Token:

Android

If you are not already using Firebase Cloud Messaging in your app you need to add FCM in your app. Follow this guide to add firebase to your app: Firebase Android Setup..

Then change your Notification Receiver service class (with intent filter com.google.firebase.MESSAGING_EVENT ) as follows,

public class MyFirebaseNotificationService extends FirebaseMessagingService {
    @Override
    public void onNewToken(String s) {
        super.onNewToken(s);
        UsageAnalytics.updateDeviceToken(s);
        // Handle token if you are implementing FCM in your app.
    }
    // Rest of your code
}

Setting up auto token refresh

Add this after initializing the core SDK:

UsageAnalytics.getInstance().setTokenFactory(new FirebaseTokenFactory() {
    @Override
    public void updateToken() {
        FirebaseInstanceId.getInstance().getInstanceId().addOnCompleteListener(new OnCompleteListener<InstanceIdResult>() {
            @Override
            public void onComplete(@NonNull Task<InstanceIdResult> task) {
                if(task.isSuccessful())
                    UsageAnalytics.updateDeviceToken(task.getResult().getToken());
            }
        });
    }
});

Usage Analytics REST API

Get Your API Keys

Add an app in the Settings section and find the API keys (AppID) under App Details. Every app has two API keys: one for the sandbox and one for production. The sandbox key is used for development and testing, and the production one for live transactions.

Get the separate REST API Key from SmartKarrot Support Team (email: support@smartkarrot.com).

API Reference

Welcome to the SmartKarrot API! SmartKarrot offers private REST API for its SaaS services. The API make it easier to quickly configure and integrate your Web app directly with our server.

The API supports Cross-origin resource sharing (CORS).

URL

The SmartKarrot API is available at:

Environment URL
Production https://api.smartkarrot.com/v4/

Authentication

SmartKarrot uses the Basic Authentication mechanism with an API key to authenticate requests. For example, if you API key is daced09f-8ade-48dc-b1d8-506204530ce3, you can log an event with a simple HTTP POST request:

curl -v -u apikey:daced09f-8ade-48dc-b1d8-506204530ce3 -H "Content-Type: application/json" -d '{"appId": "4ed062f1-fc38-4f32-a714-b63dc5399626","platform":"iOS","deviceId": "53e11019-8034-496b-a484-fa978918873c","loginMechanism" : "AUTH","bundleId": "com.smartkarrot.tasks","lastLoggedInUserId": "f1d0c16d-f9e0-4eb4-8739-45574c43f508","userId": "8f2dfb97-fe4b-49b3-a5d5-a671335cde00","sessionId": "234240-234-234-234-234-234237B891079-A302-4DDD-8860-2672B9682A3B","status": "Active","customerAccountId": "de8327c8-ece7-427a-ba8f-e4c7809ea716"}' 'https://api.smartkarrot.com/v4/usageanalytics/user'

Data Types

The SDK uses the following data types.

Type Description
String A simple quoted string, following standard JSON rules; see the JSON spec for details.
Integer A whole number, transmitted as a JSON number.
Boolean A JSON boolean, the literal string true or false.
Array A JSON array. Each element contains a payload that will be described.
Timestamp Time in UTC stored in the ISO 8601 format with millisecond precision. (Example: 2018-09-29T09:58:44.635Z)
UUID A UUID string. Preferably a version 4 UUID. Example: f30ccccf-54a8-49bf-b3e4-6eee274810ab.
Decimal A decimal value, encoded in a JSON string. The contents will be a series of digits, followed by an optional decimal point and additional digits.

Create User Endpoint

Use this endpoint to create a user Id when a user is using your app. A user can be a guest user, in which case, you can generate a random UUID for the user. If a user is logged in, use this endpoint to create the user in SmartKarrot.

Creating a user is required only once, and is not required if the user is already added to SmartKarrot through a backend upload process.

HTTPS Request

POST usageanalytics/user

Sample Request

{
  "appId": "4ed062f1-fc38-4f32-a714-b63dc5399626",
  "platform":"iOS",
  "deviceId": "53e11019-8034-496b-a484-fa978918873c",
  "loginMechanism" : "AUTH",
  "bundleId": "com.smartkarrot.tasks",
  "lastLoggedInUserId": "f1d0c16d-f9e0-4eb4-8739-45574c43f508",
  "userId": "8f2dfb97-fe4b-49b3-a5d5-a671335cde00",
  "sessionId": "234240-234-234-234-234-234237B891079-A302-4DDD-8860-2672B9682A3B",
  "status": "Active",
  "customerAccountId": "de8327c8-ece7-427a-ba8f-e4c7809ea716"
}

Request Body

Parameter Type Required Description
bundleId String required Client unique id.(Android Package Name, iOS Bundle Id and Web Domain Name)
loginMechanism String required Enum 'AUTH', 'GUEST', If the user is in your system then send AUTH else GUEST.
userId String required The system user Id.
appId String required SmartKarrot App Id.
sessionId String optional Client session Id.
deviceId String optional Client device Id.
idempotencyId String required Unique key for the request, v4 UUID is recommended.
platform String required Enum: iOS, Android, Web
status String required Enum: Active, Inactive
customerAccountId String required The system customer account id.

Sample Output

{
  "status": "SUCCESS"
}

Response Body

Log user response.

Parameter Type Description
status String Enum SUCCESS, ERROR, INVALID_INPUT

Use this endpoint to create a new customer account or update an existing one.

Log customer account response.

Parameter Type Description
status String Enum SUCCESS, ERROR, INVALID_INPUT

Create or Update Customer Account Endpoint

Use this endpoint to create a new customer account or update an existing one.

HTTPS Request

POST /usageanalytics/customer

Sample Request

{
  "appId": "4ed062f1-fc38-4f32-a714-b63dc5399626",
  "accountId": "de8327c8-ece7-427a-ba8f-e4c7809ea716",
  "name" : "SmartKarrot",
  "base64EncodedLogoImage" : "iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAYAAABXAvmHAAAAAXNSR0IArs4c6QAAAVlpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IlhNUCBDb3JlIDUuNC4wIj4KICAgPHJ",
  "status": "Active"
}

Request Body

Parameter Type Required Description
accountId String required The customer account ID in your system.
appId String required SmartKarrot App ID.
name String required Name of system customer account.
base64EncodedLogoImage String optional Image in base64 encoded string. The image size should be less than 3 MB.
status String required Enum: Active, Inactive

Sample Output

{
  "status": "SUCCESS"
}

Response Body

Log customer account response.

Parameter Type Description
status String Enum SUCCESS, ERROR, INVALID_INPUT

Update User Status Endpoint

Use this endpoint to update user data when a user is using your app. A user can be a guest user, in which case, you can generate a random UUID for the user. If a user is logged in, use this endpoint to update the user in SmartKarrot.

HTTPS Request

POST usageanalytics/user

Sample Request

{
  "appId": "4ed062f1-fc38-4f32-a714-b63dc5399626",
  "platform":"iOS",
  "deviceId": "53e11019-8034-496b-a484-fa978918873c",
  "loginMechanism" : "AUTH",
  "bundleId": "com.smartkarrot.tasks",
  "lastLoggedInUserId": "f1d0c16d-f9e0-4eb4-8739-45574c43f508",
  "userId": "8f2dfb97-fe4b-49b3-a5d5-a671335cde00",
  "sessionId": "234240-234-234-234-234-234237B891079-A302-4DDD-8860-2672B9682A3B",
  "status": "Active",
  "customerAccountId": "de8327c8-ece7-427a-ba8f-e4c7809ea716"
}

Request Body

Parameter Type Required Description
bundleId String required Client unique id.(Android Package Name, iOS Bundle Id and Web Domain Name)
loginMechanism String required Enum 'AUTH', 'GUEST', If the user is in your system then send AUTH else GUEST.
userId String required User's unique identifier.
appId String required SmartKarrot App Id.
sessionId String optional Client session Id.
deviceId String optional Client device Id.
idempotencyId String required Unique key for the request, generating v4 UUID is recommended.
platform String required Enum: iOS, Android, Web
status String required Enum: Active, Inactive
customerAccountId String required The customer account ID in your system.

Sample Output

{
  "status": "SUCCESS"
}

Response Body

Log user response.

Parameter Type Description
status String Enum SUCCESS, ERROR, INVALID_INPUT

Log Events Endpoint

You can log screen views and other events to SmartKarrot. Examples of app events are the user opening a screen, purchasing a product, or logging in.

Events may have attributes associated with them. For example, a “Purchased Product” event may have attributes like “Product Id” with a value “B01M3TD8CF” and “Deliver to ZIP Code” as “07120-4719". An event can have up to five attributes.

Multiple events can be logged in the same call.

HTTPS Request

POST usageanalytics/event

Sample Request

{
  "events": [
    {
      "name": "app_session_start",
      "loggedAtTime": "2019-03-28T12:07:58.165Z",
      "parameters": [
        {
          "attributeName": "sessionId",
          "dataType": "String",
          "stringValue": "j28d89f9wi5eup4789794"
        },
        {
          "attributeName": "startTime",
          "dataType": "Date",
          "stringValue": "2019-03-28T12:07:58.165Z"
        }
      ]
    }
  ],
  "userId": "28f05cea-4721-0818-2a7c-a88b102012fa",
  "appId": "a8548489-6d1d-44c4-b068-061f48c9f93c",
  "sessionId": "j28d89f9wi5eup4789794",
  "deviceId": "45010143537367203626121537363900144024",
  "platform": "Web",
  "customerAccountId": "35373-67203-62612-15373-63900-1440",
  "appVersion": "1.0"
}

Request Body

The list of events.

Parameter Type Required Description
events [Event] required An array of events.
userId String required The user ID in your system.
appId String required SmartKarrot App ID.
customerAccountId String required The customer account ID as in your system.
sessionId String optional Client session ID.
deviceId String optional The unique device ID.
platform String required Enum: iOS, Android, Web

The Event structure is as follows.

Parameter Type Required Description
name String required Event name.
loggedAtTime String required ISO 8601 format.
parameters [EventParameter] optional Event parameters

A Event parameter structure is as follows.

Parameter Type Required Description
attributeName String required Event attribute name.
dataType String required Enum String, Number, Date, Boolean
stringValue String optional Required only if dataType is String or Date. Date: ISO 8601 format.
numberValue Number optional Required only if dataType is Number.
booleanValue Bool optional Required only if dataType is Bool.

Sample Output

{
  "status": "SUCCESS"
}

Response Body

Log events response.

Parameter Type Description
status String Enum SUCCESS, ERROR, INVALID_INPUT

Mandatory Events

Set User Attributes Endpoint

User attributes can be the user's language preference, her zip code, city, or country. User attributes are useful in segmenting users. SmartKarrot has a set of standard user attributes:

  1. User Id
  2. Name
  3. Email Id
  4. Mobile Number
  5. Date of Birth
  6. Gender
  7. Country
  8. Language

You can add or update custom user attributes when your app needs a specific one. The attribute value can be a string, number (int, float or double), boolean or date.

HTTPS Request

POST /usageanalytics/user/attribute

Sample Request

{
  "userId": "8f2dfb97-fe4b-49b3-a5d5-a671335cde00",
  "deviceId" : "53e11019-8034-496b-a484-fa978918873c",
  "platform" : "Web",
  "appId": "4ed062f1-fc38-4f32-a714-b63dc5399626",
  "sessionId": "4ed062f1-fc38-4f32-a714-b63dc5399626CF32B30B-B7B0-4F5B-B278-408E5D02484E",
  "customerAccountId" : "35373-67203-62612-15373-63900-1440",
  "userAttributes": [
    {
      "name": "Subscribed To Email",
      "dataType": "Boolean",
      "booleanValue": true,
      "loggedAtTime": "2018-12-14T07:46:31.565Z"
    },
    {
      "name": "Region",
      "dataType": "String",
      "stringValue": "US",
      "loggedAtTime": "2018-12-14T07:46:31.565Z"
    },
    {
      "name": "Gender",
      "dataType": "String",
      "stringValue": "Male",
      "loggedAtTime": "2018-12-14T07:46:31.565Z"
    },
    {
      "name": "Age",
      "dataType": "Number",
      "numberValue": 25,
      "loggedAtTime": "2018-12-14T07:46:31.565Z"
    }
  ]
}

Request Body

The list of user attributes.

Parameter Type Required Description
userAttributes [UserAttribute] required An array of user attributes.
userId String required The system user Id.
appId String required SmartKarrot App Id.
sessionId String optional Client session Id.
deviceId String optional Client device Id.
idempotencyId String required Unique key for the request, v4 UUID is recommended.
platform String required Enum: iOS, Android, Web
customerAccountId String optional The system customer account id. Required for multilevel organizations.

A User Attribute structure is as follows.

Parameter Type Required Description
name String required User attribute name.
dataType String required Enum String, Number, Date, Boolean
loggedAtTime String required ISO 8601 format.
stringValue String optional Required only if dataType is String or Date. Date: ISO 8601 format.
numberValue Number optional Required only if dataType is Number.
booleanValue Bool optional Required only if dataType is Bool.

Sample Output

{
  "status": "SUCCESS"
}

Response Body

Log user attributes response.

Parameter Type Description
status String Enum SUCCESS, ERROR, INVALID_INPUT

Log Device Attributes Endpoint

If you use the SmartKarrot SDK, it automatically collects these device attributes. No action is required from your end.

If you decide to use this REST API, you could choose to populate one or more of the device attributes.

  1. Device Id: This is an alphanumeric string that uniquely identifies a device to the app’s vendor as provided by iOS.
  2. App Name: The display name of the app.
  3. App Bundle Identifier
  4. App Build: The build version in the iOS project settings (in the Info.plist).
  5. App Version: The app version in the iOS project settings. This is not the version in the App Store.
  6. Device Name: This is the device name as set in the iOS device settings at General > About settings.
  7. Device Make: Set as "Apple" for iOS devices.
  8. Device Model
  9. OS: The device operating system.
  10. OS Version
  11. System Language: The language set in the iOS device settings at General > Language & Region > iPhone Language. The data collected is in the two-letter ISO 693-1 format.
  12. System Currency: The currency set in the iOS device settings at General > Language & Region > Region. The currency is derived from the region and is in the three-letter alphabetic code in the ISO 4217 format.
  13. System Region: The currency set in the iOS device settings at General > Language & Region > Region. This is typically the user's country and is in the two-letter alphabetic code in the ISO 3166-1 format.

HTTPS Request

POST /usageanalytics/device/attribute

Sample Request

{
  "appId": "4ed062f1-fc38-4f32-a714-b63dc5399626",
  "platform": "Web",
  "deviceId": "53e11019-8034-496b-a484-fa978918873c",
  "idempotencyId": "9890BDAA-CF16-4A08-A8F7-9F680D9ADEBA",
  "userId": "8f2dfb97-fe4b-49b3-a5d5-a671335cde00",
  "sessionId": "234240-234-234-234-234-234237B891079-A302-4DDD-8860-2672B9682A3B",
  "deviceAttributes": {
    "App Bundle Identifier": "org.app.demo.UsageAnalytics",
    "Make": "Apple"
  }
}

Request Body

The list of user's device attributes.

Parameter Type Required Description
deviceAttributes Map required A key value pair of device attributes. Key and value are String type.
userId String required The system user Id.
appId String required SmartKarrot App Id.
sessionId String optional Client session Id.
deviceId String optional Client device Id.
idempotencyId String required Unique key for the request, v4 UUID is recommended.
platform String required Enum: iOS, Android, Web

Any custom device attributes can be logged. Some of pre-defined keys for device attributes are:

'Device ID', 'Device Name', 'Make', 'Model', 'OS', 'OS Version', 'System Language', 'System Currency', 'System Region', 'App Name', 'App Bundle Identifier', 'App Build', 'App Version'

The data collected for below attributes should be in respective formats.

  1. System Language: Two-letter code ISO 693-1 format.
  2. System Currency: Three-letter alphabetic code in the ISO 4217 format.
  3. System Region: Two-letter alphabetic code in the ISO 3166-1 format.

Sample Output

{
  "status": "SUCCESS"
}

Response Body

Log device attributes response.

Parameter Type Description
status String Enum SUCCESS, ERROR, INVALID_INPUT

Set Device Token Endpoint

Use this endpoint to send the notification device token to SmartKarrot. This is either the Firebase device token for Android, or the APNs device token for iOS.

HTTPS Request

POST /usageanalytics/device/token

Sample Request

{
  "appId": "4ed062f1-fc38-4f32-a714-b63dc5399626",
  "platform":"iOS",
  "deviceId": "53e11019-8034-496b-a484-fa978918873c",
  "idempotencyId": "9890BDAA-CF16-4A08-A8F7-9F680D9ADEBA",
  "userId": "8f2dfb97-fe4b-49b3-a5d5-a671335cde00",
  "sessionId": "234240-234-234-234-234-234237B891079-A302-4DDD-8860-2672B9682A3B",
  "deviceToken": "740f4707 bebcf74f 9b7c25d4 8e335894 5f6aa01d a5ddb387 462c7eaf 61bb78ad",
  "appInDistribution": true
}

Request Body

Parameter Type Required Description
deviceToken String required A device token generated by mobile device. (Android or iOS)
appInDistribution Bool optional Required only if platform is iOS. True if the app is running in distribution mode, false otherwise.
userId String required The system user Id.
appId String required SmartKarrot App Id.
sessionId String optional Client session Id.
deviceId String optional Client device Id.
idempotencyId String required Unique key for the request, v4 UUID is recommended.
platform String required Enum: iOS, Android, Web

Sample Output

{
  "status": "SUCCESS"
}

Response Body

Log device token response.

Parameter Type Description
status String Enum SUCCESS, ERROR, INVALID_INPUT

App Analytics SDK

Engagement Score & Score Maturity

Duration Index

Loyalty Index

Loyalty Index is a measure of the percentage of user churn, i.e. the percentage of total users uninstalling the app to the total users installing the app in a given time period. If you have to enable Loyalty Index for your app, you need to add the following lines of code:

Enabling Loyalty Index for iOS

To enable Loyalty Index for your iOS app, you need to submit your Apple Push Notification certificates. There is a detailed step by step guide to generate them: external link After generating the certificates, submit the Dev & Prod certificates in .p12 format wihle app on boarding.

On your app side, add the following lines of codes:

// Add these functions to your AppDelegate file

func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        UsageAnalytics.shared.didRegisterForRemoteNotificationsWithDeviceToken(deviceToken: deviceToken)
    }

func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
    UsageAnalytics.shared.didFailToRegisterForRemoteNotificationsWithError(error: error)
}

Enabling Loyalty Index for Android

To enable Loyalty Index for your android app you need to register for Firebase Cloud Messaging and then submit your app's FCM key (available as Server Key in your Firebase console.).

A detailed guide about registering your app for FCM can be found here: external link.

Then change your Notification Receiver service class (with intent filter com.google.firebase.MESSAGING_EVENT) as follows,

public class MyFirebaseNotificationService extends FirebaseMessagingService {
    @Override
    public void onNewToken(String s) {
        super.onNewToken(s);
        UsageAnalytics.updateDeviceToken(s);
        // Handle token if you are implementing FCM in your app.
    }
    // Rest of your code
}

Enabling Loyalty Index for Hybrid - Cordova/PhoneGap/Ionic

The pushNotificationDeviceToken will be the deviceToken obtained while using any push notification providers. This value can be obtained during push notification registration of the provider.

cordova.plugins.SmartKarrot.registerNotificationWithToken(“pushNotificationDeviceToken”, successCallback(), failureCallback())

If the app fails to register for push Notification, use the below code

cordova.plugins.SmartKarrot.failRegisterNotificationWithError(“error”, successCallback(), failureCallback())

No code is required to configure Loyalty Index for Android.

Retention Index

Feedback Index

Feedback Index is a measure of your app's rating across iOS App Store & Google Playstore.

Enabling for iOS

iOS App Store ratings are publicly available. So, you don't need to do anything.

Enabling for Android App:

For Android, you need to authorize the SmartKarrot platform to fetch your app's rating on your behalf. For this, you need to generate a service account with view access and submit the credentials json file while onboarding. Here is step by step guide to help you service account credentials file: Generating Service Account

Realtime Engagement

Survey and Feedback SDK

This module lets you run a survey with a single line of code. Build your survey on the SmartKarrot web platform. Integrate the SDK and run the survey in three quick steps:

  1. Add our SDK to your app.
  2. Configure the SmartKarrot integration.
  3. Run the survey.

Step 1: Add our SDK to Your App

SmartKarrot provides iOS and Android SDKs.

iOS App

You can install the SDK using CocoaPods or as a dynamic framework.

For installing using CocoaPods, add the line pod 'SmartKarrot-Survey' to your Podfile and install it with pod install.

If you want to add the SDK as a dynamic framework, download it, and add it to your Xcode project.

Survey SDK uses Camera or Gallery to upload photos for Survey. The NSPhotoLibraryUsageDescription key is now required for access to Photos.

      <key>NSPhotoLibraryUsageDescription</key>
      <string>This App uses Camera or Gallery to upload photos for Survey.</string>

Android App

allprojects {
  repositories {
    maven { url "https://s3.amazonaws.com/smartkarrot-android-repo/" }
  }
}

The Android SDK comes as a Java library. Installing it is simple adding the lines to the right to your project level build.gradle file. You may have already completed this step when adding any other SmartKarrot SDK.

Then add this to your App's build.gradle file:

implementation 'com.smartkarrot:survey:0.0.4.6'

Web - JavaScript

Survey features are already available in Web - JavaScript Core SDK (UsageAnalytics).

Hybrid - Cordova/PhoneGap/Ionic

Survey features are already available in SmartKarrot plugin.

Step 2: Configure the SDK

The SDK must be initialized before using any of its functions.

iOS App

Import the SDK with into AppDelegate.swift file with

import Survey

Add this to your AppDelegate.swift file

Survey.shared.configure()

Android App

Add this line to the onCreate method of your activity or Application class.

Survey.init(context);

Web - JavaScript

Survey features are already configured as part of Web - JavaScript Core SDK (UsageAnalytics) integration.

Hybrid - Cordova/PhoneGap/Ionic

Call configureSurvey to configure SDK.

cordova.plugins.SmartKarrot.configureSurvey()

Step 3: Run the SDK

The SmartKarrot Survey SDK can be used to launch a single survey or to display a list of available surveys and let the user take the survey they choose.

List Available Surveys

This is the easiest way to launch a survey. The SmartKarrot SDK view lists all available surveys, letting the user choose a survey to start. If only one survey is available, the SDK launches it automatically.

iOS

  Survey.shared.listSurveys(from: viewController, animated: true)

The survey will be presented from a UIViewController. Typically, this is the view controller whose view is currently visible. The SmartKarrot SDK automatically dismisses the SDK view controller once the user has completed or abandoned the survey.

Android

  Survey.getInstance().listSurveys(context); 
  // `user_id` is the id of the user in your app.

You can add the user name and other information about the user by integrating the SmartKarrot Usage Analytics SDK.

Web - JavaScript

  UsageAnalytics.listSurveys(); 
  // `user_id` is the id of the user in your app.

This will display a list of surveys.

Hybrid - Cordova/PhoneGap/Ionic

  # List Surveys
  # This will render from native view.
  cordova.plugins.SmartKarrot.listSurveys(animated:true, successCallBack(), failureCallBack());

This will display a list of surveys from native view.

Start a Single Survey

  UsageAnalytics.startSurvey("survey-id");
  Survey.shared.startSurvey(surveyId: "survey-id", from: viewController, animated: true)
  // The user-id of the user taking the survey is taken from SmartKarrot-Core SDK.
  Survey.getInstance().startSurvey(context, "survey-id");
   // `user_id` is the id of the user in your app.

   # Single Survey
   # This will render from native view.

   # For Android
   cordova.plugins.SmartKarrot.startSurvey("survey-id", "app-user-id", successCallBack(), failureCallBack());

   # For iOS
   let animated= "true | false";
   cordova.plugins.SmartKarrot.startSurvey("survey-id", animated, successCallBack(), failureCallBack());

Add this line to launch a single survey with given id. You can get the survey id from SmartKarrot dashboard.

Rich Push Notifications SDK

This session describes how to enable rich push notifications (InApp PopUp and Push Notifications) in your iOS , Android and web apps.

Push Notifications

iOS

App Configuration

1. Enable background mode for remote notification in capabilities tab

2. Enable push notifications capability in capabilities tab

Register for Push Notifications

    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        UsageAnalytics.shared.didRegisterForRemoteNotificationsWithDeviceToken(deviceToken: deviceToken)
    }

    func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
        UsageAnalytics.shared.didFailToRegisterForRemoteNotificationsWithError(error: error)
    }

Ask User Permission

Call requestUserNotificationsPermission to request user permission to show push notifications.

    UsageAnalytics.shared.requestUserNotificationsPermission()

Receive Push Notifications

Add following callback in app delegate to reveive and handle push notifications.

- application(_:didReceiveRemoteNotification:fetchCompletionHandler:)

Call handleRemoteNotification to handle the notificaiton. showDropdown is an option used to show notificaion as a drop down message when the app is in foreground.

    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
          UsageAnalytics.shared.handleRemoteNotification(userInfo: userInfo, showDropdown: true)
          completionHandler(.noData)
    }    

Add Notification Service Extension

To add a notification service app extension to your iOS app In Xcode

- select New > Target to add a new target to your project.

- In the iOS > Application Extension section, select the Notification Service Extension target, Click Next.

- Specify the name and other details for your app extension, Click Finish.

Notification Service Extension Code Changes

After adding notification service extension, You will see a folder with the extension name you provided. This folder will have NotificationService.swift and info.plist file.

Replace contents of NotificationService.swift with content from this file download.

Android

Register for Push Notifications

To enable RichPush you need to integrate FCM as given here.

Then change your Notification Receiver service class (with intent filter com.google.firebase.MESSAGING_EVENT) as follows,

public class MyFirebaseNotificationService extends FirebaseMessagingService {
    @Override
    public void onNewToken(String s) {
        super.onNewToken(s);
        UsageAnalytics.updateDeviceToken(s);
        // Handle token if you are implementing FCM in your app.
    }
    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        super.onMessageReceived(remoteMessage);
        boolean isRichPushNotification = RichPush.isRichPushNotification(remoteMessage.getData());
        if(isRichPushNotification) {
            // Push notification is SK RichPush.
            RichPush.handleRichPush(this, remoteMessage.getData());
            return;
        }
        // Push notification is not SK RichPush. Handle if required.

    }
}

Hybrid - Cordova/PhoneGap/Ionic

Hybrid - iOS

1. Enable background mode for remote notification in capabilities tab

2. Enable push notifications capability in capabilities tab

 # 3. Register for remote notifications.
 cordova.plugins.SmartKarrot.registerNotificationWithToken(deviceToken, successCallback(), failureCallback());

3. Call the didRegisterForRemoteNotificationsWithDeviceToken method as shown.

4. Ask user permission.

 # 4. Ask user permission
 cordova.plugins.SmartKarrot.requestUserNotificationsPermission(successCallback(),errorCallback());

5. Receive Push Notifications

 # 5. Receive Push Notifications

 let userInfo : any;
 let showDropdown = true | false;
 cordova.plugins.SmartKarrot.handleRemoteNotification(userInfo, showDropdown, successCallback(), errorCallback());

Hybrid - Android

Register and integrate FCM as given here.

Add the below highlighted code in the third party FCM provider (inside .java file) you are using.

# Hybrid - Android
# Add the below highlighted code in the third party FCM provider (inside .java file) you are using.

# public class MyFirebaseNotificationService extends FirebaseMessagingService {
#    @Override
#    public void onNewToken(String s) {
#        super.onNewToken(s);
         UsageAnalytics.updateDeviceToken(s);
#       // Handle token if you are implementing FCM in your app.
#    }
#    @Override
#    public void onMessageReceived(RemoteMessage remoteMessage) {
#        super.onMessageReceived(remoteMessage);
        boolean isRichPushNotification = RichPush.isRichPushNotification(remoteMessage.getData());
        if(isRichPushNotification) {
            // Push notification is SK RichPush.
            RichPush.handleRichPush(this, remoteMessage.getData());
            return;
        }
#        // Push notification is not SK RichPush. Handle if required.
#
#    }
# }

InApp PopUp

iOS

Show InApp PopUp

InApp popups can be displayed to from any visible view controller or it can can be configured to display from specific view controllr.

      RichPush.shared.handle(fromAny: true) { (richPushCampaignId, actionName, actionValue) in
            // Your code handle the user action on InApp popup.
     }
       let viewControllerToPresentInAppPopUp = 
       RichPush.shared.handle(from: viewControllerToPresentInAppPopUp) { (richPushCampaignId, actionName, actionValue) in
         // Your code handle the user action on InApp popup.
    }

Handle InApp PopUp Actions

InAppPopUpActionHandler, A closure to handle InApp popup actions.

InAppPopUpActionHandler: (_ campaignId: String, _ actionName: String, _ value: String) -> Void

Flags

RichPush.shared.enabled = false

Android

Show InApp PopUp

InApp popups can be displayed to from any visible Activity/Fragment. Call enablePopUpFor(this, mInAppPopUpActionHandler) in the activity/fragment's onResume method to show InApp popups. The InAppPopUpActionHandler is optional. You can also call enablePopUpFor(this) function if you do not wish to handle actions on popup.

To avoid memory leak, in onPause() of your activity/fragment call disablePopupFor(this, mInAppPopUpActionHandler) or disablePopupFor(this) to disable popup.

Handle InApp PopUp Actions

You can create an InAppPopUpActionHandler to handle actions done on the popups by the user. To handle actions, create a InAppPopUpActionHandler object as given and pass it while calling enablePopUpFor(this, mInAppPopUpActionHandler). If you are adding an actionHandler, make sure to de-register it in onPause() of your activity/fragment by calling disablePopupFor(this, mInAppPopUpActionHandler).

InAppPopUpActionHandler mInAppPopUpActionHandler = new InAppPopUpActionHandler() {
            @Override
            public void onUserAction(String campaignId, String action, String value) {
                // Handle Action Here
            }
        };

Financial Data Integration

This section describes how you can send financial data to SmartKarrot. SmartKarrot helps you collect three types of financial data:

  1. Orders
  2. App Financial data
  3. Account Financial data

URL for Financial Integration

The SmartKarrot API for financial data is available at:

Environment URL
Production https://api.smartkarrot.com/dashboards/v4/financial

Get REST API Key

Get REST API Key from SmartKarrot Support Team (email: support@smartkarrot.com).

Authenticate using API key.

SmartKarrot uses the Basic Authentication mechanism with an API key to authenticate requests. For example, if you API key is daced09f-8ade-48dc-b1d8-506204530ce3, you can log an order with a simple HTTP POST request:

curl -v -u apikey:daced09f-8ade-48dc-b1d8-506204530ce3 -H "Content-Type: application/json" -d '{ "appId" :"3956ca1e-d306-4dea-abc1-bfdabe44b524", "productId":"c519d994-a0cb-41f9-89ba-074a63923239" "orderId":"038883ee-88b5-4851-a0cd-eb704e085cfe", "customerAccountId":"csm-id-CA", "status":"Activated", "amount" : 21325.0, "effectiveDate":"2019-05-12", "endDate" :"2020-05-12" }' 'https://api.smartkarrot.com/dashboards/v4/financial/orders/'

Orders

HTTPS Request
POST    /orders         [create or update an order]
DELETE  /orders/{id}    [delete an order with id]

The orders are the basic object in Financial data dashboard around which many operations are centered. Basically, orders are components of contracts by which we get to know the amount or the revenues generated by a particular account. Based on the amount the ARR, MRR and other data in the Financial Dashboard are calculated.

Create or Update an order

HTTPS Request

POST /orders

This api is used to create an order in Smartkarrot. If the same order is pushed using the same api it will update the if any change is passed on to the system.

Sample Request

{
  "orderId": "8920b276-5d2f-457c-87c4-af7156d2fe95",
  "status": "Activated",
  "endDate": "2020-12-31",
  "customerAccountId": "d28f2cc6-4385-47b7-ab51-3fda6d0c1ab6",
  "appId": "c50f05b4-0fc7-43c7-88f6-46f0f0aef4a3",
  "amount": 8400,
  "effectiveDate": "2020-01-01",
  "productId": "c8af1413-8227-40ad-bfaa-bcc60a62cdbf"
}

Request Body

Parameter Type Required Description
customerAccountId String required The customer account ID in your system.
appId String required SmartKarrot App ID.
productId String required The product ID in your system associated with the order.
orderId String required The order ID in your system.
status String required The status of order. {Activated, Draft}
amount Number (Double) required Amount of the Order.
effectiveDate String required The start date of the order in 'yyyy-mm-dd' format.
endDate String required The end date of the order in 'yyyy-mm-dd' format.

Sample Output

{
  "status": "SUCCESS"
}

Response Body

Response for creating an order.

Parameter Type Description
status String Enum SUCCESS, ERROR, INVALID_INPUT

Delete an Order

DELETE /orders/{id}

This api is used to delete an order which is passed in the params.

Sample Request

{
  "appId" : "c50f05b4-0fc7-43c7-88f6-46f0f0aef4a3"
}

Request Body

Parameter Type Required Description
appId String required SmartKarrot App ID.

Sample Output

{
  "status": "SUCCESS"
}

Response Body

Response for creating an order.

Parameter Type Description
status String Enum SUCCESS, ERROR, INVALID_INPUT

App Financial Data

HTTPS Request
POST    /app-financial-data                       [create or update a configuration of an app]
DELETE  /app-financial-data/{your-app-id}         [delete the configuration related to app]

The configuration of an app must be provided for calculation of financial data which will reflect in the Financial Dashboard.

Create or Update a configuration of app

HTTPS Request

POST /app-financial-data

This api is used to set the customer churn tolerance value for the app. This will remain same for each customer accounts, customer success managers.

Sample Request

{
  "appId" : "c50f05b4-0fc7-43c7-88f6-46f0f0aef4a3",
  "logoChurnTolerance": 0.05                // logoChurnTolerance = 5% 
}

Request Body

Parameter Type Required Description
appId String required SmartKarrot App ID.
logoChurnTolerance String required The upper limit of customer churn.

Sample Output

{
  "status": "SUCCESS"
}

Response Body

Response for creating an order.

Parameter Type Description
status String Enum SUCCESS, ERROR, INVALID_INPUT

Delete an app configuration

DELETE /app-financial-data/{your-app-id}

This api is used to delete a configuration (churn tolerance) related to an app which is passed in the params. Request parameters are not required.

Sample Output

{
  "status": "SUCCESS"
}

Response Body

Response for creating an order.

Parameter Type Description
status String Enum SUCCESS, ERROR, INVALID_INPUT

Account Financial Data

HTTPS Request
POST    /account-financial-data                            [create or update a configuration on account level]
DELETE  /account-financial-data/{your-customer-account-id} [delete the configuration related to app]

The account financial data is for adding details of a particular customer account, like ARR Target and customer account start date.

Sample Request

{
  "customerAccountId": "d28f2cc6-4385-47b7-ab51-3fda6d0c1ab6",
  "appId": "c50f05b4-0fc7-43c7-88f6-46f0f0aef4a3",  
  "accountStartDate": "2020-12-31",
  "arrTarget": 1000000
}

Create or Update a configuration of a particular customer account.

HTTPS Request

POST /account-financial-data

This api is used to create or update a configuration of customer account in Smartkarrot.

Request Body

Parameter Type Required Description
customerAccountId String required The customer account ID in your system.
appId String required SmartKarrot App ID.
accountStartDate String required Creation date of the account for financial data in 'yyyy-mm-dd' format.
arrTarget Number (Double) required The ARR target defined for a particular customer.

Sample Output

{
  "status": "SUCCESS"
}

Response Body

Response for creating an order.

Parameter Type Description
status String Enum SUCCESS, ERROR, INVALID_INPUT

Delete an account configuration

DELETE /account-financial-data/{your-customer-account-id}

This api is used to delete/reset a configuration related to a customer account, like ARR Target and customer account start date.

Sample Request

{
  "appId" : "c50f05b4-0fc7-43c7-88f6-46f0f0aef4a3"
}

Request Body

Parameter Type Required Description
appId String required SmartKarrot App ID.

Sample Output

{
  "status": "SUCCESS"
}

Response Body

Response for creating an order.

Parameter Type Description
status String Enum SUCCESS, ERROR, INVALID_INPUT