Mobile SDKs

Integrating CustomerGlu on your Mobile Apps

Pre-Requisites

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

Installation

Add the following dependency to the app's build.gradle file:

dependencies{
    implementation 'com.customerglu:CustomerGluLibrary:2.5.4'
}

Add the below code snippet in project level build.gradle file:

allprojects {
    repositories {
        ...
        mavenCentral()
    }
}

For new Projects , add the below code snippet in settings.gradle file (if above not work):

dependencyResolutionManagement {
    repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
    repositories {
        ...
        mavenCentral()

    }
}

Initialise SDK

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

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.

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. Context: this/getApplicationContext()

  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.

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.

customerGlu.clearGluData(getApplicationContext());

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:

customerGlu.enableAnalyticsEvent(true);

Handling Events

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.

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.

NudgeConfiguration nudgeConfiguration = new NudgeConfiguration();
nudgeConfiguration.setAbsoluteHeight(700);
nudgeConfiguration.setRelativeHeight(60);
nudgeConfiguration.setLayout("bottom-popup");
nudgeConfiguration.setOpacity(0.9);
nudgeConfiguration.setCloseOnDeepLink(true);
 
  1. Relative Height - It accepts an integer value from 1 to 100 as Percentage(%) of device screen height. Default value: 70

  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:

customerGlu.openWallet(getApplicationContext(),nudgeConfiguration);

Function Parameters

  1. Context: this/getApplicationContext()

  2. 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

Tag

Use the following function to open a specific campaign:

customerGlu.loadCampaignById(getApplicationContext(),"CAMPAIGN_ID/TAG",nudgeConfiguration);

Function Parameters

  1. Context: this/getApplicationContext()

  2. CampaignId/Tag : Unique Identifier assigned to a campaign, can be copied from the dashboard.

  3. 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

customerGlu.isCampaignValid("campaignId");

Above method returns the boolean value is the campaign valid or not.

Function Parameters

  1. CampaignId/Tag : Unique Identifier assigned to a campaign, can be copied from the dashboard.

Entry Points

Entry Points are the various ways how users can discover and explore experiences like games, challenges, rewards, nudges, wallet, etc.

The following entry points are supported by CustomerGlu Mobile SDKs:

  1. Banner

  2. Floating Button/Launcher

  3. Popup

  4. Embed View

Enable Entry Points

Use the given function to enable Entry Points in the app (should be called on every app launch):

customerGlu.enableEntryPoints(getApplicationContext(), true);

Setting up Banners

Banners need elements with unique ids to be pre-defined in the app screens. These components need to be added at all the places where banners need to show up- that is why it is important to add these elements generously, covering all possible use cases where a banner might be needed, as an app release will be required to edit them.

Note: These components will not take any screen space and will remain hidden in the background unless the banners configured are activated explicitly from the dashboard.

Add the following component, wherever a banner might be needed, in the Activity’s layout file (XML):

<com.customerglu.sdk.entrypoints.Banner
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/someUniqueIdentifier"/> //same id should be configured on the dashboard

Note : The id or bannerId is mandatory and the exact same id needs to be set on the dashboard as the bannerId in the entry point configuration section. Please follow a semantic nomenclature like screenName_banner_1 for the ids for ease of configuration on the dashboard.

The banner will be hidden automatically in cases like the banner being disabled, user not eligible to see the banner (not in segment/campaign already completed).

If the status of banner components is also needed by the app, for use cases like changing the parent container size, depending on visibility of the banner, the following method can be used to check the banner availability:

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("CUSTOMERGLU_BANNER_LOADED")) {

                        String data = intent.getStringExtra("data"); 
                         JSONObject jsonObject = new JSONObject(data);
                         
                         System.out.println(jsonObject.toString());
                       //  Output - {"banner1":2,"banner2":0}
           // Key is the bannerId and value is number of banners in the Banner Component
                    }

                } catch (Exception e) {
                    System.out.println(e);
                }
            }

        };

        registerReceiver(mMessageReceiver, new IntentFilter("CUSTOMERGLU_BANNER_LOADED"));

