# Mobile SDKs

## Pre-Requisites

{% tabs %}
{% tab title="Android" %}
CustomerGlu Android SDK supports API 21 and above. Please ensure the `minSDKVersion` in the app's `build.gradle` file reflects the same.

{% hint style="info" %}
​**Note:**

If **Proguard** is enabled in the app, please add the following rule in&#x20;

`proguard-rules.pro` file to ensure smooth working of CustomerGlu SDK:

```java
-keep class com.customerglu.sdk.Modal.*{*;}
```

{% endhint %}

### Permissions

Add the following permissions to the `AndroidManifest.xml` file

```xml
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
```

{% endtab %}

{% tab title="iOS" %}
CustomerGlu iOS SDK supports **IOS 12.0+** and requires **Xcode 12** or above to build.
{% endtab %}

{% tab title="Flutter" %}
{% tabs %}
{% tab title="Android" %}
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

```xml
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
```

{% hint style="info" %}
**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.&#x20;

```java
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:

```java
-keep class com.customerglu.sdk.Modal.*{*;}
```

###

{% endhint %}
{% endtab %}

{% tab title="iOS" %}
CustomerGlu iOS SDK supports **IOS 11.0+** and requires **Xcode 12** or above to build.
{% endtab %}
{% endtabs %}
{% endtab %}

{% tab title="React Native" %}
{% tabs %}
{% tab title="Android" %}
CustomerGlu Android SDK supports API 21 and above. Please ensure the `minSDKVersion` in the app's `build.gradle` file reflects the same.

{% hint style="info" %}
​**Note:**

If **Proguard** is enabled in the app, please add the following rule in Proguard Rules file to ensure smooth working of CustomerGlu SDK:

```java
-keep class com.customerglu.sdk.Modal.*{*;}
```

{% endhint %}

### Permissions

Add the following permissions to the `AndroidManifest.xml` file

```xml
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
```

{% endtab %}

{% tab title="iOS" %}
CustomerGlu iOS SDK supports **IOS 11.0+** and requires **Xcode 12** or above to build.
{% endtab %}
{% endtabs %}
{% endtab %}
{% endtabs %}

## Installation

{% tabs %}
{% tab title="Android" %}
Add the following dependency to the app's `build.gradle` file:

```java
dependencies{
    implementation 'com.customerglu:CustomerGluLibrary:3.0.4'
}
```

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

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

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

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

    }
}
```

{% endtab %}

{% tab title="iOS" %}

#### 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.&#x20;

![](https://1004846827-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-M0ahLW2WavtwcwNbSR9%2Fuploads%2FmgQhjKelyCAwG6nN1Ory%2FScreenshot%202022-01-11%20at%206.43.03%20PM.png?alt=media\&token=aaaa0e98-656b-4730-a135-1f35ffd38a65)
{% endtab %}

{% tab title="Flutter" %}
**Option 1**&#x20;

Add the CustomerGlu Flutter plugin in `pubspec.yaml` file&#x20;

```dart
customerglu_plugin: ^2.1.0
```

**Option 2**&#x20;

Run this command With Flutter:

```shell
flutter pub add customerglu_plugin
```

{% endtab %}

{% tab title="React Native" %}
**Option 1**&#x20;

Add the CustomerGlu React Native plugin in package.json file

```dart
"@customerglu/react-native-customerglu" : "2.1.1"
"@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**&#x20;

Run this command With npm:

```shell
npm install @customerglu/react-native-customerglu
```

{% endtab %}
{% endtabs %}

## Initialise SDK

{% tabs %}
{% tab title="Android" %}
Add your WriteKey/API Key in meta-data of the `AndroidManifest.xml` file like this:

```xml
<meta-data android:name="CUSTOMERGLU_WRITE_KEY" android:value="YOUR_WRITE_KEY" /> 
<!-- only value should be changed -->
```

{% hint style="info" %}
**WriteKey** - Mandatory (WriteKey/API Key is provided by CustomerGlu)
{% endhint %}

**Define the global instance of CustomerGlu SDK** in  your Application class:

```java
public CustomerGlu customerGlu;
customerGlu = CustomerGlu.getInstance();
```

For **Initialising SDK** add the following line in your **Application Class (Mandatory)**

```java
CustomerGlu.getInstance().initializeSdk(getApplicationContext());
```

{% endtab %}

{% tab title="iOS" %}
&#x20;Add the following key to the `Info.plist` file.

```xml
<key>CUSTOMERGLU_WRITE_KEY</key>
<string>YOUR_WRITE_KEY</string>
```

{% hint style="info" %}
**WriteKey** - Mandatory (WriteKey/API Key is provided by CustomerGlu)
{% endhint %}

**Define the global instance of CustomerGlu SDK**&#x20;

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

```swift
let customerGlu = CustomerGlu.getInstance
```

For **Initialising SDK** add the following line in your **AppDelegate  (Mandatory)**

```java
CustomerGlu.getInstance.initializeSdk()
```

{% endtab %}

{% tab title="Flutter" %}
To initialize the SDK, the initialization method must be called at every app launch before using any other method from the CG SDK. This should be done in main.dart at the entry point of the app. Use the following values to specify the region: \
\
"**in**" → Indian Region \
"**me**" → Middle-East Region \
"**us**" → USA Region

```dart
import 'package:customerglu_plugin/customerglu_plugin.dart';

  
void main() {
  WidgetsFlutterBinding.ensureInitialized();

  // Initialize CustomerGlu SDK with the desired region ("in", "me", or "us")
  CustomergluPlugin.initSDK("me"); // Change "me" to "in" or "us" as needed

  runApp(MyApp());
}
```

{% tabs %}
{% tab title="Android" %}
Add your WriteKey/API Key in meta-data of the `AndroidManifest.xml` file like this:

```xml
<meta-data android:name="CUSTOMERGLU_WRITE_KEY"  
    android:value="YOUR_WRITE_KEY" />  //Don't Change Name
```

{% hint style="info" %}
**WriteKey** - Mandatory (WriteKey/API Key is provided by CustomerGlu)
{% endhint %}
{% endtab %}

{% tab title="iOS" %}
Add the following key to the `Info.plist` fil&#x65;**:**

```xml
<key>CUSTOMERGLU_WRITE_KEY</key>
<string>YOUR_WRITE_KEY</string
```

{% hint style="info" %}
**WriteKey** - Mandatory (WriteKey/API Key is provided by CustomerGlu)
{% endhint %}

{% endtab %}
{% endtabs %}
{% endtab %}

{% tab title="React Native" %}
{% tabs %}
{% tab title="Android" %}
Add your WriteKey/API Key in meta-data of the `AndroidManifest.xml` file like this:

```xml
<meta-data android:name="CUSTOMERGLU_WRITE_KEY"  
    android:value="YOUR_WRITE_KEY" />  //Don't Change Name
```

{% hint style="info" %}
**WriteKey** - Mandatory (WriteKey/API Key is provided&#x20;
{% endhint %}

To initialize the SDK the initialization method must be called at every app launch before using any other method from the CG SDK. use it in index.js at entry point of the app<br>

```
import { initCGSDK } from '@customerglu/react-native-customerglu';

initCGSDK("in");  
```

{% endtab %}

{% tab title="iOS" %}
Add the following key to the `Info.plist` fil&#x65;**:**

```xml
<key>CUSTOMERGLU_WRITE_KEY</key>
<string>YOUR_WRITE_KEY</string>
```

{% hint style="info" %}
**WriteKey** - Mandatory (WriteKey/API Key is provided&#x20;
{% endhint %}

\
To initialize the SDK the initialization method must be called at every app launch before using any other method from the CG SDK. use it in **index.js** or **App.js** at entry point of the app<br>

```
import { initCGSDK } from '@customerglu/react-native-customerglu';

initCGSDK("in");  

```

{% endtab %}
{% endtabs %}
{% endtab %}
{% endtabs %}

## Register User (Mandatory)&#x20;

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](https://docs.customerglu.com/miscellaneous-topics/handling-non-logged-in-users).

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.

{% tabs %}
{% tab title="Android" %}
This method is now used to register the user with CG. Make sure to call it on every **App launch**. In **SDK v3.0.0** or above we are **not accepting CustomAttributes** here in the registerDevice:

<pre class="language-java"><code class="lang-java">
customerGlu.registerDevice(this, registerData, new DataListner() {
            //this method register your device with CG and load the campaigns
            @Override
            public void onSuccess(Boolean success) {
<strong>                Toast.makeText(getApplicationContext(), "Registered" , Toast.LENGTH_SHORT).show();
</strong>            }
            @Override
            public void onFail(String message) {
                Toast.makeText(getApplicationContext(), "" + message, Toast.LENGTH_SHORT).show();
            }
        }
);

</code></pre>

{% hint style="info" %}
**Note:** The Register function is  used to generate token only
{% endhint %}

#### Function Parameters:

1. **Context:** this/getApplicationContext()
2. **userData:** A HashMap that holds user information

**Sample UserData object**

```java
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
```

{% hint style="info" %}
**Note:** You can check out the complete userData object payload [here](https://docs.customerglu.com/integration-doc#register-a-device).
{% endhint %}
{% endtab %}

{% tab title="iOS" %}
This method is now used to register the user with CG. Make sure to call it on every **App launch**. In **SDK v3.0.0** or above we are **not accepting CustomAttributes** here in the registerDevice:

```swift
customerGlu.registerDevice(userdata: userData) { success in
            if success {
               print("Register Successfully")
            } else {
                print("error")
            }
        }
```

{% hint style="info" %}
**Note:** The Register function is used to generate Token only
{% endhint %}

#### Function Parameters:

1. **userData:** A Dictionary that holds user information

**Sample UserData object**

<pre class="language-swift"><code class="lang-swift"> 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
<strong>        userdata["referralCode": "userAReferralCode"]; // for referrals
</strong>       
</code></pre>

{% hint style="info" %}
**Note:** You can check out the complete userData object payload [here](https://docs.customerglu.com/integration-doc#register-a-device)
{% endhint %}
{% endtab %}

{% tab title="Flutter" %}
Use the given function to register a user with CustomerGlu :&#x20;

```dart
bool is_registered = await CustomergluPlugin.registerDevice(userData)
```

{% hint style="info" %}
**Note:** The Register function is also used to update the user attributes
{% endhint %}

**Sample UserData object**

```dart
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"
 }
}
```

{% hint style="info" %}
**Note:** You can check out the complete userData object payload [here](https://docs.customerglu.com/integration-doc#register-a-device).
{% endhint %}
{% endtab %}

{% tab title="React Native" %}
Use the given function to register a user with CustomerGlu :&#x20;

```dart
import { RegisterDevice } from '@customerglu/react-native-customerglu';
var ok = await RegisterDevice(userData);
if (ok == true) {
// Success 
}else { 
// fail
} 

