Skip to content

In‐app chat

Maksym Svitlovskyi edited this page Dec 23, 2024 · 19 revisions

Find more info about Live chat product on Infobip docs.

Intro

In-app chat is the mobile component for connecting and interacting with Infobip's LiveChat product. In-app chat is built on top of Mobile Messaging SDK and that's why Mobile Messaging should be included into your application and properly configured. In-app chat requires from you a careful setup, both in your mobile app and in Infobip's portal. The following steps must be prepared in order to ensure the chat communication:

  1. Include and setup Mobile Messaging SDK plugin in your application. If you haven't already, please follow its Quick start guide carefully. Only by being able to receive a pushRegistrationId in your device, you'll be able to successfully connect to In-app chat in the next steps.

  2. Create a LiveChat Widget and link Mobile Messaging application profile you created in step 1 to the widget configuration.

  3. Setup In-app chat for Mobile Messaging SDK plugin, put inAppChatEnabled: true in configuration:

mobileMessaging.init({
        ...
        inAppChatEnabled: true,
        ...
});

Display In-app chat view

By default In-app chat screen will be displayed with toolbar and back button at the left corner for closing the screen.

MobileMessaging.showChat()
android_chat_screen ios_chat_screen
Examples of android and iOS in-app-chat
You can configure presenting options for iOS, so that In-app chat screen will be displayed with toolbar and x button for iOS.
MobileMessaging.showChat({
    ios: {
         shouldBePresentedModally: true
    }
});

Customer's Chat History

When your app is installed, it is assigned a set of ids for receiving push notifications and connecting to LiveChat. And also a "person" entity is created on Infobip side, automatically, and mostly empty, for that installation. There is separate page explaining users and installations terminology.

While having an anonymous customer/person fits some use cases, most likely you have an authenticated customer you can/want to identify (for example by his/her email, phone number, or some other unique id). Fortunately, you can use the Personalize feature of Mobile messaging SDK to not only to link your customer to your app installation, but also for recovering the chat history of that customer.

Once your app has received the push registration, personalize your customer and, next time the chat is shown, previously sent messages will be presented, recovering the open conversation.

There is also option to depersonalize, that reverts the customer to its original, anonymous state, emptying the chat history. This is a common/suggested practice in log-out flows.

Customize In-app chat

You can define your own custom appearance for chat view by passing json containing predefined fields to mobileMessaging.setChatCustomization();. Call this method before loading the chat, once our SDK has been initialised, for the changes to be applied. We offer an example on chat customization in the example application.

Json object fields

  • Status bar
    • chatStatusBarBackgroundColor (String) -- in hex format, color of the status bar
    • chatStatusBarIconsColorMode (String) -- text one of ['dark','light'] indicating light/dark mode of status bar's icons
  • Toolbar
    • chatToolbar (Object) -- a Toolbar Json fields, used in chat screen
    • attachmentPreviewToolbar (Object) -- a Toolbar Json fields, used in attachment preview screen
    • attachmentPreviewSaveMenuItemIcon (String) -- save icon resource (path to file) in attachment preview screen
    • attachmentPreviewMenuItemsIconTint (String) -- in hex format, icons tint in attachment preview screen
  • Network error
    • networkErrorText (String) -- text of network error alert
    • networkErrorTextColor (String) -- in hex format, text color of network error alert
    • networkErrorTextAppearance (String) -- text appearance of network error alert
    • networkErrorLabelBackgroundColor (String) -- in hex format, background of text in network error alert
  • Chat
    • chatBackgroundColor (String) -- in hex format, chat background color
    • chatProgressBarColor (String) -- in hex format, chat's loading progress bar's color
  • Input
    • chatInputTextAppearance (String) -- text appearance in input
    • chatInputTextColor (String) -- in hex format, color text in input
    • chatInputBackgroundColor (String) -- in hex format, input's background color
    • chatInputHintText (String) -- input's hint text (placeholder)
    • chatInputHintTextColor (String) -- in hex format, input hint's color
    • chatInputAttachmentIcon (String) -- attachment's icon resource (path to file) in input
    • chatInputAttachmentIconTint (String) -- in hex format, input attachment's icon color
    • chatInputAttachmentBackgroundDrawable (String) -- resource (path to file), icon which is used as background for attachment button in chat input
    • chatInputAttachmentBackgroundColor (String) -- in hex format, background color of the attachment icon in the input view
    • chatInputSendIcon (String) -- resource (path to file), icon which represent send button in chat input
    • chatInputSendIconTint (String) -- in hex format, tint color of chat input send button
    • chatInputSendBackgroundDrawable (String) -- resource (path to file), icon which is used as background for send button in chat input
    • chatInputSendBackgroundColor (String) -- resource (path to file), icon which is used as background for send button in chat input
    • chatInputSeparatorLineColor (String) -- in hex format, color of a separator between the chat and the chat input
    • chatInputSeparatorLineVisible (Boolean) -- indicating if separator line is visible
    • chatInputCursorColor (String) -- in hex format, color of chat input cursor

