Comment on page

Mobile SDKs

Integrating CustomerGlu on your Mobile Apps

Pre-Requisites

Android
iOS
Flutter
React Native
CustomerGlu Android SDK supports API 21 and above. Please ensure the minSDKVersion in the app's build.gradle file reflects the same.
Note:
If Proguard is enabled in the app, please add the following rule in
proguard-rules.pro file to ensure smooth working of CustomerGlu SDK:
-keep class com.customerglu.sdk.Modal.*{*;}

Permissions

Add the following permissions to the AndroidManifest.xml file
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
CustomerGlu iOS SDK supports IOS 11.0+ and requires Xcode 12 or above to build.
Android
iOS
CustomerGlu Flutter SDK supports API 21 and above. Please ensure the minSDKVersion in the app's build.gradle file reflects the same.
Firstly add the permission of internet in Manifest file
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Note:
If Proguard is enabled in the app, please add the following rule in the build.gradle file to ensure smooth working of CustomerGlu SDK.
buildTypes {
release {
// TODO: Add your own signing config for the release build.
// Signing with the debug keys for now, so `flutter run --release` works.
signingConfig signingConfigs.debug
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'),
'proguard-rules.pro'
}
}
Create a Proguard rules file if not present and add the following rule in Proguard Rules file:
-keep class com.customerglu.sdk.Modal.*{*;}

CustomerGlu iOS SDK supports IOS 11.0+ and requires Xcode 12 or above to build.
Android
iOS
CustomerGlu Android SDK supports API 21 and above. Please ensure the minSDKVersion in the app's build.gradle file reflects the same.
Note:
If Proguard is enabled in the app, please add the following rule in Proguard Rules file to ensure smooth working of CustomerGlu SDK:
-keep class com.customerglu.sdk.Modal.*{*;}

Permissions

Add the following permissions to the AndroidManifest.xml file
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
CustomerGlu iOS SDK supports IOS 11.0+ and requires Xcode 12 or above to build.

Installation

Android
iOS
Flutter
React Native
Add the following dependency to the app's build.gradle file:
dependencies{
implementation 'com.github.customerglu:CG-SDK-Android:v2.4.1'
}
If targetSdkVersion <=30, add the below code snippet in project level build.gradle file:
allprojects {
repositories {
...
maven { url "https://jitpack.io"}
}
}
If targetSdkVersion >=31, add the below code snippet in settings.gradle file:
dependencyResolutionManagement {
repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
repositories {
...
maven { url 'https://jitpack.io' }
}
}

Option 1: Using CocoaPods

Add CustomerGlu to your Podfile and run pod install
pod 'CustomerGlu'

Option 2: Using Swift Package Manager

Add https://github.com/customerglu/CG-iOS-SDK as a Swift Package Repository in Xcode and follow the instructions to add Intercom as a Swift Package.
Option 1
Add the CustomerGlu Flutter plugin in pubspec.yaml file
customerglu_plugin: ^1.3.3
Option 2
Run this command With Flutter:
flutter pub add customerglu_plugin
Option 1
Add the CustomerGlu React Native plugin in package.json file
"@customerglu/react-native-customerglu" : "1.3.3"
"@react-native-community/push-notification-ios": "^1.10.1",
"@react-native-firebase/app": "^15.1.1",
"@react-native-firebase/messaging": "^15.1.1",
"react-native-push-notification": "^8.1.1",
Option 2
Run this command With npm:
npm install @customerglu/react-native-customerglu

Initialise SDK