```

{% hint style="info" %}
**Note:** The Register function is also used to update the user attributes
{% endhint %}

**Sample UserData object**

```dart
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"
 }
}
```

{% hint style="info" %}
**Note:** You can check out the complete userData object payload [here](https://docs.customerglu.com/integration-doc#register-a-device).
{% endhint %}
{% endtab %}
{% endtabs %}

## **UpdateUser Attributes**

This method is used to update the user custom Attributes to add users to the respective segments

{% tabs %}
{% tab title="Android" %}

```java
Map<String, Object> attributes = new HashMap<>();
attributes.put("city", "Mumbai");
customerGlu.updateUserAttributes(getApplicationContext(), attributes);

```

{% endtab %}

{% tab title="iOS" %}

<pre class="language-java"><code class="lang-java">var myCustomAttributes = [String: AnyHashable]()
myCustomAttributes["city"] = "Mumbai"
<strong>CustomerGlu.getInstance.updateUserAttributes(customAttributes: myCustomAttributes)
</strong></code></pre>

{% endtab %}

{% tab title="Flutter" %}

```dart
var attributes = {
'count': 50
}
CustomergluPlugin.updateUserAttributes(attributes)
```

{% endtab %}

{% tab title="React Native" %}

```javascript
  userAttributes = {
            city : "Mumbai"
    }
    UpdateUserAttributes(userAttributes)
```

{% endtab %}
{% endtabs %}

## **UpdateUser Profile**

You can update the user profile and customAttributes values by using following method:

{% hint style="info" %}
**Note:** You can check out the complete userData object payload [here](https://docs.customerglu.com/integration-doc#register-a-device).
{% endhint %}

{% tabs %}
{% tab title="Android" %}

```java
Map<String, Object> registerData = new HashMap<>();
registerData.put("userName", "glutest-234");

customerGlu.updateProfile(this, registerData, new DataListner() {
            //this method register your device with CG and load the campaigns
            @Override
            public void onSuccess(Boolean success) {

            }
            @Override
            public void onFail(String message) {
                Toast.makeText(getApplicationContext(), "" + message, Toast.LENGTH_SHORT).show();
            }
        }
);

```

{% endtab %}

{% tab title="iOS" %}

```swift
customerGlu.updateProfile(userdata: ["userName" : "glutest"])
```

{% endtab %}

{% tab title="Flutter" %}

```dart
var userData = {
'userName': "glutest"
}

CustomergluPlugin.updateProfile(userData)
```

{% endtab %}

{% tab title="React Native" %}

```javascript
userdata = {
    userName: "glutest"
    }
UpdateProfile(userdata)
```

{% endtab %}
{% endtabs %}

## **Clear Data on Logout (Mandatory)**&#x20;

Use the given function when the user logs out, to clear CustomerGlu SDK cached data like user\_id, token, entry point related data, etc.

{% tabs %}
{% tab title="Android" %}

```java
customerGlu.clearGluData(getApplicationContext());
```

{% endtab %}

{% tab title="iOS" %}

```swift
customerGlu.clearGluData();
```

{% endtab %}

{% tab title="Flutter" %}

```dart
CustomergluPlugin.clearGluData()
```

{% endtab %}

{% tab title="React Native" %}

```dart
import {dataClear} from '@customerglu/react-native-customerglu';
dataClear();
```

{% endtab %}
{% endtabs %}

## **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

{% hint style="info" %}
**Note:** Analytics events need to be explicitly enabled
{% endhint %}

### **Enable Analytics Events**&#x20;

If click analytics are to be captured directly via the app, you can enable the analytics events by using the given function:

{% tabs %}
{% tab title="Android" %}

```java
customerGlu.enableAnalyticsEvent(true);
```

{% endtab %}

{% tab title="iOS" %}

```swift
customerGlu.enableAnalyticsEvent(event: true)
```

{% endtab %}

{% tab title="Flutter" %}

```dart
CustomergluPlugin.enableAnalyticsEvent(true)
```

{% endtab %}

{% tab title="React Native" %}

```javascript
import {enableAnalytic} from '@customerglu/react-native-customerglu';
enableAnalytic(true);
```

{% endtab %}
{% endtabs %}

### **Handling Events**&#x20;

{% tabs %}
{% tab title="Android" %}
For handling [Deeplink](https://docs.customerglu.com/schema/webview-callback-schema#open-deeplink) or [Analytics](https://docs.customerglu.com/schema/webview-callback-schema#analytics) events triggered by the webview, you need to register a broadcast receiver and handle the logic for the respective event:

```java
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"));


