# CustomerGlu Notification

CustomerGlu sends notification as firebase data messages in the following formats

### Using webview

If you would like to use the layouts from CG,  you can extract the nudge url from data messages and load it in a webview

```
{
  name: 'CustomerGlu',
  data: {
    "type": "CustomerGlu",
    "glu_message_type":"in-app",
    "title": "Attended live class X time(s)",
    "body": "You are doing great! Just x more times to go and win your reward",
    "image": "",
    "nudge_url": "https://staging.d283eczxp8leqk.amplifyapp.com/program-nudge/streak-progress/?token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOiIyMzk3OTMiLCJjbGllbnQiOiI0ZjdmNjE5OC0yNGNmLTRkZDYtODcxOS04MjdkM2RlNzYwNGYiLCJpYXQiOjE2MTcwMTU3MDEsImV4cCI6MTY0ODU1MTcwMX0.sAoqC8TGw3SSFl3W7PvJJilLivD7tL3Y-n23iBWHXAU&campaignId=44941f5f-a84f-46c0-9901-6e80e445a257"
  }
}
```

![Fullscreen nudge](https://1004846827-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M0ahLW2WavtwcwNbSR9%2F-MX6o1o5jpU8KpdhP8gB%2F-MX6oEpiH34EG7jcPHDT%2FScreenshot%20from%202021-03-31%2015-54-53.png?alt=media\&token=897114d0-d1b1-46fb-89ec-cfe414af444a)

### Using Native In-app Layouts

If In-app layout already exists in the app, You can build the in-app notifications using he data messages we send. sample below

```
{
  name: 'CustomerGlu',
  notification: {
    title: "Congrats!!",
    body: "You're now 7 steps away from getting 10000 Bonus points! Click here to complete rest of the activities to earn $100"
  },
  data: {
    data: "JSON NOTIFICATION OBJECT"
  },
  token: 'tempsdajhsadvvjhsdv'
}
```

### CustomerGlu Notification Object

```
{
      "type": "CustomerGlu",
      "glu_message_source": "",
      "glu_user_id": "",
      "glu_campaign_id": "",
      "glu_message_type": "in-app",
      "glu_push_message_content": {
        "title": "Your friend just signed up",
        "body": "Get all of your friends on here",
        "image": "/assets/multi-step/mini-icons/7.png",
        "cta_button_text": "Go To Challenge",
        "cta_button_link": "/tasks?event=customerGlu&deepLink=",
        "deeplink": "/tasks?event=customerGlu&deepLink="
      },
      "glu_inapp_message_content": {
        "page_name": "",
        "page_type": "middle-default",
        "page_accent": "default",
        "page_details": {
          "title": "Your friend just signed up",
          "body": "Get all of your friends on here",
          "image": "/assets/multi-step/mini-icons/7.png",
          "cta_button_text": "Go To Challenge",
          "cta_button_link": "/tasks?event=customerGlu&deepLink="
        }
      }
    }
  }
```

### Handling CustomerGlu Notifications

{% tabs %}
{% tab title="Android (Java)" %}

```java
@RequiresApi(api = Build.VERSION_CODES.M)
public static void displayCustomerGluNotification(Context context,JSONObject json,int icon) {
    JSONObject data = null;
    try {
        data = new JSONObject(String.valueOf(json));
        System.out.println(data);
        String type = data.getString("type");
        String in_app="";
        String in_app_type="";

        if(type.equalsIgnoreCase("CustomerGlu")) {
            String url = data.getString("nudge_url");
            String body = data.getString("body");
            String title = data.getString("title");
            String glu_message_type = data.getString("glu_message_type");
            String image = data.getString("image");
            if(data.has("inapp")) {
                 in_app = data.getString("inapp");
                JSONObject in_app_object = new JSONObject(in_app);
                 in_app_type = in_app_object.getString("type");
            }

            if (glu_message_type.equalsIgnoreCase("in-app")) {
                CustomerGlu.handleDataMessage(context,url,in_app_type);
            }
            else {
                if(image.equalsIgnoreCase(""))
                {
                    displayNotification(context, title, body, url,icon);

                }
                else {
                    displayExpandedNotification(context, title, body, url, image,icon);
                }
            }
        }
        else
        {
            return;
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }


}
 public static void handleDataMessage(Context context,String url,String type) {

            System.out.println(type);
            if(type.equalsIgnoreCase("bottom-slider"))
            {
                Intent intent = new Intent(context, BottomSheet.class);
                intent.putExtra("nudge_url", url);
                intent.setFlags(FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(intent);
            }
           else if(type.equalsIgnoreCase("bottom-default"))
            {
                Intent intent = new Intent(context, BottomDialog.class);
                intent.putExtra("nudge_url", url);
                intent.setFlags(FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(intent);
            }
         else   if(type.equalsIgnoreCase("middle-default"))
            {
                Intent intent = new Intent(context, MiddleDialog.class);
                intent.putExtra("nudge_url", url);
                intent.setFlags(FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(intent);
            }

else            {
                Intent intent = new Intent(context, NotificationWeb.class);
                intent.putExtra("nudge_url", url);
                intent.setFlags(FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(intent);
            }

    }


    @RequiresApi(api = Build.VERSION_CODES.M)
    public static void displayExpandedNotification(Context context, String title, String message, String url,String image,int icon) {
        System.out.println("sdadsad");
        System.out.println(url);
        Intent intent = new Intent(context, NotificationWeb.class);
        intent.setFlags(FLAG_ACTIVITY_NEW_TASK);
        intent.putExtra("nudge_url",url);
        PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);

        Bitmap bmp = null;
        try {
            InputStream in = new URL(image).openStream();
            bmp = BitmapFactory.decodeStream(in);
        } catch (IOException e) {
            e.printStackTrace();
        }
        NotificationCompat.Builder builder = new NotificationCompat.Builder(context, "234")
                .setSmallIcon(icon)
                .setContentTitle(Html.fromHtml(title))
                .setContentText(Html.fromHtml(message))
                .setAutoCancel(true)
                .setContentIntent(pendingIntent)
                .setPriority(PRIORITY_MAX)
                .setLargeIcon(bmp)
                .setStyle(new NotificationCompat.BigPictureStyle()
                        .bigPicture(bmp)
                        .bigLargeIcon(null))
                .setDefaults(DEFAULT_ALL);
        NotificationManager manager = context.getSystemService(NotificationManager.class);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            @SuppressLint("WrongConstant") NotificationChannel notificationChannel = new NotificationChannel("234", "CustomerGlu", NotificationManager.IMPORTANCE_MAX);

            manager.createNotificationChannel(notificationChannel);
        }
        manager.notify(Integer.parseInt(("234")), builder.build());




    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    public static void displayNotification(Context context, String title, String message, String url,int icon) {
        System.out.println("sdadsad");
        System.out.println(url);
        Intent intent = new Intent(context, NotificationWeb.class);
        intent.setFlags(FLAG_ACTIVITY_NEW_TASK);
        intent.putExtra("nudge_url",url);
        PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);

        NotificationCompat.Builder builder = new NotificationCompat.Builder(context, "234")
                .setSmallIcon(icon)
                .setContentTitle(Html.fromHtml(title))
                .setContentText(Html.fromHtml(message))
                .setAutoCancel(true)
                .setContentIntent(pendingIntent)
                .setPriority(PRIORITY_MAX)
                .setDefaults(DEFAULT_ALL);
        NotificationManager manager = context.getSystemService(NotificationManager.class);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            @SuppressLint("WrongConstant") NotificationChannel notificationChannel = new NotificationChannel("234", "CustomerGlu", NotificationManager.IMPORTANCE_MAX);

            manager.createNotificationChannel(notificationChannel);
        }
        manager.notify(Integer.parseInt(("234")), builder.build());




    }
```

{% endtab %}

{% tab title="Android (Kotlin)" %}

```kotlin
@RequiresApi(api = Build.VERSION_CODES.M)
public static void displayCustomerGluNotification(Context context,JSONObject json,int icon) {
    JSONObject data = null;
    try {
        data = new JSONObject(String.valueOf(json));
        System.out.println(data);
        String type = data.getString("type");
        String in_app="";
        String in_app_type="";

        if(type.equalsIgnoreCase("CustomerGlu")) {
            String url = data.getString("nudge_url");
            String body = data.getString("body");
            String title = data.getString("title");
            String glu_message_type = data.getString("glu_message_type");
            String image = data.getString("image");
            if(data.has("inapp")) {
                 in_app = data.getString("inapp");
                JSONObject in_app_object = new JSONObject(in_app);
                 in_app_type = in_app_object.getString("type");
            }

            if (glu_message_type.equalsIgnoreCase("in-app")) {
                CustomerGlu.handleDataMessage(context,url,in_app_type);
            }
            else {
                if(image.equalsIgnoreCase(""))
                {
                    displayNotification(context, title, body, url,icon);

                }
                else {
                    displayExpandedNotification(context, title, body, url, image,icon);
                }
            }
        }
        else
        {
            return;
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }


}
 public static void handleDataMessage(Context context,String url,String type) {

            System.out.println(type);
            if(type.equalsIgnoreCase("bottom-slider"))
            {
                Intent intent = new Intent(context, BottomSheet.class);
                intent.putExtra("nudge_url", url);
                intent.setFlags(FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(intent);
            }
           else if(type.equalsIgnoreCase("bottom-default"))
            {
                Intent intent = new Intent(context, BottomDialog.class);
                intent.putExtra("nudge_url", url);
                intent.setFlags(FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(intent);
            }
         else   if(type.equalsIgnoreCase("middle-default"))
            {
                Intent intent = new Intent(context, MiddleDialog.class);
                intent.putExtra("nudge_url", url);
                intent.setFlags(FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(intent);
            }

else            {
                Intent intent = new Intent(context, NotificationWeb.class);
                intent.putExtra("nudge_url", url);
                intent.setFlags(FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(intent);
            }

    }


    @RequiresApi(api = Build.VERSION_CODES.M)
    public static void displayExpandedNotification(Context context, String title, String message, String url,String image,int icon) {
        System.out.println("sdadsad");
        System.out.println(url);
        Intent intent = new Intent(context, NotificationWeb.class);
        intent.setFlags(FLAG_ACTIVITY_NEW_TASK);
        intent.putExtra("nudge_url",url);
        PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);

        Bitmap bmp = null;
        try {
            InputStream in = new URL(image).openStream();
            bmp = BitmapFactory.decodeStream(in);
        } catch (IOException e) {
            e.printStackTrace();
        }
        NotificationCompat.Builder builder = new NotificationCompat.Builder(context, "234")
                .setSmallIcon(icon)
                .setContentTitle(Html.fromHtml(title))
                .setContentText(Html.fromHtml(message))
                .setAutoCancel(true)
                .setContentIntent(pendingIntent)
                .setPriority(PRIORITY_MAX)
                .setLargeIcon(bmp)
                .setStyle(new NotificationCompat.BigPictureStyle()
                        .bigPicture(bmp)
                        .bigLargeIcon(null))
                .setDefaults(DEFAULT_ALL);
        NotificationManager manager = context.getSystemService(NotificationManager.class);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            @SuppressLint("WrongConstant") NotificationChannel notificationChannel = new NotificationChannel("234", "CustomerGlu", NotificationManager.IMPORTANCE_MAX);

            manager.createNotificationChannel(notificationChannel);
        }
        manager.notify(Integer.parseInt(("234")), builder.build());




    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    public static void displayNotification(Context context, String title, String message, String url,int icon) {
        System.out.println("sdadsad");
        System.out.println(url);
        Intent intent = new Intent(context, NotificationWeb.class);
        intent.setFlags(FLAG_ACTIVITY_NEW_TASK);
        intent.putExtra("nudge_url",url);
        PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);

        NotificationCompat.Builder builder = new NotificationCompat.Builder(context, "234")
                .setSmallIcon(icon)
                .setContentTitle(Html.fromHtml(title))
                .setContentText(Html.fromHtml(message))
                .setAutoCancel(true)
                .setContentIntent(pendingIntent)
                .setPriority(PRIORITY_MAX)
                .setDefaults(DEFAULT_ALL);
        NotificationManager manager = context.getSystemService(NotificationManager.class);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            @SuppressLint("WrongConstant") NotificationChannel notificationChannel = new NotificationChannel("234", "CustomerGlu", NotificationManager.IMPORTANCE_MAX);

            manager.createNotificationChannel(notificationChannel);
        }
        manager.notify(Integer.parseInt(("234")), builder.build());




    }
```

{% endtab %}

{% tab title="iOS (Swift)" %}
To handle the notifications configured via CustomerGlu Dashboard (Push/In-app), use the given method:

**Configure Notification Type -**

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

**Function Parameter:**

**fcmApn**- It accepts string "fcm" or "apn" depending on the notfication service being used by the app.

**Set FCM/APNS Token -**

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)
        CustomerGlu.getInstance.displayBackgroundNotification(remoteMessage: userInfo as? [String: AnyHashable] ?? ["glu_message_type": "glu"])
        completionHandler()
    }
    
    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
        print(userInfo)
        CustomerGlu.getInstance.cgapplication(application, didReceiveRemoteNotification: userInfo, backgroundAlpha: 0.5, 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 %}

### In-App Nudges Samples

![](https://1004846827-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M0ahLW2WavtwcwNbSR9%2F-MU7uOtz6DGUHQtaQbWO%2F-MU7uygdef_o7lW4v7mF%2FGroup%208366.png?alt=media\&token=6bfc1587-eed1-4025-8d29-79aea8337148)