Android
iOS
Flutter
React Native
Add your WriteKey/API Key in meta-data of the AndroidManifest.xml file like this:
<meta-data android:name="CUSTOMERGLU_WRITE_KEY" android:value="YOUR_WRITE_KEY" />
<!-- only value should be changed -->
WriteKey - Mandatory (WriteKey/API Key is provided by CustomerGlu)
Define the global instance of CustomerGlu SDK in your Application class:
public CustomerGlu customerGlu;
customerGlu = CustomerGlu.getInstance();
For Initialising SDK add the following line in your Application Class (Mandatory)
CustomerGlu.getInstance().initializeSdk(getApplicationContext());
Only for V2.0.5 and above
Add the following key to the Info.plist file.
<key>CUSTOMERGLU_WRITE_KEY</key>
<string>YOUR_WRITE_KEY</string>
WriteKey - Mandatory (WriteKey/API Key is provided by CustomerGlu)
Define the global instance of CustomerGlu SDK
You can store the global instance of CustomerGlu SDK in a variable so you don't have to use CustomerGlu.getInstance for each function call
let customerGlu = CustomerGlu.getInstance
For Initialising SDK add the following line in your AppDelegate (Mandatory)
CustomerGlu.getInstance.initializeSdk()
Import the following package in classes where CG methods are used:
import “package:customerglu_plugin/customerglu_plugin.dart”;
Android
iOS
Add your WriteKey/API Key in meta-data of the AndroidManifest.xml file like this:
<meta-data android:name="CUSTOMERGLU_WRITE_KEY"
android:value="YOUR_WRITE_KEY" /> //Don't Change Name
WriteKey - Mandatory (WriteKey/API Key is provided by CustomerGlu)
Add the following key to the Info.plist file:
<key>CUSTOMERGLU_WRITE_KEY</key>
<string>YOUR_WRITE_KEY</string
WriteKey - Mandatory (WriteKey/API Key is provided by CustomerGlu)
Android
iOS
Add your WriteKey/API Key in meta-data of the AndroidManifest.xml file like this:
<meta-data android:name="CUSTOMERGLU_WRITE_KEY"
android:value="YOUR_WRITE_KEY" /> //Don't Change Name
WriteKey - Mandatory (WriteKey/API Key is provided
Add the following key to the Info.plist file:
<key>CUSTOMERGLU_WRITE_KEY</key>
<string>YOUR_WRITE_KEY</string
WriteKey - Mandatory (WriteKey/API Key is provided

Register User (Mandatory)

Registering a user of your platform with CustomerGlu is mandatory to be able to show any CG powered UIs and experiences to the user. Users need not be registered on your platform. You can check out the flow to handle non-logged/guest users here.
As the same registration method can also be used to update user attributes, it is recommended to use this method on every app launch, after signing in/up and reaching the app home page.
Android
iOS
Flutter
React Native
Use the given function to register a user with CustomerGlu:
customerGlu.registerDevice(this,userData,new DataListner() {
//this method registers the user
@Override
public void onSuccess(RegisterModal registerModal) {
Toast.makeText(getApplicationContext(), "Registered", Toast.LENGTH_SHORT).show();
}
@Override
public void onFail(String message) {
Toast.makeText(getApplicationContext(), ""+message, Toast.LENGTH_SHORT).show();
}
}
Note: The Register function is also used to update the user attributes

Function Parameters:

  1. 1.
    Context: this/getApplicationContext()
  2. 2.
    userData: A HashMap that holds user information
Sample UserData object
Map<String,Object> userData = new HashMap<>();
String user_id="testUser_1";
String fcmToken="FCM_TOKEN_OF_DEVICE";
userData.put("userId",user_id); // Mandatory:any identifier to uniquely identify a user of your platform
userdata.put("firebaseToken",fcmToken); // for enabling Firebase Notifications
userdata.put("referredBy": "userAId"); // for referrals
userdata.put("referralCode": "userAReferralCode"); // for referrals
Map<String,String> customAttributes = new HashMap<>();
// any custom key-value pairs, which may be used for targeting can be sent as customAttributes
// segments can be created by applying filters on these customAttributes
// campaigns can be launched on specific segments
customAttributes.put("orderCount",5);
customAttributes.put("age",21);
customAttributes.put("city","Mumbai");
userdata.put("customAttributes",customAttributes);
Map<String,String> profile = new HashMap<>();
profile.put("firstName","jane");
userdata.put("profile",profile);
Note: You can check out the complete userData object payload here.
Use the given function to register a user with CustomerGlu:
customerGlu.registerDevice(userdata: userData) { success in
if success {
print("Register Successfully")
} else {
print("error")
}
}
Note: The Register function is also used to update the user attributes

Function Parameters:

  1. 1.
    userData: A Dictionary that holds user information
Sample UserData object
var userData = [String: AnyHashable]()
userData["userId"] = "testUser_1" // Mandatory:any identifier to uniquely identify a user of your platform
userData["userName"] = "John Doe"
userData["firebaseToken"] = CustomerGlu.getInstance.fcmToken // for enabling Firebase Notifications
userData["apnsDeviceToken"] = CustomerGlu.getInstance.apnToken // for enabling APNS Notifications
userdata["referredBy": "userAId"]; // for referrals
userdata["referralCode": "userAReferralCode"]; // for referrals
var customAttributes = [String: AnyHashable]()
// any custom key-value pairs, which may be used for targeting can be sent as customAttributes
// segments can be created by applying filters on these customAttributes
// campaigns can be launched on specific segments
customAttributes["orderCount"] = 5
customAttributes["city"] = "Mumbai"
userData["customAttributes"] = customAttributes
var profile = [String: AnyHashable]()
profile["firstName"] = "jane"
userData["profile"] = profile
Note: You can check out the complete userData object payload here
Use the given function to register a user with CustomerGlu :
bool is_registered = await CustomergluPlugin.registerDevice(userData)
Note: The Register function is also used to update the user attributes
Sample UserData object
var userData = {
'userId': user_id, // Mandatory:any identifier to uniquely identify a user of your platform
'firebaseToken': "FCM_TOKEN_OF_DEVICE", // for enabling Firebase Notifications
'referredBy': "userAId", // for referrals
'referralCode': "userAReferralCode", // for referrals
'customAttributes':{
// any custom key-value pairs, which may be used for targeting can be sent as customAttributes
// segments can be created by applying filters on these customAttributes
// campaigns can be launched on specific segments
"orderCount":5,
"city":"Mumbai"
}
'profile':{
"firstName":"JaneDoe"
}
}
Note: You can check out the complete userData object payload here.
Use the given function to register a user with CustomerGlu :
import { RegisterDevice } from '@customerglu/react-native-customerglu';
var ok = await RegisterDevice(userData);
if (ok == true) {
// Success
}else {
// fail
}
Note: The Register function is also used to update the user attributes
Sample UserData object
let userData = {
'userId': user_id, // Mandatory:any identifier to uniquely identify a user of your platform
'firebaseToken': "FCM_TOKEN_OF_DEVICE", // for enabling Firebase Notifications
'apnsDeviceToken': "APN_TOKEN_OF_DEVICE", // for enabling APN Notifications only for IOS
'referredBy': "userAId", // for referrals
'referralCode': "userAReferralCode", // for referrals
'customAttributes':{
// any custom key-value pairs, which may be used for targeting can be sent as customAttributes
// segments can be created by applying filters on these customAttributes
// campaigns can be launched on specific segments
"orderCount":5,
"city":"Mumbai"
}
'profile':{
"firstName":"JaneDoe"
}
}
Note: You can check out the complete userData object payload here.

Clear Data on Logout (Mandatory)

Use the given function when the user logs out, to clear CustomerGlu SDK cached data like user_id, token, entry point related data, etc.
Android
iOS
Flutter
React Native
customerGlu.clearGluData(getApplicationContext());
customerGlu.clearGluData();
CustomergluPlugin.clearGluData()
import {dataClear} from '@customerglu/react-native-customerglu';
dataClear();

Handling Webview Events

CG Webviews send the following types of events to the app:
  • Deeplink redirection Events (OPEN_DEEPLINK): Redirect to a given screen on click of buttons from CustomerGlu UIs Example: Clicking on "Go To Cart" should redirect to the Cart Screen
  • Analytics Events (ANALYTICS): Send click analytics events on CG UI directly from the app to your servers/CDP Platform Example: coupon code copied event
Note: Analytics events need to be explicitly enabled

Enable Analytics Events

If click analytics are to be captured directly via the app, you can enable the analytics events by using the given function:
Android
iOS
Flutter
React Native
customerGlu.enableAnalyticsEvent(true);
customerGlu.enableAnalyticsEvent(event: true)
CustomergluPlugin.enableAnalyticsEvent(true)
import {enableAnalytic} from '@customerglu/react-native-customerglu';
enableAnalytic(true);

Handling Events

Android
iOS
Flutter
React Native
For handling Deeplink or Analytics events triggered by the webview, you need to register a broadcast receiver and handle the logic for the respective event:
BroadcastReceiver mMessageReceiver;
mMessageReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
try {
if(intent.getAction().equalsIgnoreCase("CUSTOMERGLU_DEEPLINK_EVENT"))
{
String data = intent.getStringExtra("data");
JSONObject jsonObject = new JSONObject(data);
String message = jsonObject.getString("deepLink");
// Add the logic to redirect to appropriate page
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
}
/* If you want to listen analytics event */
if(intent.getAction().equalsIgnoreCase("CUSTOMERGLU_ANALYTICS_EVENT"))
{
String data = intent.getStringExtra("data");
JSONObject jsonObject = new JSONObject(data);
Toast.makeText(getApplicationContext(), jsonObject.toString(), Toast.LENGTH_LONG).show();
//This Event can be forwarded to your Servers/CDP tool
}
}
catch (Exception e)
{
System.out.println(e);
}
}
};
registerReceiver(mMessageReceiver,new IntentFilter("CUSTOMERGLU_DEEPLINK_EVENT"));
/* If you want to listen analytics event register the below reciever*/
registerReceiver(mMessageReceiver,new IntentFilter("CUSTOMERGLU_ANALYTICS_EVENT"));
Note: Do not unregister the broadcast receiver in the app lifecycle.
For handling Deeplink events triggered by the webview, you need to add a notification observer:
NotificationCenter.default.addObserver(
self,
selector: #selector(self.catchDeeplinkNotification),
name: Notification.Name("CUSTOMERGLU_DEEPLINK_EVENT"),
object: nil)
@objc private func catchDeeplinkNotification(notification: NSNotification) {
//do stuff using the userInfo property of the notification object
if let userInfo = notification.userInfo as? [String: Any] // or use if you know the type [AnyHashable : Any]
{
print(userInfo)
}
}

Analytics Events

For handling analytics events triggered by the webview, you need to a notification observer:
NotificationCenter.default.addObserver(
self,
selector: #selector(self.catchAnalyticsNotification),
name: Notification.Name("CUSTOMERGLU_ANALYTICS_EVENT"),
object: nil)
@objc private func catchAnalyticsNotification(notification: NSNotification) {
if let userInfo = notification.userInfo as? [String: Any]
{
print(userInfo)
}
}
For handling Deeplink and Analytics broadcast events in Flutter you need to create a MethodChannel and handle the logic for the respective event:
static const broadcast_channel = MethodChannel("CUSTOMERGLU_EVENTS");
broadcast_channel.setMethodCallHandler((call) async {
switch (call.method) {
case "CUSTOMERGLU_DEEPLINK_EVENT":
print("CUSTOMERGLU_DEEPLINK_EVENT");
print(call.arguments);
var json = jsonDecode(call.arguments);
print(json["name"]);
break;
case "CUSTOMERGLU_ANALYTICS_EVENT":
print("CUSTOMERGLU_ANALYTICS_EVENT");
print(call.arguments);
var json = jsonDecode(call.arguments);
print(json["event_name"]);
break;
}
});
For handling Deeplink and Analytics broadcast events in React-Native you need to add following code in your js file :
useEffect(() => {
const { Rncustomerglu } = NativeModules;
const RncustomergluManagerEmitter = new NativeEventEmitter(Rncustomerglu);
const eventanalytics = RncustomergluManagerEmitter.addListener(
'CUSTOMERGLU_ANALYTICS_EVENT',
(reminder) => console.log('CUSTOMERGLU_ANALYTICS_EVENT...', reminder)
);
const eventdeeplink = RncustomergluManagerEmitter.addListener(
'CUSTOMERGLU_DEEPLINK_EVENT',
(reminder) =>
if (Platform.OS === ‘ios’) {
reminder = reminder.data
}
console.log('CUSTOMERGLU_DEEPLINK_EVENT...', reminder)
);
}
return () => {
eventanalytics.remove();
eventdeeplink.remove();
}
}, []);