```

{% hint style="info" %}
**Note:** Do not unregister the broadcast receiver in the app lifecycle.
{% endhint %}
{% endtab %}

{% tab title="iOS" %}

### Deeplink Events

For handling [Deeplink](https://docs.customerglu.com/integration-doc/bind-webview-to-native-app-functions#1.-open-deeplink) events triggered by the webview, you need to add a notification observer:

<pre class="language-swift"><code class="lang-swift">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]
        {
<strong>             print(userInfo)
</strong><strong>        }
</strong>    }
</code></pre>

###

### Analytics Events&#x20;

For handling analytics events triggered by the webview, you need to a notification observer:

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

{% endtab %}

{% tab title="Flutter" %}
For handling [Deeplink](https://docs.customerglu.com/integration-doc/bind-webview-to-native-app-functions#1.-open-deeplink) and Analytics broadcast events in Flutter you need to create a `MethodChannel` and handle the logic for the respective event:&#x20;

```dart
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;
  }
});
```

{% endtab %}

{% tab title="React Native" %}
For handling [Deeplink](https://docs.customerglu.com/integration-doc/bind-webview-to-native-app-functions#1.-open-deeplink) and Analytics broadcast events in React-Native you need to add following code in your js file :&#x20;

```javascript

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();
        }
    }, []);
```

{% endtab %}
{% endtabs %}

## Nudge Configuration

Nudge Configuration is an object that can be passed as an optional parameter to the [openWallet](#open-wallet), [loadCampaignById](#open-campaign) and [openNudge](#open-nudge) methods to configure the layout, height, and other related properties for the webview.

{% tabs %}
{% tab title="Android" %}

```java
NudgeConfiguration nudgeConfiguration = new NudgeConfiguration();
nudgeConfiguration.setAbsoluteHeight(700);
nudgeConfiguration.setRelativeHeight(60);
nudgeConfiguration.setLayout("bottom-popup");
nudgeConfiguration.setOpacity(0.9);
nudgeConfiguration.setCloseOnDeepLink(true);
 
```

{% endtab %}

{% tab title="iOS" %}

```swift
let nudgeConfiguration = CGNudgeConfiguration()
            nudgeConfiguration.closeOnDeepLink = false
            nudgeConfiguration.opacity = 0.9
            nudgeConfiguration.layout = "bottom-default"
            nudgeConfiguration.absoluteHeight = 100
            nudgeConfiguration.relativeHeight = 70
```

{% endtab %}

{% tab title="Flutter" %}

```dart
nudgeConfiguration = NudgeConfiguration(relativeHeight: 50,
absoluteHeight: 700, layout: "bottom-slider",closeOnDeepLink: true,
opacity: 0.7),
```

{% endtab %}

{% tab title="React-Native" %}

```javascript
 let nudgeConfigurationData = {
        nudgeConfiguration:{
             layout:'middle-default',
             opacity:'0.8',
             closeOnDeepLink:true,
             absoluteHeight:'50',
             relativeHeight:'60'
        },
    };
