NAV Navbar
Swift Java JavaScript Ionic

Introduction

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

  1. Usage analytics
  2. App analytics
  3. Survey and feedback
  4. Referral
  5. Rich push notifications
  6. Geofencing

SmartKarrot offers SDKs and private REST APIs for all its SaaS services. Our SDKs and APIs make it easy to quickly configure and integrate otherwise complex functionalities like referrals, user segmentation, geofencing, actions like rich push, gamification, surveys and feedback, analytics, donations, a full-fledged journey designer, wallets for cryptocurrency and fiat currency, and smart contracts on public and permissioned blockchains.

We have language bindings in Swift, Java, and JavaScript! You can view code examples in the area to the right, and you can switch the programming language of the examples with the tabs at the top right.

Development Quickstart

Integrating the SmartKarrot API requires only three quick steps:

  1. Get your API keys.
  2. Add our SDK to your app.
  3. 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: 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 4.0.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.5'

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 3: 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")

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")

Android App

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

UsageAnalytics.init(context, "app-id")

Web - JavaScript

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

UsageAnalytics.configure("app-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. Financial transactions involving fiat and cryptocurrency use test funds and not real funds.

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

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

Usage Analytics

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")
UsageAnalytics.getInstance().setUserId("your-app-user-id");
UsageAnalytics.setUser("your-app-user-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
UsageAnalytics.shared.set(value: 42, for: "T-shirt Size")
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

UsageAnalytics.shared.log(event: "Signed In")

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

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

EventParameters params = new EventParameters.Builder()
    .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);
UsageAnalytics.logEvent("Signed In");

var eventParams = {
    "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.

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());
            }
        });
    }
});

App Analytics

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

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.5'

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.

Referral

This session describes how to enable referrals in your iOS, Android and web apps.

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-Referral' 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.

Android App

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:referral:0.0.4.5'

Hybrid - Cordova/PhoneGap/Ionic

Referral features are already available in SmartKarrot plugin.

Step 2: Configure the Referral SDK

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

iOS App

Go to the project’s Capabilities tab and enable Associated Domains. Enable the Associated Domains Entitlement.

Add Invite link domain to Associated Domains List.

Format: applinks:<Invite Link Prefix>.aktion.link

Add URI scheme

Get URI Scheme from referral campaign's tech configuration and add it to URL Types in info.plist

Configure Referral

Call configure on referral SDK, make sure UsageAnalytics SDK ic configured before calling this function

Referral.shared.configure();

Add following callback in app delegate to handle referral links.

  func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey: Any] = [:]) -> Bool {
        return Referral.shared.handle(url: url)
    }

  func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([Any]?) -> Void) -> Bool {
        return Referral.shared.handleUniversalLink(userActivity: userActivity)
    }

Call handle from application(_app:, open url:options:) handle referral links.

Call handleUniversalLink from application(_ application:, continue userActivity:, restorationHandler:) handle referral links.

Android App

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

Referral.init(Context context);

Add this intent filter to the activies that will be opened on referral link clicks:

<intent-filter>
    <action android:name="android.intent.action.VIEW" />
    <category android:name="android.intent.category.DEFAULT" />
    <category android:name="android.intent.category.BROWSABLE" />
    <data android:scheme="https"
            android:host="<Invlite Link Prefix>.aktion.link" />
</intent-filter>

And inside your activity with the intent filter, add this line in onCreate and in onNewIntent:

Referral.getInstance().handle(getIntent());

Hybrid - Cordova/PhoneGap/Ionic

Hybrid - iOS

Enable support for universal links:

Go to the project’s Capabilities tab and enable Associated Domains. Enable the Associated Domains Entitlement.

Add Invite link domain to Associated Domains List.

Format: applinks:<Invite Link Prefix>.aktion.link

Invite Link Prefix - Replace this with the link prefix configured in referral campaign. Add URI scheme

Get URI Scheme from referral campaign's tech configuration and add it to URL Types in info.plist

Hybrid - Android

<intent-filter>
    <action android:name="android.intent.action.VIEW" />
    <category android:name="android.intent.category.DEFAULT" />
    <category android:name="android.intent.category.BROWSABLE" />
    <data android:scheme="https"
            android:host="<Invlite Link Prefix>.aktion.link" />
</intent-filter>

Add this intent filter to the activies that will be opened on referral link clicks.

Invite Link Prefix - Replace this with the link prefix configured in referral campaign.

Step 3: Run the Referral SDK

The SmartKarrot Referral SDK can be used to launch a single referral or to display a list of available referrals.

- List Available Referrals

 Referral.shared.listCampaigns(from: self, animated: true)
 Referral.getInstance().listCampaigns(context);
 # List Referrals
 # This will render from native view.

 # Set animated to true for iOS and null/undefined for Android
 cordova.plugins.SmartKarrot.listReferrals(animated: true, successCallBack(), failureCallBack());

The SmartKarrot SDK view lists all available referral campaigns. If only one campaign is available, the SDK launches it automatically.

- Show a Single Referral Dashboard

 Referral.shared.showDashboard(campaignId: <String>, from: <UIViewController>, animated: <Bool>)
 Referral.getInstance().showCampaignDashboard(context, campaignId)
  # Single Referral
  # This will render from native view.

  # For Android
  cordova.plugins.SmartKarrot.showDashboard("campaign-id", successCallBack(), failureCallBack());

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

Add this line to show a single referral campaign with given id. You can get the campaign id from SmartKarrot dashboard.

Rich Push Notifications

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)
    }    

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
            }
        };

Multilevel Setup

Upgrade to multilevel with few steps below:

  1. Upgrade your account to multilevel.
  2. Integrate REST API
  3. Configure the SmartKarrot integration.

Step 1: Upgrade to multilevel

Send a request to SmartKarrot Support (email: support@smartkarrot.com).

Step 2: Integrate REST API

Get API Key

Get 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/v3/

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/v3/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

{
  "accountId": "de8327c8-ece7-427a-ba8f-e4c7809ea716",
  "appId": "4ed062f1-fc38-4f32-a714-b63dc5399626",
  "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",
  "deviceId": "740f4707 bebcf74f 9b7c25d4 8e335894 5f6aa01d a5ddb387 462c7eaf 61bb78ad",
  "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 Your customer's unique identifier in your system.

Sample Output

{
  "status": "SUCCESS"
}

Response Body

Log user response.

Parameter Type Description
status String Enum SUCCESS, ERROR, INVALID_INPUT

Step 3: Configure the SmartKarrot Integration for Multilevel

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.

UsageAnalytics.init(context, "app-id", "customer-accountId")

Web - JavaScript

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

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

Hybrid - Cordova/PhoneGap/Ionic Plugin

Set User Id

UsageAnalytics.shared.set(userId: "your-app-user-id", "customer-account-id")
UsageAnalytics.getInstance().setUserId("your-app-user-id", "customer-accountId");
UsageAnalytics.setUser("your-app-user-id", "customer-account-id");

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.