Nudge Configuration

Nudge Configuration is an object that can be passed as an optional parameter to the openWallet, loadCampaignById and openNudge methods to configure the layout, height, and other related properties for the webview.
Android
iOS
Flutter
React-Native
NudgeConfiguration nudgeConfiguration = new NudgeConfiguration();
nudgeConfiguration.setAbsoluteHeight(700);
nudgeConfiguration.setRelativeHeight(60);
nudgeConfiguration.setLayout("bottom-popup");
nudgeConfiguration.setOpacity(0.9);
nudgeConfiguration.setCloseOnDeepLink(true);
let nudgeConfiguration = CGNudgeConfiguration()
nudgeConfiguration.closeOnDeepLink = false
nudgeConfiguration.opacity = 0.9
nudgeConfiguration.layout = "bottom-default"
nudgeConfiguration.absoluteHeight = 100
nudgeConfiguration.relativeHeight = 70
nudgeConfiguration = NudgeConfiguration(relativeHeight: 50,
absoluteHeight: 700, layout: "bottom-slider",closeOnDeepLink: true,
opacity: 0.7),
let nudgeConfigurationData = {
nudgeConfiguration:{
layout:'middle-default',
opacity:'0.8',
closeOnDeepLink:true,
absoluteHeight:'50',
relativeHeight:'60'
},
};
  1. 1.
    Relative Height - It accepts an integer value from 1 to 100 as Percentage(%) of device screen height. Default value: 70
  2. 2.
    Absolute Height - It accepts an integer value greater than 0. It follows native units like px (iOS) and dp (android) to adjust height. Default value: 0