```

{% endtab %}
{% endtabs %}

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**&#x20;

{% hint style="info" %}
Provide either relative or absolute dimensions for height. Priority is given to relative height in case of both being defined.
{% endhint %}

&#x20; 3\. **Layout** - Set the layout of nudge. Possible values: \[full-default, middle-popup, bottom-popup, bottom-slider] | Refer [here](#supported-layouts) to see al supported layouts. **Default value : full-default**&#x20;

&#x20; 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**  &#x20;

&#x20; 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:

&#x20;                                             ![](https://1004846827-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-M0ahLW2WavtwcwNbSR9%2Fuploads%2FckhOAUGWzIXBno8gR7Gz%2Fimage.png?alt=media\&token=0d310bf9-35e4-4505-9a7a-61bc8cafb814)

Use the following function to open the wallet screen powered by CustomerGlu:

{% tabs %}
{% tab title="Android" %}

```java
customerGlu.openWallet(getApplicationContext(),nudgeConfiguration);
```

#### Function Parameters

1. **Context:** this/getApplicationContext()
2. **NudgeConfiguration(optional)** : Please refer to the [NudgeConfiguration](#nudge-configuration)                        &#x20;
   {% endtab %}

{% tab title="iOS" %}

```swift
customerGlu.openWallet(nudgeConfiguration: nudgeConfiguration)
```

#### Function Parameters

&#x20; **NudgeConfiguration(optional)** : Please refer to the [NudgeConfiguration](#nudge-configuration)
{% endtab %}

{% tab title="Flutter" %}

```dart
CustomergluPlugin.openWallet(nudgeConfiguration: nudgeConfiguration)
```

**Function Parameters:**

**NudgeConfiguration(optional)** : Please refer to the [NudgeConfiguration](#flutter)&#x20;
{% endtab %}

{% tab title="React native" %}

```dart
import { openWallet } from '@customerglu/react-native-customerglu';
openWallet(nudgeConfigurationData)
```

**Function Parameters:**

**NudgeConfiguration(optional)** : Please refer to the [NudgeConfiguration](#nudge-configuration)
{% endtab %}
{% endtabs %}

## Open Campaign

You can also open specific campaigns by using the **campaignId** or **tag** assigned to a campaign.

**CampaignId**

![Finding the campaignId](https://1004846827-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-M0ahLW2WavtwcwNbSR9%2Fuploads%2FwsthlE303wIocU4lN6jo%2Fimage.png?alt=media\&token=7b0645b2-12cd-4cc7-910a-ce38ad778a3d)

**Tag**

![Adding a tag](https://1004846827-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-M0ahLW2WavtwcwNbSR9%2Fuploads%2FRAcsadZN149hN2nD0B1J%2Fimage.png?alt=media\&token=ad13a13e-6c19-4e78-bc4a-bc044f2f883c)

Use the following function to open a specific campaign:

{% tabs %}
{% tab title="Android" %}

```java
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](#nudge-configuration)
   {% endtab %}

{% tab title="iOS" %}

```swift
customerGlu.loadCampaignById(campaign_id: "CAMPAIGN_ID/TAG", nudgeConfiguration: nudgeConfiguration);
```

####

#### Function Parameters

1. **CampaignId/Tag :** Unique Identifier assigned to a campaign, can be copied from the dashboard.
2. **NudgeConfiguration(optional)** : Please refer to the [NudgeConfiguration](#nudge-configuration)
   {% endtab %}

{% tab title="Flutter" %}

```dart
CustomergluPlugin.loadCampaignById("CAMPAIGN_ID/TAG",nudgeConfiguration: nudgeConfiguration);
```

#### Function Parameters

1. **CampaignId/Tag :** Unique Identifier assigned a campaign, can be copied from the dashboard.
2. **NudgeConfiguration** - Please refer to  [NudgeConfiguration](#flutter)&#x20;
   {% endtab %}

{% tab title="React Native" %}

```dart
import { loadCampaginById } from '@customerglu/react-native-customerglu';
loadCampaginById("CAMPAIGN_ID/TAG",nudgeConfigurationData)
```

#### Function Parameters

1. **CampaignId/Tag :** Unique Identifier assigned a campaign, can be copied from the dashboard.
2. **NudgeConfiguration(optional)** : Please refer to the [NudgeConfiguration](#nudge-configuration)
   {% endtab %}
   {% endtabs %}

{% hint style="info" %}
**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**](#handling-invalid-campaign-id) event can be consumed
{% endhint %}

#### Verify CampaignId

You can verify the campaignId before opening the campaign using the below method

{% tabs %}
{% tab title="Android" %}

```java
customerGlu.isCampaignValid("campaignId");
```

{% endtab %}

{% tab title="iOS" %}

```swift
customerGlu.isCampaignValid("campaignId");
```

{% endtab %}
{% endtabs %}

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

**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**

#### &#x20; **Banner                                                                                                Floating Button/Launcher**

&#x20;  ![](https://1004846827-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-M0ahLW2WavtwcwNbSR9%2Fuploads%2FFSsUNNL7xTk0Kz9C4oR6%2F22-04-19-16-00-58.gif?alt=media\&token=b63f419a-ac3a-4b9e-b355-1a308fe892ec)                            ![](https://1004846827-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-M0ahLW2WavtwcwNbSR9%2Fuploads%2FedM96hvoaNOwu48SDnbu%2F22-05-02-11-16-19%20\(1\).gif?alt=media\&token=6629ef1e-56b2-40de-9659-dac926578751)

#### &#x20;                                                                                   **Popup**

&#x20;                                                    ![](https://1004846827-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-M0ahLW2WavtwcwNbSR9%2Fuploads%2FVVKqZJat0mGSgMHIiFlv%2F22-05-02-12-05-42%20\(1\).gif?alt=media\&token=0e8f6b2a-2095-43d5-81fc-033baa13e01a)

### **Enable Entry Points**

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

{% tabs %}
{% tab title="Android" %}

```java
customerGlu.enableEntryPoints(getApplicationContext(), true);
```

{% endtab %}

{% tab title="iOS" %}

```swift
customerGlu.enableEntryPoints(enabled: true)
```

{% endtab %}

{% tab title="Flutter" %}

```dart
CustomergluPlugin.enableEntryPoints(true);
```

{% endtab %}

{% tab title="React Native" %}

```javascript
import { enableEntryPoints } from '@customerglu/react-native-customerglu';
enableEntryPoints(true);
```

{% endtab %}
{% endtabs %}

### **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.

{% hint style="info" %}
**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.
{% endhint %}

{% tabs %}
{% tab title="Android" %}
Add the following component, wherever a banner might be needed, in the Activity’s layout file (XML):

```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
```

{% endtab %}

{% tab title="iOS" %}
Banners can be set up in the following ways:

#### **1. Storyboard / XIB**&#x20;

* &#x20;Drag and drop an empty UIView on the ViewController in which a banner might be needed, and adjust it to the correct position.&#x20;
* Under **identity inspector** add **BannerView** as the class name.
* Under **attribute inspector** add a unique value for **BannerId.**&#x20;
* Height constraint can be added in the same view.

#### **2. SwiftUI**&#x20;

If the app screens are developed using SwiftUI, add the following banner component, wherever a banner might be needed:

```swift
// Add code where a banner might be needed
Spacer()
VStack {
           AddBannerView()
}.padding(.horizontal, 10)
Spacer()

//Struct for adding banner view
struct AddBannerView: UIViewRepresentable {
    func updateUIView(_ uiView: BannerView, context: Context) {

    }
    
    func makeUIView(context: Context) -> BannerView {
        let view = BannerView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width-30, height: 0), bannerId: "Add unique bannerId ID here")
        view.setContentHuggingPriority(.required, for: .horizontal)
        view.setContentHuggingPriority(.required, for: .vertical)
        return view
    }
}
```

{% endtab %}

{% tab title="Flutter" %}
Add the following banner component, wherever a banner might be needed, in the flutter layout :

<pre class="language-dart"><code class="lang-dart"><strong>CustomergluPlugin().showBanner(id:"uniqueBannerId") 
</strong></code></pre>

**For Android:**

In `MainActivity` add the following code in `configureFlutterEngine` to add BannerVie&#x77;**:**

```java
import io.flutter.embedding.android.FlutterActivity;
import io.flutter.embedding.engine.FlutterEngine;
import com.customerglu.customerglu_plugin.FLNativeFactoryBannerView;

public class MainActivity extends FlutterActivity {

    @Override
    public void configureFlutterEngine( FlutterEngine flutterEngine) {
        super.configureFlutterEngine(flutterEngine);
        flutterEngine
                .getPlatformViewsController()
                .getRegistry()
                .registerViewFactory("cgnativebanner", new FLNativeFactoryBannerView());
    }

}
```

{% endtab %}

{% tab title="React Native" %}
Add the following banner component, wherever a banner might be needed, in the React-Native layout :

```javascript
import { BannerWidget } from '@customerglu/react-native-customerglu';
<BannerWidget
    bannerId="UniqueBannerId"
 />

```

{% endtab %}
{% endtabs %}

{% hint style="info" %}
&#x20;**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.
{% endhint %}

:information\_source: **Banner Loaded Callback:**

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:

{% tabs %}
{% tab title="Android" %}
Register a Broadcast Receiver, listen for the banner load event and handle the logic:<br>

```java
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"));
```

{% endtab %}

{% tab title="iOS" %}
Add a Notification Observer, listen for the banner load event and handle the logic:

```swift
// Add Observer to listen Notification with name CUSTOMERGLU_BANNER_LOADED
NotificationCenter.default.addObserver(
                    self,
                    selector: #selector(self.getBannersCount),
                    name: Notification.Name("CUSTOMERGLU_BANNER_LOADED"),
                    object: nil)
                    
// Method to listen notification with name CUSTOMERGLU_BANNER_LOADED
@objc private func getBannersCount(notification: NSNotification) {
       if let userInfo = notification.userInfo as? [String: Any]
            {
                    //  Output - ["banner1":2,"banner2":0]
                    // Key is the bannerId and value is number of banners in the Banner Component
                    print(userInfo)
            }
  }
```

{% endtab %}

{% tab title="Flutter" %}
Create a MethodChannel, listen for the banner load event and handle the logic:

```dart
static const broadcast_channel = MethodChannel("CUSTOMERGLU_EVENTS");
broadcast_channel.setMethodCallHandler((call) async {
  switch (call.method) {
    case "CUSTOMERGLU_BANNER_LOADED":
      print(call.arguments);
      break;

  }
});
```

{% endtab %}

{% tab title="React Native" %}
Add the following code to listen for banner load event callback:

```javascript
useEffect(() => {
        const { Rncustomerglu } = NativeModules;
        const RncustomergluManagerEmitter = new NativeEventEmitter(Rncustomerglu);
        const eventbanner = RncustomergluManagerEmitter.addListener(
            'CUSTOMERGLU_BANNER_LOADED',
            (reminder) => console.log('CUSTOMERGLU_BANNER_LOADED...', reminder)
        );
        const eventfheight = RncustomergluManagerEmitter.addListener(
            'CGBANNER_FINAL_HEIGHT',
             (reminder) => {
                    console.log('CGBANNER_FINAL_HEIGHT....', reminder["entry1"])
                    if (reminder["entry1"]) {                            
                }
            );
        }

        return () => {
            eventbanner.remove();
            eventfheight.remove();
        }
    }, []);
```

{% endtab %}
{% endtabs %}

### **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](#setting-up-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.

{% hint style="info" %}
**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.
{% endhint %}

{% tabs %}
{% tab title="Android" %}
Add the following component, wherever a banner might be needed, in the Activity’s layout file (XML):

```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
```

{% endtab %}

{% tab title="iOS" %}
Banners can be set up in the following ways:

#### **1. Storyboard / XIB**&#x20;

* &#x20;Drag and drop an empty UIView on the ViewController in which a banner might be needed, and adjust it to the correct position.&#x20;
* Under **identity inspector** add **CGEmbedView** as the class name.
* Under **attribute inspector** add a unique value for **embedId.**&#x20;
* Height constraint can be added in the same view.

#### **2. SwiftUI**&#x20;

If the app screens are developed using SwiftUI, add the following banner component, wherever a banner might be needed:

```swift
// Add code where a banner might be needed
Spacer()
VStack {
CGEmbedView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 0), embedId: "embedded1")}.padding(.horizontal, 10)
Spacer()

//Struct for adding embed view
struct EmbedViewAdd: UIViewRepresentable {
  func updateUIView(_ uiView: CGEmbedView, context: Context) {
  }
  func makeUIView(context: Context) -> CGEmbedView {
    let view = CGEmbedView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 0), embedId: "embedded1")
    view.setContentHuggingPriority(.required, for: .horizontal) // << here !!
    view.setContentHuggingPriority(.required, for: .vertical)
    // the same for compression if needed
    return view
  }
}
  
  
```

{% endtab %}

{% tab title="Flutter" %}
Add the following embed component, wherever a embed view might be needed, in the flutter layout :

<pre class="language-dart"><code class="lang-dart"><strong>CustomergluPlugin().CGEmbedView(id:"uniqueEmbedId") 
</strong></code></pre>

**For Android:**

In `MainActivity` add the following code in `configureFlutterEngine` to add BannerVie&#x77;**:**

```java
import io.flutter.embedding.android.FlutterActivity;
import io.flutter.embedding.engine.FlutterEngine;
import com.customerglu.customerglu_plugin.FLNativeFactoryBannerView;

public class MainActivity extends FlutterActivity {

    @Override
    public void configureFlutterEngine( FlutterEngine flutterEngine) {
        super.configureFlutterEngine(flutterEngine);
        flutterEngine
                .getPlatformViewsController()
                .getRegistry()
                .registerViewFactory("cgnativebanner", new FLNativeFactoryBannerView());
    }

}
```

{% endtab %}

{% tab title="React Native" %}
Add the following embed component, wherever a embed view might be needed, in the React-Native layout :

```javascript
import { BannerWidget } from '@customerglu/react-native-customerglu';
  EmbedBannerHeight = RncustomergluManagerEmitter.addListener(
                'CGEMBED_FINAL_HEIGHT',
                (reminder) => {
                    console.log('reminder----', reminder);
                    console.log('reminder["embedded1"]....', reminder["embedded1"])
                    if (reminder && reminder["embedded1"]) {
                        finalEBHeight = (reminder["embedded1"]);
                    }

                }

            );

<EmbedBannerWidget
                    style={{ width: '100%', height: Platform.OS === 'ios' ? finalEBHeight : null }}
                    bannerId="embedded1"
                />

```

{% endtab %}
{% endtabs %}

{% hint style="info" %}
&#x20;**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.
{% endhint %}

### **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.

{% tabs %}
{% tab title="Android" %}
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:

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

{% endtab %}

{% tab title="iOS" %}
The given function should be used on each **ViewController's** `viewWillAppear()` method to support adding the floating button/popup entry points via the dashboard:

```swift
override func viewWillAppear(_ animated: Bool) {
    super.viewDidLoad()
    customerGlu.setCurrentClassName(className: String(describing: type(of: self)))
}
```

{% endtab %}

{% tab title="Flutter" %}
The given code should be added on every Activity:

```dart
@override 
Widget build(BuildContext context) { 
return CGScreenDetector(
 classname: "screenName",
  child: Scaffold( 
  body: Container( 
  width: MediaQuery.of(context).size.width, 
  decoration: BoxDecoration(color: Colors.white), 
  child: Text("My Widget");
      ),
     )
    );
   }
  
```

**For Android:**

The given function should be used in `MainActivity` , inside the `onResume` method to support adding the floating button/popup entry points on the activity via the dashboard:

```java
@Override
protected void onResume() {
    super.onResume();
        CGUtils.setActivity(this);
} 
```

{% endtab %}

{% tab title="React Native" %}
The given function should be used on every Activity's `useFocusEffect()` Method to support adding the floating button/popup entry points on the activity via the dashboard:

```javascript
import { SetCurrentClassName } from '@customerglu/react-native-customerglu';
import { useFocusEffect, useRoute } from "@react-navigation/native";
const route = useRoute();
    useFocusEffect(
        React.useCallback(() => {
            SetCurrentClassName(route.name);
        }, [navigation])
    );
   
```

{% endtab %}
{% endtabs %}

## Handle CustomerGlu Nudges

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

{% tabs %}
{% tab title="Android" %}
Add the `displayCustomerGluNotification` method in the Firebase `onMessageRecieved` callback to handle nudges, as shown below:

```java
@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

{% hint style="info" %}
**Note**: App icon should be in PNG format with size less than 100KB.
{% endhint %}

### Handling Nudges for Background/Killed State

Add the given snippet on the Splash Screen to fetch nudge data and then call the [displayCustomerGluBackgroundNotification](#handle-customerglu-nudges) method on the same

```java
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);


                            }
                        }
      }