Toolbar Json fields

  • backgroundColor (String) -- in hex format, background of toolbar
  • navigationIcon (String) -- back icon resource (path to file)
  • navigationIconTint (String) -- tint of back icon
  • titleTextAppearance (String) -- text appearance of toolbar title
  • titleTextColor (String) -- in hex format, color of toolbar title
  • titleText (String) -- toolbar title text
  • titleCentered (Boolean) -- indicating if toolbar text is centered
  • subtitleTextAppearance (String) -- text appearance of toolbar subtitle, android only
  • subtitleTextColor (String) -- in hex format, color of subtitle, android only
  • subtitleText (String) -- subtitle text, android only
  • subtitleCentered (Boolean) -- indicating if subtitle text is centered, android only

Note: Same style can be achieved in a xml format of android styles. Define your own theme.

Livechat widget theme

Livechat widget themes are defined on the Live chat widget setup page on Infobip Portal. You can define multiple custom themes and customize various widget attributes, read Livechat documentation to get information about all possible widget customization options.

To set Livechat theme in In-app chat you must:

  1. Define the name and values of your theme(s) in a JSON format, under widget section Theme -> Advanced Customization, in Infobip Portal.
  2. Once you know the names of your themes, you can use them with MobileMessaging.setWidgetTheme() function.

Handle notification taps

Mobile Messaging Plugin has notificationTapped event, which will be sent when user opens the app by tapping on the notification alert. Note that chat messages may be recognised by chat attribute:

mobileMessaging.register('notificationTapped', (eventData) => {
      if (eventData[1].chat) {
        console.log('Chat message tapped', eventData);
      }
});

Customize notifications

Set title and message body in in-app chat notifications and override default values. Default value for title is Chat message. Default value for body is original message content from push notification. To use default values again you have to set setChatPushTitle(null) and setChatPushBody(null). Supported only by Android platform.

mobileMessaging.setChatPushBody('Custom Chat Body');
mobileMessaging.setChatPushTitle('Custom Chat Title');

In-app chat events

In-app chat library supports all core SDK library events plus following chat specific events:

Event Parameters Description
inAppChat.availabilityUpdated boolean for isConfigurationSynced Occurs when the connection has been established successfully and chat can be presented (Note: currently iOS only)
inAppChat.unreadMessageCounterUpdated Unread messages count Triggered when number of unread messages is changed.
inAppChat.viewStateChanged In-app chat view name: LOADING, THREAD_LIST, LOADING_THREAD, THREAD, CLOSED_THREAD, SINGLE_MODE_THREAD, UNKNOWN Triggered when when view in InAppChat is changed.
inAppChat.configurationSynced Triggered when chat configuration is synchronized. (Note: Android only)
inAppChat.livechatRegistrationIdUpdated Livechat registration id Triggered when livechat registration id is updated. (Note: Android only)
chatAvailabilityUpdated Boolean telling if chat is available Triggered when chat availability is updated.

Library events can be subscribed on using the following code snippet:

import { mobileMessaging } from 'infobip-mobile-messaging-react-native-plugin';

mobileMessaging.subscribe(
    '<event name>',
    eventData => {
        console.log('Event received', eventData);
    }
);

In-app chat view usage as React component

You can use ChatView from Mobile Messaging plugin like any other React component in your app. Using this approach, you have more flexibility for how In-app chat presented and displayed. In this approach top bar isn't managed by Mobile Messaging plugin, so you need to setup it by yourself. sendButtonColor property can be customized (not supported for Android).

import {
  ChatView,
  mobileMessaging,
} from 'infobip-mobile-messaging-react-native-plugin';

function chatScreen() {
  return <ChatView style={{flex: 1}} sendButtonColor={'#FF0000'}/>;
}

Sending attachments