Provide either relative or absolute dimensions for height. Priority is given to relative height in case of both being defined.
3. Layout - Set the layout of nudge. Possible values: [full-default, middle-popup, bottom-popup, bottom-slider] | Refer here to see al supported layouts. Default value : full-default
4. closeOnDeepLink - If set to true , the Webview will be dismissed automatically if the user is redirected to an app screen from a button in the UI. Default value: false
5. Opacity - For any of the layouts except for fullscreen, set the background opacity of the screen not covered by content. It can take values between 0 to 1, where 0 means fully transparent and 1 means fully opaque background. Default value: 0.5

Open Wallet

CustomerGlu offers a fully customisable wallet page which contains challenges, games, rewards and other user specific information as shown below:
Use the following function to open the wallet screen powered by CustomerGlu:
Android
iOS
Flutter
React native
customerGlu.openWallet(getApplicationContext(),nudgeConfiguration);

Function Parameters

  1. 1.
    Context: this/getApplicationContext()
  2. 2.
    NudgeConfiguration(optional) : Please refer to the NudgeConfiguration
customerGlu.openWallet(nudgeConfiguration: nudgeConfiguration)

Function Parameters

NudgeConfiguration(optional) : Please refer to the NudgeConfiguration
CustomergluPlugin.openWallet(nudgeConfiguration: nudgeConfiguration)
Function Parameters:
NudgeConfiguration(optional) : Please refer to the NudgeConfiguration
import { openWallet } from '@customerglu/react-native-customerglu';
openWallet(nudgeConfigurationData)
Function Parameters:
NudgeConfiguration(optional) : Please refer to the NudgeConfiguration