```

{% endtab %}

{% tab title="iOS" %}

#### **Configure Notification Type**&#x20;

Set the sender of the nudge (Firebase/APNS) in the `AppDelegate` file:

```swift
customerGlu.isFcmApn(fcmApn:"fcm") //or "apn"
```

**Function Parameter**

**fcmApn:** It accepts a string value out of "fcm" or "apn" depending on the notification service being used by the app.

#### **Set FCM/APNS Token**&#x20;

Add following code in **`didFinishLaunchingWithOptions()`**

```swift
 func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

          
        UNUserNotificationCenter.current().delegate = self
        let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
        UNUserNotificationCenter.current().requestAuthorization(
            options: authOptions,
            completionHandler: {_, _ in })
        application.registerForRemoteNotifications()

        //Only For FCM
        FirebaseApp.configure()
        Messaging.messaging().delegate = self

        return true
    }

```

Add the following extension in `AppDelegate`:

```swift
extension AppDelegate: UNUserNotificationCenterDelegate {
    
    // Receive displayed notifications for iOS 10 devices.
    func userNotificationCenter(_ center: UNUserNotificationCenter,
                                willPresent notification: UNNotification,
                                withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        // Change this to your preferred presentation option
        customerGlu.cgUserNotificationCenter(center, willPresent: notification, withCompletionHandler: completionHandler)
    }
    
    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) { //apn
        let tokenString = deviceToken.reduce("", {$0 + String(format: "%02X", $1)})
        print("Device token: \(tokenString)")
        customerGlu.apnToken = tokenString
        
        // Not required for FCM
        let userData = [String: AnyHashable]()
        customerGlu.updateProfile(userdata: userData) { success in
            if success {
            } else {
            }
        }
        
        //Only required for FCM
        Messaging.messaging().apnsToken = deviceToken
        print("APNs token retrieved: \(deviceToken)")
    }
    
    func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
    }
    
    func userNotificationCenter(_ center: UNUserNotificationCenter,
                                didReceive response: UNNotificationResponse,
                                withCompletionHandler completionHandler: @escaping () -> Void) {
        let userInfo = response.notification.request.content.userInfo
        print(userInfo)
  // autoclosewebview - If True then it will dismiss the webview on Deeplink Event.

customerGlu.displayBackgroundNotification(remoteMessage: userInfo as? [String: AnyHashable] ?? ["glu_message_type":"glu"],auto_close_webview:false)        completionHandler()
        completionHandler()
    }
    
    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
        print(userInfo)
          // autoclosewebview - If True then it will dismiss the webview on Deeplink Event.