Starting from [2.1.0 plugin version] we've added sending attachments support, more info in iOS SDK docs, Android SDK docs

Attachments preview

For saving attachments to photo library you will need to add additional permissions

Supported attachment types

Unread chat push messages counter

Starting from version 4.1.0, new API is available to get and reset current unread chat push messages counter. The counter increments each time the application receives chat push message (this usually happens when chat screen is inactive or the application is in background/terminated state). In order to get current counter value use following API:

mobileMessaging.getMessageCounter((result) => {
    console.log('Counter: ' + result);
});

MobileMessaging SDK automatically resets the counter to 0 whenever user opens the chat screen. However, use the following API in case you need to manually reset the counter:

mobileMessaging.resetMessageCounter();

You can register to event inAppChat.unreadMessageCounterUpdated, in order to get updates of the counter in runtime.

Changing localization

The predefined messages prompted within the In-app chat (such as status updates, button titles, input field prompt) by default are localized using system locale setting, but can be easily changed providing your locale string with the following formats: "es_ES", "es-ES", "es".

mobileMessaging.setLanguage("es");

Sending Contextual Data

It is possible to send contextual data / metadata to Infobip’s Conversations via the Mobile Messaging SDK. Data can be sent several times but only last sent data are stored in conversation. Every sent data will overwrite the previously sent contextual data.

There are two possible scenarios:

  1. Contextual data is sent before chat is present and loaded. Mobile Messaging SDK stores the data and automatically sends it once the chat is loaded.
  2. Contextual data is sent when chat is present and loaded. In a single thread, the data will be sent to an open conversation. In multi-thread, LiveChat widget tracks a list of open conversations, and based on the strategy, it will either send it to a currently ACTIVE conversation or ALL conversations.

Multi-thread strategy

In-app chat supports having multiple conversations between an agent and a customer. Considering this, Mobile Messaging SDK needs to know to which conversations send contextual data:

  • ACTIVE - sends metadata to a currently active conversation
  • ALL - sends metadata to all conversations between an agent and a customer (This field has no impact in case of a single-thread LiveChat widget.)
  • ALL_PLUS_NEW - sends metadata to all non-closed conversations for the widget and to any newly created conversations within the current session. If you send an event of a different type in the same session after using ALL_PLUS_NEW, it will override the previous metadata settings, and newly created chats will no longer receive metadata from the earlier usage of ALL_PLUS_NEW.

Mobile Messaging SDK function to send contextual data has four parameters:

  1. The mandatory data, sent as string, in a format of JavaScript objects and values (for guidance, it must be accepted by JSON.stringify())
  2. A multithread strategy, possible values are:
    • ALL = metadata sent to ALL non-closed conversations for a widget
    • ACTIVE = metadata sent to ACTIVE only conversation for a widget. Callback in case of successful send
    • ALL_PLUS_NEW = metadata sent to all non-closed and new conversations
  3. Callback in case of successful send
  4. Callback in case of failure

Usage:

mobilemessaging.sendContextualData(
  "{ exampleKey: 'InAppChat Metadata Value Example' }",
  "ALL_PLUS_NEW",
  () => console.log('Success'),
  (error) => console.log(error)
);

Multiple chat threads

Default LiveChat widget (name of the channel In-app chat uses in backend) works with single chat threads: one customer can only have one single open conversation. But the option to have multiple chat threads can be enabled in its backend setup.

Multithread setting

When the setting above is enabled, the In-app chat UI will automatically offer in mobile:

  • A list (initially empty) of all the unsolved conversation threads the user has opened.
  • A button to "Start new chat" thread.
  • A navigation to each specific conversation thread. To open a particular chat view, user can tap on a conversation in the list.
Threads list Threads list
Examples of android and iOS multiple chat threads

The functionality for multiple chat threads works out of the box: there is no need for extra implementation in the mobile integrator's side. But there is something you may need to consider regarding navigation bar and the back button:

When multiple threads are in use, the SDK needs to take control over the back button to allow a return to the threads list. In other words: In-app chat will handle internal back navigation logic. On the other hand, if you show In-app chat as React component without navigation bar, you have to handle back navigation from thread into threads list. You can observe current chat view by subscribing to the inAppChat.viewStateChanged event and implement back navigation by yourself.

let isNestedDestination = view === "THREAD" || view === "LOADING_THREAD" || view === "CLOSED_THREAD";
if(isNestedDestination){
  mobileMessaging.showThreadList();
}