Open Campaign

You can also open specific campaigns by using the campaignId or tag assigned to a campaign.
CampaignId
Finding the campaignId
Tag
Adding a tag
Use the following function to open a specific campaign:
Android
iOS
Flutter
React Native
customerGlu.loadCampaignById(getApplicationContext(),"CAMPAIGN_ID/TAG",nudgeConfiguration);

Function Parameters

  1. 1.
    Context: this/getApplicationContext()
  2. 2.
    CampaignId/Tag : Unique Identifier assigned to a campaign, can be copied from the dashboard.
  3. 3.
    NudgeConfiguration(optional) : Please refer to the NudgeConfiguration
customerGlu.loadCampaignById(campaign_id: "CAMPAIGN_ID/TAG", nudgeConfiguration: nudgeConfiguration);

Function Parameters

  1. 1.
    CampaignId/Tag : Unique Identifier assigned to a campaign, can be copied from the dashboard.
  2. 2.
    NudgeConfiguration(optional) : Please refer to the NudgeConfiguration
CustomergluPlugin.loadCampaignById("CAMPAIGN_ID/TAG",nudgeConfiguration: nudgeConfiguration);

Function Parameters

  1. 1.
    CampaignId/Tag : Unique Identifier assigned a campaign, can be copied from the dashboard.
  2. 2.
    NudgeConfiguration - Please refer to NudgeConfiguration