customerGlu.cgapplication(application, didReceiveRemoteNotification: userInfo, backgroundAlpha: 0.5 ,auto_close_webview:false,fetchCompletionHandler: completionHandler)     }
     }
    
    func messaging(_ messaging: Messaging, didRefreshRegistrationToken fcmToken: String) {
        print(fcmToken)
    }
}

// MARK: FCM Notification delegate
extension AppDelegate: MessagingDelegate {
    func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String?) {
        print("Firebase registration token: \(String(describing: fcmToken))")
        customerGlu.fcmToken = fcmToken ?? ""
        let userData = [String: AnyHashable]()
        customerGlu.updateProfile(userdata: userData) { success in
            if success {
            } else {
            }
        }
    }
}
```

{% endtab %}

{% tab title="Flutter" %}
{% tabs %}
{% tab title="Android" %}

Add your Notification icon  in meta-data of the `AndroidManifest.xml` file like this:

```xml
<meta-data
    android:name="CUSTOMERGLU_NOTIFICATION_ICON"
    android:resource="@drawable/appicon" /><!-- only value should be changed -->
```

Add the following method in the Firebase message listener:

```java
FirebaseMessaging.onMessage.listen((message) {
  print("FirebaseMessaging.onMessage.listen");
  CustomergluPlugin.displayCustomerGluNotification(message.data,autoclosewebview: true);
});
  FirebaseMessaging.onMessageOpenedApp.listen((message) {
      print("FirebaseMessaging.onMessageOpenedApp.listen");
      CustomergluPlugin.displayCustomerGluBackgroundNotification(message.data);
    });
        FirebaseMessaging.instance.getInitialMessage().then((message) async {
      print("FirebaseMessaging.instance.getInitialMessage().then((message)");
      if (message != null) {
        CustomergluPlugin.displayCustomerGluBackgroundNotification(message.data);

      }
    });
```

**Function Parameters:**

**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.
{% endtab %}

{% tab title="iOS" %}

#### **Configure Notification Type**&#x20;

Set the sender of the nudge (Firebase/APNS) in the `AppDelegate` file:

```swift
customerGlu.isFcmApn(fcmApn:"fcm") //or "apn"
```

**Function Parameter**

**fcmApn:** It accepts a string value out of "fcm" or "apn" depending on the notification service being used by the app.

#### **Set FCM/APNS Token**&#x20;

Add following code in **`didFinishLaunchingWithOptions()`**

```swift
 func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

          
        UNUserNotificationCenter.current().delegate = self
        let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
        UNUserNotificationCenter.current().requestAuthorization(
            options: authOptions,
            completionHandler: {_, _ in })
        application.registerForRemoteNotifications()

        //Only For FCM
        FirebaseApp.configure()
        Messaging.messaging().delegate = self

        return true
    }

```

Add the following extension in `AppDelegate`:

```swift
extension AppDelegate: UNUserNotificationCenterDelegate {
    
    // Receive displayed notifications for iOS 10 devices.
    func userNotificationCenter(_ center: UNUserNotificationCenter,
                                willPresent notification: UNNotification,
                                withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        // Change this to your preferred presentation option
        CustomerGlu.getInstance.cgUserNotificationCenter(center, willPresent: notification, withCompletionHandler: completionHandler)
    }
    
    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) { //apn
        let tokenString = deviceToken.reduce("", {$0 + String(format: "%02X", $1)})
        print("Device token: \(tokenString)")
        CustomerGlu.getInstance.apnToken = tokenString
        
        // Not required for FCM
        let userData = [String: AnyHashable]()
        CustomerGlu.getInstance.updateProfile(userdata: userData) { success in
            if success {
            } else {
            }
        }
        
        //Only required for FCM
        Messaging.messaging().apnsToken = deviceToken
        print("APNs token retrieved: \(deviceToken)")
    }
    
    func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
    }
    
    func userNotificationCenter(_ center: UNUserNotificationCenter,
                                didReceive response: UNNotificationResponse,
                                withCompletionHandler completionHandler: @escaping () -> Void) {
        let userInfo = response.notification.request.content.userInfo
        print(userInfo)
  // autoclosewebview - If True then it will dismiss the webview on Deeplink Event.

CustomerGlu.getInstance.displayBackgroundNotification(remoteMessage: userInfo as? [String: AnyHashable] ?? ["glu_message_type":"glu"],auto_close_webview:false)        completionHandler()
        completionHandler()
    }
    
    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
        print(userInfo)
          // autoclosewebview - If True then it will dismiss the webview on Deeplink Event.

CustomerGlu.getInstance.cgapplication(application, didReceiveRemoteNotification: userInfo, backgroundAlpha: 0.5 ,auto_close_webview:false,fetchCompletionHandler: completionHandler)     }
     }
    
    func messaging(_ messaging: Messaging, didRefreshRegistrationToken fcmToken: String) {
        print(fcmToken)
    }
}

// MARK: FCM Notification delegate
extension AppDelegate: MessagingDelegate {
    func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String?) {
        print("Firebase registration token: \(String(describing: fcmToken))")
        CustomerGlu.getInstance.fcmToken = fcmToken ?? ""
        let userData = [String: AnyHashable]()
        CustomerGlu.getInstance.updateProfile(userdata: userData) { success in
            if success {
            } else {
            }
        }
    }
}
```

{% endtab %}
{% endtabs %}
{% endtab %}

{% tab title="React native" %}

* Add the given dependencies in your application's `package.json file`:

```javascript
"@react-native-community/push-notification-ios": "^1.10.1",
"@react-native-firebase/messaging": "^15.1.1",
"react-native-push-notification": "^8.1.1"
```

* Import the given function:

```javascript
import { DisplayCGNotification,DisplayCGBackgroundNotification } from '@customerglu/react-native-customerglu';
```

* Add it in the PushNotification library `onNotification` callback, as shown below:

```javascript
import PushNotification from "react-native-push-notification";
PushNotification.configure({
  // (required) Called when a remote is received or opened, or local notification is opened
       onNotification: function (notification) {
        console.log("NOTIFICATION----:", notification);
        if (notification.foreground) {
            if (notification.data.glu_message_type) {
                //ios notification open from forground
                DisplayCGNotification(notification.data, true)

            } else {
                DisplayCGNotification(notification.data.data, true)
            }
        } else {
            //ios  notification open from Background 
            if(Platform.OS==='android'){
                DisplayCGBackgroundNotification(notification.data, true)
            }else{
                DisplayCGNotification(notification.data, true)
            }
        }
    },
    
});

```

#### For Android -&#x20;

Add your Notification icon  in meta-data of the `AndroidManifest.xml` file like this:

```xml
<meta-data
    android:name="CUSTOMERGLU_NOTIFICATION_ICON"
    android:resource="@drawable/appicon" />
```

**For iOS**

* Create a file named `NotificationServices.js` in the src folder and add given code in the file:

```javascript
import messaging from '@react-native-firebase/messaging';
import AsyncStorage from '@react-native-async-storage/async-storage'
import { setApnFcmToken } from '@customerglu/react-native-customerglu'
import PushNotification from 'react-native-push-notification';
import { Platform } from 'react-native';
export async function requestUserPermission() {
    const authStatus = await messaging().requestPermission();
    const enabled =
        authStatus === messaging.AuthorizationStatus.AUTHORIZED ||
        authStatus === messaging.AuthorizationStatus.PROVISIONAL;

    if (enabled) {
        console.log('Authorization status:', authStatus);
        getFcmToken()
    }
}