Setting up Embed View

Embed views can be used to embed CustomerGlu campaigns and screens directly in your native screens. Embed view works similar to Banners and needs elements with unique ids to be pre-defined in the app screens. These components need to be added at all the places where Embed view need to show up- that is why it is important to add these elements generously, covering all possible use cases where a Embed view might be needed, as an app release will be required to edit them.

Note: These components will not take any screen space and will remain hidden in the background unless the embed views configured are activated explicitly from the dashboard.

Add the following component, wherever a banner might be needed, in the Activity’s layout file (XML):

 <com.customerglu.sdk.entrypoints.CGEmbedView
  android:layout_width="wrap_content"
  android:layout_height="wrap_content" 
  android:id="@+id/someUniqueIdentifier"/> //same id should be configured on the dashboard

Note : The id or bannerId is mandatory and the exact same id needs to be set on the dashboard as the bannerId in the entry point configuration section. Please follow a semantic nomenclature like screenName_banner_1 for the ids for ease of configuration on the dashboard.

Setting up Floating Buttons and Popups and PIP

As Floating Buttons and Popups are overlays, they need no special components to be predefined like Banners. They only need to be added on all screens/activities of the app and each screen should be assigned a name/identifier which can then be used to configure these entrypoints via the dashboard.

The given function should be used on every Activity's onResume Method to support adding the floating button/popup entry points on the activity via the dashboard:

@Override
protected void onResume() {
    super.onResume();
    customerGlu.showEntryPoint(MainActivity.this,"screenName");
} 

Handle CustomerGlu Nudges

The push and in-app nudges sent via CustomerGlu need to be handled by the app.

Add the displayCustomerGluNotification method in the Firebase onMessageRecieved callback to handle nudges, as shown below:

@RequiresApi(api = Build.VERSION_CODES.M)
@Override
public void onMessageReceived(@NonNull RemoteMessage remoteMessage) {
    super.onMessageReceived(remoteMessage);
    JSONObject data = null;
    JSONObject json = new JSONObject(remoteMessage.getData());

     customerGlu.displayCustomerGluNotification(this,json,R.drawable.icon,0.5,true);

    }

Function Parameters:

  1. context : this/getApplicationContext()

  2. json : The json object of the remote message.

  3. icon : The App Icon to be displayed for the push notifications.

  4. opacity: For any of the layouts except for fullscreen, set the background opacity of the screen not covered by content. Can take values between 0 to 1, where 0 means fully transparent and 1 means fully opaque background. (Default value is 0.5)

  5. autoclosewebview : 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

Note: App icon should be in PNG format with size less than 100KB.

Handling Nudges for Background/Killed State

Add the given snippet on the Splash Screen to fetch nudge data and then call the displayCustomerGluBackgroundNotification method on the same

Intent parent_intent = getIntent();
String intentSource = "none";
    if (parent_intent != null) {
        if (parent_intent.getExtras() != null) {
            intentSource = parent_intent.getExtras().getString("type", "none");
            String myType = parent_intent.getExtras().getString("from", "none");
                if (intentSource.equalsIgnoreCase("CustomerGlu")) {
                    Bundle data = parent_intent.getExtras();
                    JSONObject json = new JSONObject();
                    Set<String> keys = data.keySet();
                    for (String key : keys) {
                        try {
                            json.put(key, JSONObject.wrap(data.get(key)));
                            } catch (JSONException e) {
                                        //Handle exception here
                            }
                            }
                    Intent i = new Intent(SplashScreen.this, MainActivity.class);
                    i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                    startActivity(i);
                    CustomerGlu.getInstance().displayCustomerGluBackgroundNotification(getApplicationContext(), json);


                            }
                        }
      }