import { loadCampaginById } from '@customerglu/react-native-customerglu';
loadCampaginById("CAMPAIGN_ID/TAG",nudgeConfigurationData)

Function Parameters

  1. 1.
    CampaignId/Tag : Unique Identifier assigned a campaign, can be copied from the dashboard.
  2. 2.
    NudgeConfiguration(optional) : Please refer to the NudgeConfiguration
Note: If the value of campaignId/tag provided is empty/invalid, wallet will be opened by default. To handle this case in a custom manner, CG_INVALID_CAMPAIGN_ID event can be consumed

Verify CampaignId

You can verify the campaignId before opening the campaign using the below method
Android
iOS
customerGlu.isCampaignValid("campaignId");
customerGlu.isCampaignValid("campaignId");
Above method returns the boolean value is the campaign valid or not.
Function Parameters
  1. 1.
    CampaignId/Tag : Unique Identifier assigned to a campaign, can be copied from the dashboard.

Handling Invalid Campaign ID

If the campaignId is invalid, SDK will trigger the CG_INVALID_CAMPAIGN_ID event. It can be listened to and consumed, similar to the Analytics and Open Deeplink events:
Android
iOS
Flutter
React native
Register a Broadcast Receiver, listen for the banner load event and handle the logic:
BroadcastReceiver mMessageReceiver;
mMessageReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// Extract data included in the Intent
try {
if (intent.getAction().equalsIgnoreCase("CG_INVALID_CAMPAIGN_ID")) {
String data = intent.getStringExtra("data");
JSONObject jsonObject = new JSONObject(data);
System.out.println(jsonObject.toString());
}
} catch (Exception e) {
System.out.println(e);
}
}
};
registerReceiver(mMessageReceiver, new IntentFilter("CG_INVALID_CAMPAIGN_ID"));
NotificationCenter.default.addObserver(
self,
selector: #selector(self.cgInvalidCampaignId),
name: Notification.Name("CG_INVALID_CAMPAIGN_ID"),
object: nil)
// Method to listen notification with name CUSTOMERGLU_BANNER_LOADED
@objc private func cgInvalidCampaignId(notification: NSNotification) {
if let userInfo = notification.userInfo as? [String: Any]
{
print(userInfo)
}
}
static const broadcast_channel = MethodChannel("CUSTOMERGLU_EVENTS");
broadcast_channel.setMethodCallHandler((call) async {
switch (call.method) {
case "CG_INVALID_CAMPAIGN_ID":
print(call.arguments);
break;
}
});
useEffect(() => {
const { Rncustomerglu