const getFcmToken = async () => {
    try {
        const fcmTokenfcm = await messaging().getToken()
        await AsyncStorage.setItem('fcmTokenFCM', fcmTokenfcm);
        console.log("fcm token generated", fcmTokenfcm)

        // --------------------If setApnFcmTokenEx((token.token, "")) for apn is commented uncomment below line -------------

        if (Platform.OS === 'ios') {
            setApnFcmToken("", fcmTokenfcm);
        }


    } catch (error) {
        console.log("error in fcm", error)
    }
}

export const notificationListner = async () => {


    messaging().setBackgroundMessageHandler(async remoteMessage => {
        console.log('Message handled in the background!', remoteMessage);
    });

    messaging().onMessage(async remoteMessage => {
        PushNotification.localNotification({
            userInfo: {
                data: remoteMessage.data,
            },
            title: remoteMessage.notification.title,
            message: remoteMessage.notification.body,
           

        });
    });


}
```

* Add the given code in `App.js` :

```javascript
    useEffect(() => {
        if (Platform.OS === 'ios') {
            const type = 'notification';
            PushNotificationIOS.addEventListener(type, onRemoteNotification);
            requestUserPermission();
            notificationListner();
        }
    }, [])
```

* Update the pod file as shown below and and install it again:

```swift
//Reference URLs
//https://rnfirebase.io/install-ios
//https://rnfirebase.io/messaging/usage/installation/ios

//Add Following lines
pod 'RNFBApp', :path => '../node_modules/@react-native-firebase/app'
pod 'RNFBMessaging', :path => '../node_modules/@react-native-firebase/messaging'

use_frameworks! :linkage => :static
pod 'Firebase/Messaging'

$RNFirebaseAsStaticFramework = true

// Remove the following line if it exists
flipper_configuration => FlipperConfiguration.enabled
```

#### **Configure Notification Type**&#x20;

Set the sender of the nudge (Firebase/APNS)

```swift
customerGlu.isFcmApn(fcmApn:"fcm") //or "apn"
```

**Function Parameter**

**fcmApn:** It accepts a string value out of "fcm" or "apn" depending on the notification service being used by the app.

#### **Set FCM/APNS Token**&#x20;

* Add following code in **`didFinishLaunchingWithOptions()`**

```swift
 #import <UserNotifications/UserNotifications.h>
#import <UserNotifications/UNUserNotificationCenter.h>
#import <RNCPushNotificationIOS.h>

 - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions

{
  [FIRApp configure];  // Required only if ypu are using FCM
  #ifdef FB_SONARKIT_ENABLED
    InitializeFlipper(application);
  #endif
  
  
  [application registerForRemoteNotifications];
  
  RCTBridge *bridge = [[RCTBridge alloc] initWithDelegate:self launchOptions:launchOptions];
  RCTRootView *rootView = [[RCTRootView alloc] initWithBridge:bridge
                                                   moduleName:@"RncustomergluExample"
                                            initialProperties:nil];

  rootView.backgroundColor = [[UIColor alloc] initWithRed:1.0f green:1.0f blue:1.0f alpha:1];

  self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
  UIViewController *rootViewController = [UIViewController new];
  rootViewController.view = rootView;
  self.window.rootViewController = rootViewController;
  [self.window makeKeyAndVisible];

  UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
  center.delegate = self;
  return YES;
}

```

* Add the following method in `AppDelegate.m`:

```swift
-(void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler
{

  NSLog(@"cgUserNotificationCenter");
  completionHandler(UNNotificationPresentationOptionSound | UNNotificationPresentationOptionAlert | UNNotificationPresentationOptionBadge);
}
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
 [RNCPushNotificationIOS didRegisterForRemoteNotificationsWithDeviceToken:deviceToken];
}
// Required for the notification event. You must call the completion handler after handling the remote notification.
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
{
  [RNCPushNotificationIOS didReceiveRemoteNotification:userInfo fetchCompletionHandler:completionHandler];
}
// Required for the registrationError event.
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error
{
 [RNCPushNotificationIOS didFailToRegisterForRemoteNotificationsWithError:error];
}
// Required for localNotification event
- (void)userNotificationCenter:(UNUserNotificationCenter *)center
didReceiveNotificationResponse:(UNNotificationResponse *)response
         withCompletionHandler:(void (^)(void))completionHandler
{
  
  [RNCPushNotificationIOS didReceiveNotificationResponse:response];
}
```

{% endtab %}
{% endtabs %}

## Supported Layouts

The following layouts are supported by CustomerGlu Mobile SDKs for various functionalities like opening wallet, campaigns, nudges, etc.

#### &#x20;                           Fullscreen                                                                                        Middle Popup

#### ![](https://1004846827-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-M0ahLW2WavtwcwNbSR9%2Fuploads%2FG6W6h4GHrR6uu5aHnRpr%2FScreenshot%202022-09-14%20at%2012.57.10%20AM.png?alt=media\&token=df254be8-1886-44f5-8a8e-d0773ca18b1a)                                ![](https://1004846827-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-M0ahLW2WavtwcwNbSR9%2Fuploads%2FBysQXRym4r0afrJ3cI33%2FScreenshot%202022-09-14%20at%2012.57.24%20AM.png?alt=media\&token=e4a97f1a-baf8-4762-a423-e6f65024d070)

#### &#x20;                     &#x20;

#### &#x20;                    Bottom Popup                                                                          **Bottom Slider (Draggable)**

![](https://1004846827-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-M0ahLW2WavtwcwNbSR9%2Fuploads%2FCijcG7zGjVNjOlHBOTi7%2FScreenshot%202022-09-14%20at%2012.57.39%20AM.png?alt=media\&token=c1272c35-18e8-44c7-8d53-d24fb49feb86)                                ![](https://1004846827-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-M0ahLW2WavtwcwNbSR9%2Fuploads%2F69kFOUHgjIBrAtsRbCES%2FScreenshot%202022-09-14%20at%2012.57.32%20AM.png?alt=media\&token=b0112710-df5b-4c90-af49-09d2e8f2b905)

##

## Handling Dark Mode/Light Configuration

The dark mode settings in the CustomerGlu SDK (only v2.2.0+) can be configured using the following Methods

### Handling Configuration Changes

For handling configuration changes like dark/light mode, orientation, etc., Flutter and React-Native apps need to implement this method in android  **MainActivity**

{% tabs %}
{% tab title="Flutter" %}

```java

   @Override
    public void onConfigurationChanged(@NonNull Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        CGUtils.handleConfigurationChanges(this);

    }
```

{% endtab %}

{% tab title="React-Native" %}

```java
   @Override
    public void onConfigurationChanged(@NonNull Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        CGUtils.handleConfigurationChanges(this);

    }
```

{% endtab %}
{% endtabs %}

## Handling CustomerGlu Deeplinks

CustomerGlu provides Universal Deeplinks to access particular campaigns and wallet page. To support these deeplinks in the app and redirection to playstore/appstore in case the app is not installed, please follow the given steps:

{% tabs %}
{% tab title="Android" %}
**Step 1**&#x20;

&#x20;Put the intent-filter inside the activity tag in Android Manifest  as below to handle navigation to that activity

```xml
        <intent-filter
                android:autoVerify="true"
                tools:targetApi="m">
                <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="<your-deeplink-subdomain>.cglu.us" />

            </intent-filter>