The demo "Example" app included in the SDK shows you how this is done in the screen under name "MultiThread".

Authenticated chat

It is possible to authenticate a user before accessing the In-app chat, given you have enabled this feature in the LiveChat widget.

Livechat widget JWT authentication setup

The authentication is accomplished by combining the Mobile Messaging SDK personalisation method with a JWT (JSON Web Token). The token needs to be generated by your end (see instructions here).

The authentication will use a unique identifier for your user, that can be an email address, a phone number, or an external identifier. It is crucial for this identifier to be valid, and to match the identity defined in the userIdentity you passed in Mobile Messaging SDK personalisation call - there will be an authentication error otherwise.

Mobile messaging provides setJwtProvider() method to give In-app chat the ability to authenticate users. In Android, the method's callback argument can be triggered multiple times during In-app chat lifetime, due to various events like screen orientation change, internet re-connection and others. If you can ensure JWT expiration time is more than In-app chat lifetime, you can return cached token, otherwise it is important to provide fresh new token for each invocation.

/*
1 - The customer authenticate in your system, and you recognise his/her unique identifier
2 - You call personalise (mobileMessaging.personalize()) with this unique identifier (and optionally, with other attributes such as first name, second name, etc)
3 - Now you can display the chat as an authenticated user by doing the following:
*/

mobileMessaging.setJwtProvider(() => {
   //every invocation create and return fresh token
   return 'your JWT';
});
mobileMessaging.showChat();

Chat and push notifications

In-app chat decides automatically when to send push notifications for incoming messages events based on the following rules:

  • If In-app chat is not loaded/disconnected => push notifications will be sent.
  • If your app is in the background or a device is locked regardless of its connection status => push notifications will be sent.
  • If the app is in the foreground and In-app chat is loaded/connected => push notification will NOT be sent.

In Android In-app chat connection is established and stopped based on component lifecycle. Chat connection is active only when Lifecycle.State is at least Lifecycle.State.STARTED. Chat connection is stopped when Lifecycle.State is below Lifecycle.State.STARTED.

In iOS chat could be loaded/connected but your app may have it hidden (e.g. behind another view) we provide you with the flexibility to control its connection. You can still receive push notifications in the foreground with these methods: stopConnection and restartConnection. Usage example:

mobileMessaging.showChat();
// Hide the chat, e.g., by displaying a new modal on top of it
mobileMessaging.stopConnection();
// Push notifications for new message events will start coming to the device
// When you detect that a chat is visible again to a user, you can reload the chat and stop push notifications by invoking: 
mobileMessaging.restartConnection();

Troubleshooting

If you face any issue using the chat, specially on the first time integration, we encourage to try your application code/certificates in our Example application, as this may give you a hint of potential mistakes. An example of the most common issues our integrators face:

  1. I get in the logs an error about no push registration id.

Please re-check the quick start guide and the steps mentioned above. For iOS, specially the part about the difference between Sandbox and Production environments, and how they need different p12 files uploaded to Infobip's web portal for Apple push notification's to work.

  1. When a chat push notification is tapped, the app is invoked, and remains wherever it previously was - but I want it to display the chat related to the push notification I tapped.

InAppChat cannot present itself: if needs the parent application (your app) to present it. So, when a push notification is tapped, your app needs to recognise that event, and present the chat if you wish so. You can detect when a push notification is tapped, its nature and content, by listening to our library-events. For this case, the event you are looking for is called 'notificationTapped'.

  1. The chat content appears blank, and the text input fields is disabled.

There are many reasons for the chat not working: from incorrect codes/ids in your setup, to badly defined livechat widget in Infobip's web portal. Usually, the console logs (if you enabled debug logs in our SDK) will give you a hint of the issue, and re-checking this guide, or comparing with our Example, should be enough to successfully integrate InAppChat. But if the issue continues, don't exitate to contact our support or ask for help here in our repository's Issues section.

  1. I have all the setup correct, but the chat is still blank and disabled.

Please confirm, within the security and authentication (last) section of your widget setup (in Infobip's web portal), if "Mobile app customer authentication - Authenticate users on mobile using JSON Web Token" is enabled. If you enabled it by mistake, disable it. If you want to authenticate mobile users, make sure you are sending a correct JSON Web Token (otherwise, similar to the point #1, the chat will remain disabled).

Clone this wiki locally