```

**Step 2**&#x20;

&#x20;To get the intent data from url you need to add the following method in the OnCreate()  of your activity &#x20;

```java
customerglu.setupCGDeepLinkIntentData(this);
```

**Function Parameter**

**activity :** Pass the activity inside the method

**Step 3**

&#x20;To handle deeplinks in a custom manne&#x72;**,** add the listener in the **Application** Class to get the callback&#x20;

```java
        CustomerGlu.getInstance().setCgDeepLinkListener(new CGDeepLinkListener() {
            @Override
            public void onSuccess(CGConstants.CGSTATE message, DeepLinkWormholeModel.DeepLinkData deepLinkData) {

                if (message.equals(CGConstants.CGSTATE.DEEPLINK_URL)) {
                    String url = "";
                    if (deepLinkData.getContent().getUrl() != null) {
                        url = deepLinkData.getContent().getUrl();

                    }
                    // Add your logic
                }
            }

            @Override
            public void onFailure(CGConstants.CGSTATE exceptions) {
                Log.e("Failure ", exceptions.toString());

            }
        });
```

{% endtab %}

{% tab title="iOS" %}
**Step 1**&#x20;

Add the Associate domain in your project\
&#x20;

<figure><img src="https://1004846827-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-M0ahLW2WavtwcwNbSR9%2Fuploads%2Fi3RYhKfPT76R7VbmYR5z%2FScreenshot%202023-03-24%20at%2011.13.53%20AM.png?alt=media&#x26;token=3e658647-e207-4b8b-97b3-76ed766c1b3a" alt=""><figcaption></figcaption></figure>

**Step 2**&#x20;

**For SwiftUI**

Implement `.onOpenURL` for the Launch view defined in WindowGroup in `Scene` class

```swift
SomeView.onOpenURL { url in
            // URL handling
            CustomerGlu.getInstance.openDeepLink(deepurl: url){
              success, string, deeplinkdata in
               
            }
           
          }
```

**For UI Kit**&#x20;

Implement the following method in `AppDelegate.swift` file

```swift
func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
  CustomerGlu.getInstance.openDeepLink(deepurl: url){
              success, string, deeplinkdata in
               
            }
    return true
}
```

{% endtab %}

{% tab title="Flutter" %}
**Android** \
&#x20;Put the intent-filter inside the activity tag in Android Manifest

```xml
        <intent-filter
                android:autoVerify="true"
                tools:targetApi="m">
                <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="testapp.cglu.us" />

            </intent-filter>
```

**iOS** \
Add the Associate domain in your project\
&#x20;

<figure><img src="https://1004846827-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-M0ahLW2WavtwcwNbSR9%2Fuploads%2FbZn6CYInnxHiMXN23Aqg%2FScreenshot%202023-03-24%20at%2011.13.53%20AM.png?alt=media&#x26;token=57101c25-b59d-4f70-a07a-709fd7ba0c64" alt=""><figcaption></figcaption></figure>

**Flutter**

Add the callback in `main.dart` in method channel

<pre class="language-dart"><code class="lang-dart"> broadcast_channel.setMethodCallHandler((call) async {
      switch (call.method) {

<strong>case "CG_UNI_DEEPLINK_EVENT":
</strong>          print("CG_UNI_DEEPLINK_EVENT FROM FLUTTER");
          print(call.arguments);
          var json = jsonDecode(call.arguments);
          break;
}
}
</code></pre>

{% endtab %}

{% tab title="React Native" %}
**Android**\
&#x20;Put the intent-filter inside the activity tag in Android Manifest

```xml
        <intent-filter
                android:autoVerify="true"
                tools:targetApi="m">
                <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="testapp.cglu.us" />

            </intent-filter>
```

**iOS**\
Add the Associate domain in your project

<figure><img src="https://1004846827-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-M0ahLW2WavtwcwNbSR9%2Fuploads%2F3QVboutI76PB3rnLpg8a%2FScreenshot%202023-03-24%20at%2011.13.53%20AM.png?alt=media&#x26;token=5b7849ab-4c55-4d39-a4a9-b4e0f5327922" alt=""><figcaption></figcaption></figure>

**React-Native**

Implement the below callback:

```javascript

 const CG_UNI_DEEPLINK_EVENT = RncustomergluManagerEmitter.addListener(
            'CG_UNI_DEEPLINK_EVENT',
            (reminder) => 
            console.log('CG_UNI_DEEPLINK_EVENT...', reminder)
        );

```

{% endtab %}
{% endtabs %}

## Send Events (to CG)

User events which may lead to rewards via a campaign need to be sent to CG. These events can be sent directly via the SDKs using the `sendEventData` method:

{% hint style="info" %}
**Note:** Check out all available options to send events [here](https://docs.customerglu.com/third-party-integrations/send-user-events)
{% endhint %}

{% tabs %}
{% tab title="Android" %}

```java
HashMap<String,Object> eventProperties = new HashMap();
eventProperties.put("orderValue",1000);
customerGlu.sendEventData(Context,"Order_Placed",eventProperties);
```

**Function Parameters**

1. **Context :** this/getApplicationContext()
2. **EventName:** Event names like `order_placed`, `add_to_cart` etc.
3. **EventProperties** - Event properties like `orderId`, `orderAmount`etc. as a HashMap
   {% endtab %}

{% tab title="iOS" %}

```swift
customerGlu.sendEventData(eventName:"Order_Placed",eventProperties:["orderValue",1000])
```

**Function Parameters**&#x20;

1. **eventName:** Event names like `order_placed`, `add_to_cart` etc.
2. **eventProperties** - Event properties like `orderId`, `orderAmount`etc as a dictonary.
   {% endtab %}

{% tab title="Flutter" %}

```java
eventproperties = {"orderValue":1000},
CustomergluPlugin.sendEventData("Order_Placed", eventproperties)
```

**Function Parameters**

1. **EventName:** Event names like `order_placed`, `add_to_cart` etc.
2. **EventProperties** - Event properties like `orderId`, `orderAmount`etc. as an object
   {% endtab %}

{% tab title="React Native" %}

```javascript
import { sendData } from '@customerglu/react-native-customerglu';
let obj = { 
eventName: "completePurchase", 
eventProperties: {
    "orderValue":1000,
    "orderId":"xyz"
    }
}
sendData(obj);
```

**Function Parameters:**&#x20;

1. **EventName:** Event names like `order_placed`, `add_to_cart` etc.
2. **EventProperties** - Event properties like `orderId`, `orderAmount`etc. as an object
   {% endtab %}
   {% endtabs %}

## **Enable SDK Debugging Mode**&#x20;

Debugging mode enables logging for ease of debugging.&#x20;

{% hint style="info" %}
**Note**: Please make sure to disable debugging mode in Release/Production build.
{% endhint %}

The given function can be used to enable SDK debugging mode:

{% tabs %}
{% tab title="Android" %}

```java
customerGlu.gluSDKDebuggingMode(getApplicationContext(), true);
```

{% endtab %}

{% tab title="iOS" %}

```swift
customerGlu.gluSDKDebuggingMode(enabled: true)
```

{% endtab %}

{% tab title="Flutter" %}

```dart
CustomergluPlugin.gluSDKDebuggingMode(true);
```

{% endtab %}

{% tab title="React native" %}

```javascript
import { gluSDKDebuggingMode } from '@customerglu/react-native-customerglu';
gluSDKDebuggingMode(true);
```

{% endtab %}
{% endtabs %}

## **Disable CustomerGlu SDK**

All the functions of SDK can be disabled by using the method:

{% tabs %}
{% tab title="Android" %}

```java
customerGlu.disableGluSdk(true);
```

{% endtab %}

{% tab title="iOS" %}

```swift
customerGlu.disableGluSdk(true);
```

{% endtab %}

{% tab title="Flutter" %}

```dart
CustomergluPlugin.disableGluSdk(true)
```

{% endtab %}

{% tab title="React native" %}

<pre class="language-javascript"><code class="lang-javascript">import { disableGluSdk } from '@customerglu/react-native-customerglu';

<strong>disableGluSdk(true);
</strong></code></pre>

{% endtab %}
{% endtabs %}
