React Native - v9.1.0

Updated 

Note: We have changed our package name from @sprinklr/chat-native-client to @sprinklrjs/chat-native-client

1) Install Sprinklr messenger**

Install Sprinklr messenger in your project using package manager (yarn/npm) as mentioned below:

yarn:

yarn add @sprinklrjs/chat-native-client@9.1.0

npm:

npm install --save @sprinklrjs/chat-native-client@9.1.0

**Note: Sprinklr Messenger is restricted package so you need to configure the following registry in .npmrc for Sprinklr scoped packages:

@sprinklr:registry=https://prod-nexus-external.sprinklr.com/nexus/repository/npm/
always-auth=true
_auth=<SPR_REGISTRY_AUTH_TOKEN>

Replace <SPR_REGISTRY_AUTH_TOKEN> with registry token provided by Sprinklr.

Note: Please raise a support ticket to tickets@sprinklr.com

2) Install Sprinklr Messenger Peer Dependencies*

Additionally install the following peer dependencies in your project as part of Sprinklr Messenger Installation:

Note: The react-native-reanimated dependency is optional. Install only if you want to use animations and transitions for messages in the Live Chat app. Otherwise, you can skip installing this dependency.

yarn:

yarn add react-native-vector-icons react-native-blob-util react-native-image-picker react-native-video @react-native-community/netinfo react-native-webview react-native-permissions @react-native-camera-roll/camera-roll @react-native-async-storage/async-storage @react-native-clipboard/clipboard react-native-svg react-native-reanimated

npm:

npm install --save react-native-vector-icons react-native-blob-util react-native-image-picker react-native-video @react-native-community/netinfo react-native-webview react-native-permissions @react-native-camera-roll/camera-roll @react-native-async-storage/async-storage @react-native-clipboard/clipboard react-native-svg react-native-reanimated

* Please note that listed dependencies also need to be linked natively so it is recommended to follow their documentation for the installation.

And make sure you have the necessary dependencies, and the version should surpass the specified threshold 

  • "redux": ">=4.0.0" 

  • "react-native": ">=0.70.0" 

  • "react-redux": ">=8.0.0" 

  • "react": ">=18.2.0" 

  • "redux-saga": ">=1.0.1"

  • “react-native-permissions" : “>=3.6.0” 

In case you have the requirement to use the alternative to a specific dependency or you want to provide custom implementation of your own then refer to this section

3) Setup for Android

You can skip this step if your app does not support Android.

1. Link Sprinklr Messenger in your project

Open android/settings.gradle, and add following lines which will add Sprinklr Messenger and related dependencies to your app.

include ':@sprinklr-chat-native-client'

project(':@sprinklr-chat-native-client').projectDir = new File(rootProject.projectDir, '../node_modules/@sprinklrjs/chat-native-client/android')

include ':spr-native-kit'

project(':spr-native-kit').projectDir = new File(rootProject.projectDir, '../node_modules/@sprinklrjs/native-kit/android')


Open android/app/build.gradle, add this line

dependencies {
  implementation project(':@sprinklr-chat-native-client')
}


Add these lines to MainApplication.java, so that Sprinklr Messenger related packages becomes part of React Native package:

import com.sprinklr.messenger.SPRMessengerPackagesProvider
.
.
    @Override
    protected List<ReactPackage> getPackages() {
      List<ReactPackage> packages = new ArrayList<>(Arrays.asList(
          ...{YOUR_NATIVE_PACKAGES}
      ));
      packages.addAll(SPRMessengerPackagesProvider.getPackages());
      return packages;
    } 


2. Add Permissions in your project

Include the following permissions in AndroidManifest.xml if you are supporting upload and download media functionality in messenger:

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.DOWNLOAD_WITHOUT_NOTIFICATION" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />  
<uses-permission android:name="android.permission.POST_NOTIFICATIONS"/> 

4) Setup for iOS

You can skip this step if your app does not support iOS.

1. Link Sprinklr Messenger in your project

Open Podfile, and add following lines which will add Sprinklr Messenger and related dependencies to your app:

pod 'SPRMessenger', :path => '../node_modules/@sprinklrjs/chat-native-client/SPRMessenger.podspec'

pod 'SPRNativeKit', :path => '../node_modules/@sprinklrjs/native-kit/SPRNativeKit.podspec' # Add this pod manually if not linked automatically via react native auto linking

2. Add Permissions in your project

Include the following permissions in info plist file if you are supporting upload and download media functionality in messenger:

<key>NSCameraUsageDescription</key>
<string>Messenger app requires access to the camera to capture the photos.</string>
<key>NSMicrophoneUsageDescription</key>
<string>Messenger app requires access to the microphone to record video.</string>
<key>NSPhotoLibraryUsageDescription</key>
<string>Messenger app requires access to the photos library.</string>

Above permissions are required by Apple for all apps that access the photo library or use the camera/microphone.

5) Initialize Messenger

Sprinklr Messenger can be initialized for both unauthenticated and authenticated users:

  • For Anonymous Users:

For anonymous chats you can initialize the messenger using the takeOff method. Behind the scenes we will automatically create the anonymous user for the messenger and initialize the flow for the same. Please note that the takeOff method should be called once in the application lifecycle. You can use separate methods for updating the user or various information in the messenger which are explained in other sections. For the best performance takeOff should be called at the root of the application or as early as possible in your application flow.

import MessengerClient from '@sprinklrjs/chat-native-client'

MessengerClient.takeOff({
appId: '<SPR_APP_ID>', // This will be provided by sprinklr

 environment: '<SPR_ENVIRONMENT>', // This will be provided by sprinklr
pushAppId: '<SPR_PUSH_APP_ID>', // Should be Unique id, if not sure pass same as device ID

 deviceId: '<UNIQUE_DEVICE_ID>',

skin: 'MODERN', // default value is MODERN, options: CLASSIC | MODERN

 locale: '<SPR_LOCALE>', // default value is en

 themeMode: 'DEFAULT' // default value is DEFAULT, options DEFAULT | DARK
})

Note: appId, environment and locale are mandatory parameters

  • For Authenticated Users: 

For authenticated chats you can initialize the messenger using takeOff method by providing user details. In this flow we will consider provided user’s information for the messenger and initialize the flow for the same. Please note that the takeOff method should be called once in the application lifecycle. You can use separate methods for updating the user or other information or may be for cleanup the messenger which are explained in other section. For the best performance takeOff should be called at the root of the application with user details or as early as possible in your application flow.

import MessengerClient from '@sprinklrjs/chat-native-client'

MessengerClient.takeOff({
appId: '<SPR_APP_ID>', // This will be provided by sprinklr

 environment: '<SPR_ENVIRONMENT>', // This will be provided by sprinklr
pushAppId: '<SPR_PUSH_APP_ID>', // Should be Unique id, if not sure pass same as device ID

 deviceId: '<UNIQUE_DEVICE_ID>',

 locale: '<SPR_LOCALE>', // default value is en

skin: 'MODERN', // default value is MODERN, options: CLASSIC | MODERN

themeMode: 'DEFAULT', // default value is DEFAULT, options: DEFAULT | DARK
user: {
  userId: '12345',
  firstName: 'John',
  lastName: 'Doe',
  phoneNo: '9876543210',
  email: 'John.Doe@example.com',
  profileImageUrl: 'https://example.com/profilePic.jpg',
  hash: 'f30c3b0835ecd378a134c74bce8cea866df8c5b6e12a8c219c9bb288f7270e22'
}
})

Note:

  • appId, environment and locale are mandatory parameters but user object should also be passed in takeOff for authenticated chats.

  • Also note that the UserID and Hash are mandatory parameters and hash should be generated for every change in user object. To know the procedure to generate hash please refer below “How to generate userHash?” 

  • User details are supposed to be concatenated to form a string, separated by underscore as shown below:

userId_firstName_lastName_profileImageUrl_phoneNo_email

  •  If you don’t have a few values, you need not send anything but keep the underscores as is. For example, let’s say you don’t have profileimageUrl, there will be 2 underscores after lastName. The string will be as shown below: 

userId_firstName_lastName__phoneNo_email

 

To know the procedure of how to generate Hash, please refer below.

  • For Authenticated Custom Users: 

This step is done to create a custom user using any custom or specific attributes. In other words, it involves creating user accounts with personalized details or characteristics 
Below is the example to initiate the process with custom attributes and Hash, where you can  pass the attributes values: 

  • Custom Attribute 1 

  • Custom Attribute 2 

  • Hash 

import MessengerClient from '@sprinklrjs/chat-native-client'
 
MessengerClient.takeOff({ 
appId: '<SPR_APP_ID>', // This will be provided by sprinklr 

 environment: '<SPR_ENVIRONMENT>', // This will be provided by sprinklr 
pushAppId: '<SPR_PUSH_APP_ID>',  // Should be Unique id, if not sure pass same as device ID

 deviceId: '<UNIQUE_DEVICE_ID>', 

 locale: '<SPR_LOCALE>', // default value is en 

 skin: 'MODERN', // default value is MODERN, options: CLASSIC | MODERN 

themeMode: 'DEFAULT', // default value is DEFAULT, options: DEFAULT | DARK
customUser: { 
   customAttribute1: 'value1', //Add your custom attribute 
   customAttribute2: ‘value2’, //Add your custom attribute 
   hash: 'f30c3b0835ecd378a134c74bce8cea866df8c5b6e12a8c219c9bb288f7270e22

}) 

 Note: If you wish to implement a Custom User Authentication Flow, kindly get in touch with the Sprinklr Team to initiate discussions about the implementation process. 

How to generate userHash?

The userHash is a generated HMAC or Hash-based Message Authentication Code. For HMAC, Sprinklr uses the sha256 hash function. You need to generate HMAC for the following "string" of user details. User details are concatenated to form a string, separated by underscore as shown below -

userId_firstName_lastName_profileImageUrl_phoneNo_email

So for the above example, the string for which you need to generate the hash would be

12345_John_Doe_https://example.com/profilePic.jpg_9876543210_John.Doe@example.com

Sample code to generate HMAC is mentioned here 

Sample Code Generation for Javascript 

import crypto from 'crypto-js'; 
const getHMACHash = (message, key) => crypto.HmacSHA256(message, key).toString();  //API Key will be provided by Sprinklr

Note: Make sure you have the necessary dependency, and the version should be within the specified threshold 

  • “crypto-js”: "<= 3.3.0”
    Refer here - crypto-js


6) Present Messenger View

Messenger view can be presented by any of your UI controls (like FAB, Messenger Icon, Tab bar Icon etc) as per your application requirement. For presenting the messenger view create a full page messenger view like below which you can define as a scene in your navigator and present as per your use case: 

import { MessengerView } from '@sprinklrjs/chat-native-client';

function SPRMessengerView(launchOptions = {}, onDismiss) {
return (
  <MessengerView launchOptions={launchOptions} onDismiss={onDismiss} /> // onDismiss should be provided to dismiss the messenger when user close the messenger. For e.g. onDismiss: navigation.pop
);
}


LaunchOptions should be provided when messenger need to be opened as a result of notifications etc. Payload structure will be:

launchOptions = { type: NOTIFICATION, data: notification }

7) Present InAppNotificationBanner

To display the messenger notifications to the user when user receive message/reply from support agent and app is in foreground mode then you can show the in-app notification banners at the top inside your app. 

To show in-app banner for messenger related notifications you can either use Sprinklr provided messenger notification banner or you can customize the view as per your requirement.

To use Sprinklr provided in app banner, add MessengerNotificationBanner parallel to root view of the application: 

import { MessengerNotificationBanner } from '@sprinklrjs/chat-native-client';

function onTapNotificationBanner(notification) {
// open sprinklr messenger view with launch options
const launchOptions = { type: 'NOTIFICATION', data: notification };
presentMessengerView(launchOptions); // provide your presentMessengerView.. we need to open conversation in messenger corresponding to the notification
}

function MainApp () {
return (
  <>
    <RootView />
    <MessengerNotificationBanner onTapBanner={onTapNotificationBanner} />
  </>
)
}

To use your customized banner instead of Sprinklr provided banner you have to follow some additional steps apart from adding your banner at the top:

Register your notification handler to the messenger client so that we provide you the control of received notifications which you can use to display received message information in your custom banner:

import MessengerClient from '@sprinklrjs/chat-native-client'

function notificationHandler(notification) {
// write your custom logic here
}


MessengerClient.registerNotificationHandler(notificationHandler)

Notification object structure will be as follows:

{
"data": {
"messageId": "<MESSAGE_ID>",
"title": "<NOTIFICATION_TITLE>",
"description": "<NOTIFICATION_DESCRIPTION>",
"cId": "<CONVERSATION_ID>", // Conversation Id
"imageURI": "<IMAGE_URI>" // Image to display inside notification banner
}
}


Step 2 - Configurations

1) Update user

User attributes can be updated by calling:

import MessengerClient from '@sprinklrjs/chat-native-client'

MessengerClient.updateUser({
  userId: '12345',
  firstName: 'John',
  lastName: 'Doe',
  phoneNo: '9876543210',
  email: 'John.Doe@example.com',
  profileImageUrl: 'https://example.com/profilePic.jpg',
  hash: 'f30c3b0835ecd378a134c74bce8cea866df8c5b6e12a8c219c9bb288f7270e22'
})

Note: UserID and Hash are mandatory parameters and hash should be generated for every change in user object. To know the procedure to generate Hash, please refer above “How to generate userHash?”  

2) Update Custom User 

Custom User attributes can be updated by calling: 

import MessengerClient from '@sprinklrjs/chat-native-client' 
 
MessengerClient.updateCustomUser({ 
   customAttribute1: ‘value1', 
   customAttribute2: ‘value2’, 
   hash: 'f30c3b0835ecd378a134c74bce8cea866df8c5b6e12a8c219c9bb288f7270e22
}) 

3) Update language

To update the user language use below function:

import MessengerClient from '@sprinklrjs/chat-native-client'


MessengerClient.updateLocale(locale)

Sprinklr live chat supports the following languages: Arabic, Bokmal, Chinese, English, Thai, Turkish, Vietnamese, Portuguese, Spanish, Indonesian, Japanese, Korean, French. 

Few languages with limited availability are Albanian, Norwegian, Bosnian, Chinese (traditional), Chinese (honk-kong), Croatian, Czech, Danish, Dutch, Estonian, Finnish, German, Hebrew, Hungarian, Italian, Latvian, Lithuanian, Macedonian, Malayalam, Polish, Romanian, Serbian, Slovak, Slovanian, Swedish.


4) Cleanup

You can logout the user and cleanup the associated data from the application by calling cleanup

import MessengerClient from '@sprinklrjs/chat-native-client'

MessengerClient.cleanup()


5) Customize Messenger Landing Screen 

By default, the messenger view opens with a home page that displays all conversations. However, you can customize this behavior and launch MessengerView with a single conversation view.

The following section describes the customization you can do with the default view and single conversation view:

Default View

Sprinklr Live Chat comprises of two screens: the home screen and the conversation screen. By default, both screens are accessible when Live Chat opens.

The following are the various ways you can configure the default view based on your use case:

By default, Live Chat opens with both the home screen and the conversation screen. The following code is for the default view:

import { MessengerView } from '@sprinklr/chat-native-client';
function SPRMessenger(launchOptions = {}, onDismiss) {

return (

<MessengerView

launchOptions={launchOptions}

onDismiss={onDismiss}

/>

);

}

Use the following code to open the default view with NEW_CONVERSATION. This configuration will initiate a new conversation on behalf of the user that starts with the welcome messages set in the application builder.

To continue any existing conversations, users must return to the home screen.

import { MessengerView } from '@sprinklr/chat-native-client';
function SPRMessenger(launchOptions = {}, onDismiss) {

const chatInitialisationContext = {

landingScreen: 'NEW_CONVERSATION',

};

return (

<MessengerView

launchOptions={launchOptions}

onDismiss={onDismiss}

chatInitialisationContext={chatInitialisationContext}

/>

);

}

Use the following code to open the default view with LAST_CONVERSATION. This configuration will open the last conversation that is still active. If there are no open conversations, Live Chat will initiate a new conversation on behalf of the user that starts with the welcome messages set in the application builder.

import { MessengerView } from '@sprinklr/chat-native-client';
function SPRMessenger(launchOptions = {}, onDismiss) {

const chatInitialisationContext = {

landingScreen: 'LAST_CONVERSATION',

};

return (

<MessengerView

launchOptions={launchOptions}

onDismiss={onDismiss}

chatInitialisationContext={chatInitialisationContext}

/>

);

}

Use the following code to open the default view with a new conversation that starts with custom brand/user messages.

To continue any existing conversations, users must return to the home screen.

import { MessengerView } from '@sprinklr/chat-native-client';
function SPRMessenger(launchOptions = {}, onDismiss) {

const chatInitialisationContext = {

landingScreen: 'NEW_CONVERSATION',

initialMessages: [

{

message: 'This is a brand message',

isSentByUser: false,

},

'This is another brand message',

{

message: 'This is a user message',

isSentByUser: true,

},

],

};
return (

<MessengerView

launchOptions={launchOptions}

onDismiss={onDismiss}

chatInitialisationContext={chatInitialisationContext}

/>

);

}

Use the following code to open a specific conversation. Ensure that the conversation you want to open is not deleted and has the most recent published message.

To open a specific conversation, you need its conversation ID. You can capture the conversation ID by listening to events indicating the ongoing conversation.

import { MessengerView } from '@sprinklr/chat-native-client';
function SPRMessenger(launchOptions = {}, onDismiss) {

const chatInitialisationContext = {

landingScreen: 'EXISTING_CONVERSATION',

params: {

conversationId: 'id_of_conversation',

} ,

};

return (

<MessengerView

launchOptions={launchOptions}

onDismiss={onDismiss}

chatInitialisationContext={chatInitialisationContext}

/>

);

}

Single Conversation View

You can choose to display only the conversation screen, and hide the home screen completely. 

The following are the various ways you can configure the single conversation view based on your use case:

Use the following code to display the conversation screen in Live Chat and hide the home screen.

Note: The scope: 'CONVERSATION' option limits Live Chat to only the conversation screen.

import { MessengerView } from '@sprinklr/chat-native-client';
function SPRMessenger(launchOptions = {}, onDismiss) {

const chatInitialisationContext = {

scope: 'CONVERSATION',

};

return (

<MessengerView

launchOptions={launchOptions}

onDismiss={onDismiss}

chatInitialisationContext={chatInitialisationContext}

/>

);

}

When Live Chat is set to a single conversation view with NEW_CONVERSATION, it initiates a new conversation on behalf of the user. This conversation starts with the welcome messages set in the application builder.

This configuration will always open a conversation view by initiating a new conversation, and will not show any previous conversations that are currently open.

import { MessengerView } from '@sprinklr/chat-native-client';
function SPRMessenger(launchOptions = {}, onDismiss) {

const chatInitialisationContext = {

scope: 'CONVERSATION',

landingScreen: 'NEW_CONVERSATION',

};

return (

<MessengerView

launchOptions={launchOptions}

onDismiss={onDismiss}

chatInitialisationContext={chatInitialisationContext}

/>

);

}

When Live Chat is set to single conversation view with LAST_CONVERSATION, it opens the last conversation of the user that is still open. If there are no open conversations, it initiates a new conversation on behalf of the user that starts with the welcome messages set in the application builder.

import { MessengerView } from '@sprinklr/chat-native-client';
function SPRMessenger(launchOptions= {}, onDismiss) {

const chatInitialisationContext = {

scope: 'CONVERSATION',

landingScreen: 'LAST_CONVERSATION',

};

return (

<MessengerView

launchOptions={launchOptions}

onDismiss={onDismiss}

chatInitialisationContext={chatInitialisationContext}

/>

);

}

Use the following code to open a single conversation view with a new conversation that starts with a custom message from your brand or user.

import { MessengerView } from '@sprinklr/chat-native-client';
function SPRMessenger(launchOptions = {}, onDismiss) {

const chatInitialisationContext = {

scope: 'CONVERSATION',

landingScreen: 'NEW_CONVERSATION',

initialMessages: [

{

message: 'This is a brand message',

isSentByUser: false,

},

'This is another brand message',

{

message: 'This is a user message',

isSentByUser: true,

},

],

};
return (

<MessengerView

launchOptions={launchOptions}

onDismiss={onDismiss}

chatInitialisationContext={chatInitialisationContext}

/>

);

}

Use the following code to open a specific conversation without the home page. Ensure that the conversation you want to open is not deleted and has the most recent published message.

To open a specific conversation, you need its conversation ID. You can capture the conversation ID by listening to events indicating the ongoing conversation.

import { MessengerView } from '@sprinklr/chat-native-client';
function SPRMessenger(launchOptions = {}, onDismiss) {

const chatInitialisationContext = {

scope: 'CONVERSATION',

landingScreen: 'EXISTING_CONVERSATION',

params: {

conversationId: 'id_of_conversation',

} ,

};

return (

<MessengerView

launchOptions={launchOptions}

onDismiss={onDismiss}

chatInitialisationContext={chatInitialisationContext}

/>

);

}

6) Capture customer context when starting a new conversation from custom view

When chat is being opened from a custom view, sometimes you might want to capture additional context on the conversation/case. 

Example - A button called “Know More about this laptop”  near a laptop product which opens a chat with a predefined contextual welcome message - “Hi there! It looks like you are interested in buying a laptop”. At the same time, you might want to set the case custom fields indicating the “product category: laptop”, “case type: inquiry”.

To do this, 

  1. Create the case custom fields and note down their field name

  2. Pass conversationContext to chatInitialisationContext* when opening new conversation directly (5ea7fa9e87651f356209878f and 5eb7fa9e87651f356219348e are the two custom field names)


const chatInitialisationContext = {
...restFields
conversationContext: {
  "5ea7fa9e87651f356209878f": ['laptop'],
  "5eb7fa9e87651f356219348e": ['inquiry']
}
}


* Note: chatInitialisationContext is explained in previous section

7) Capture customer context from the application on all cases of the user

Sometimes you might want to pass some contextual information in case custom fields for new conversations started by the user. 

To do this,

  1. Create the case custom fields and note down their field name. Field Name can be copied from the Sprinklr UI by navigating to Custom Fields -> Click on 3 dots -> Copy Field Name. 

  2. You can pass these values in clientContext in the takeOff method called in step 5.  (5e281d040844e435b is the custom field name)

import MessengerClient from '@sprinklrjs/chat-native-client'

MessengerClient.takeOff({
...restSettings,
clientContext: {"5e281d040844e435b": ["Custom Field Value"]}
})


You can also update the client context on run time by calling the following method:

import MessengerClient from '@sprinklrjs/chat-native-client'

MessengerClient.updateClientContext({"5e281d040844e435b": ["Custom Field Value"]})



8) Update Conversation Context (Case Custom Field) on Demand 

At times you might want to update the value of conversation context/case custom field during or after a conversation.  

Example: After a purchase is made on the website you might want to set the transaction amount or id on the case for reporting. After doing this, you can attribute sales to each conversation/case.  

To do this,  

  1. Create the case custom fields and note down their field name1.  

  2. Whenever you want to update the case custom field, call the following JavaScript function (5e291d040844e435b is the custom field name). 

    import MessengerClient from '@sprinklrjs/chat-native-client'
      
    MessengerClient.updateConversationContext({"context": {"5e291d040844e435b": ["Custom Field Value"]}})

 

9) Update the profile context within Profile Custom Fields

When chat is being opened from a custom button or hyperlink, sometimes you might want to capture some context on the profile/user during the conversation or after the conversation. To do this, 

  1. Create the profile custom fields and note down their field name 

  2. Whenever you want to update the profile custom field, call the following JavaScript function and pass the information for profile level custom fields. 
    This can be done via sdk for updating it on-demand 

    import MessengerClient from '@sprinklrjs/chat-native-client' 
     
    MessengerClient.updateUserContext({"5e281d040844e435b": ["Custom Field Value"]}) 

10) Close Messenger

You can close messenger by

import MessengerClient from '@sprinklrjs/chat-native-client';

MessengerClient.closeMessenger();

11) Get number of open conversations

Sometimes you might want to hide the live chat widget based on the number of open conversation. 

To do this,

1. Call the the below function to get the number of open conversations

import MessengerClient from '@sprinklrjs/chat-native-client'

// Call this function to fetch the number of open conversations
MessengerClient.getNumberOfOpenConversations()

2. Listent to the output of the above function to get the number of open conversations

import MessengerClient from '@sprinklrjs/chat-native-client'

// Register this callback to listen for the output of above function


MessengerClient.onNumberOfOpenConversations((count) => {

 // Write your implementation here

})

import MessengerClient from '@sprinklrjs/chat-native-client'
// Call this function to stop listening for number of open conversations
// This should mostly be called in componentWillUnmount function of your main app

MessengerClient.offNumberOfOpenConversations()

12) Get Number of Unread Messages

You'll get notified whenever there's a change in the unread message count. It's a convenient way to stay updated on unread message counts in real-time

import MessengerClient from '@sprinklrjs/chat-native-client';
MessengerClient.registerUnreadMessagesCountHandler(this.unreadMessagesCountHandler);

unreadMessagesCountHandler = (payload) => {
  // Success Payload:
  // success: true,
  // unreadMessagesCount

  // Failure Payload:
  // success: false,
  // error,
};

// Call unregister to stop listening for unread count

MessengerClient.unregisterUnreadMessagesCountHandler();

13) Add delegate to listen to external events from messenger

import MessengerClient from '@sprinklrjs/chat-native-client';

MessengerClient.setMessengerActionHandler(this.messengerActionsHandler);

messengerActionsHandler = (type, payload) => {};


14) Add Messenger Analytics Handler to Listen to tracking events and screen

import MessengerClient from '@sprinklrjs/chat-native-client';

MessengerClient.registerAnalyticsTracker({
trackScreen: this.trackScreen,
trackEvent: this.trackEvent,
});

trackScreen = (screenName) => {};

trackEvent = ({ eventType, ...restPayload }) => {};

15) Add Messenger Events Listener to SDK events

The following events can be listened:

Event Type:

  1. BOOT_FAILED

  2. BOOT_STARTING

  3. BOOT_COMPLETE

  4. USER_LOGOUT

  5. SSL_CERTIFICATE

  6. UPDATE_USER_FAILED

  7. UPDATE_USER_SUCCESS

  8. UPDATE_USER_CONTEXT_FAILED

  9. UPDATE_CLIENT_CONTEXT_FAILED

  10. ANONYMOUS_SESSION_CREATION_STARTING

  11. ANONYMOUS_SESSION_CREATION_SUCCESS

  12. ANONYMOUS_SESSION_CREATION_FAILED

  13. UPDATE_USER_STARTING

Event Type: INTERNET_CONNECTION_STATUS_CHANGED

Event Type:

  1. PUSH_NOTIFICATION_REGISTRATION_EXISTS

  2. PUSH_NOTIFICATION_REGISTRATION_SUCCESS

  3. PUSH_NOTIFICATION_REGISTRATION_FAILED

  4. PUSH_NOTIFICATION_UNREGISTRATION_SUCCESS

  5. PUSH_NOTIFICATION_UNREGISTRATION_FAILED

Event Type:

  1. NEW_CONVERSATION_INITIATION_FAILED

  2. CONVERSATION_CLOSED

  3. CONVERSATION_DELETED

  4. CONVERSATION_CLOSE_FAILED

  5. CONVERSATION_DELETE_FAILED

  6. CONVERSATION_CLOSED_BY_AGENT

import MessengerClient from '@sprinklrjs/chat-native-client';

MessengerClient.registerEventsListener(this.eventsListener);

eventsListener = (eventGroup, eventType, payload) => {};

16) Add Events Logger to SDK Events

The provided code snippet establishes a custom logging system which can handle logging events at different levels. This setup enables us to efficiently track and manage various events within the app.

MessengerClient.setLoggerConfig({

      enableLogs: true, // required to enable logs

      logLevel: 4, // optional, default level is 4

      transports: [

        {

          write(level, ...logs) {

            // your custom logger transport

          },

        },

      ], // optional, default transport is console

    });

The following log levels are maintained:

OFF: 0,

FATAL: 1,

ERROR: 2,

WARN: 3,

INFO: 4,

DEBUG: 5,

TRACE: 6,

ALL: 7

17) Update Theme Mode for User on demand

You can update the theme mode on demand:

MessengerClient.updateThemeMode('DARK'); // options: DEFAULT | DARK

Note: Upon invoking the updateThemeMode() method, a confirmation alert will prompt the user to reload the app for the changes in theme to take effect. Furthermore, the parent application should send the updated theme within the configuration while chat initialization

 

18) Configure your Status Card

Note: To get this capability enabled, please reach out to our support team at tickets@sprinklr.com, providing the live chat application ID. Status Card can be enabled only if you are using the modern skin version of live chat widget.

Using Status Cards, you can update your customers about the health of a key resource. This key resource could be a tool or service that they interact with frequently. By showing the status of this resource directly, customers don’t have to reach to agents repeatedly. Hence, this improves the customer experience while reducing agent workload.

Once status card is enabled for your Livechat widget, you can update the status card by using the following:

import MessengerClient from '@sprinklrjs/chat-native-client’;

MessengerClient.updateWidget({

id: ‘WIDGET_ID’, // Same ID configured in the Live Chat builder must also be utilized here

    details: {

      title: ‘Your title, %%[status]’,

      description: ‘Your description, %%[updatedAt]’,

status: ‘ALL_SYSTEMS_OPERATIONAL’,

      updatedAt: Date.now(),

    },

});

You can use the following placeholders for title and description:

a.     %%[updatedAt] --> Placeholder for formatted time

b.    %%[status] --> Placeholder for Status, mentioned below in the table as SPR_STATUS


Status Placeholder Value


Icon



SPR_STATUS



All Systems Operational





ALL_SYSTEMS_OPERATIONAL



Service Under Maintenance





SERVICE_UNDER_MAINTENANCE



Partially Degraded Service





PARTIALLY_DEGRADED_SERVICE



Degraded System Service





DEGRADED_SYSTEM_SERVICE



Partial System Outage





MINOR_SYSTEM_OUTAGE



Minor System Outage





PARTIAL_SYSTEM_OUTAGE



Major System Outage





MAJOR_SYSTEM_OUTAGE


 

 

19) Disable Attachments for Customer

 You can prevent customers from adding attachments in the chat by hiding the attachment icon from the chat widget.


To do this, you can pass disableAttachment:true in the takeOff method

import MessengerClient from '@sprinklrjs/chat-native-client’;

MessengerClient.takeOff({

  ...restSettings,

disableAttachment: true, // by default, attachments are enabled

});

20) Integrate Your Brand's Custom Header in Live Chat 

Enhance your live chat experience by incorporating your own custom header. This allows you to replace Live Chat default header with one that aligns with your brand identity, creating a consistent and seamless experience for your users. 

import { MessengerView } from '@sprinklrjs/chat-native-client'; 

  

function SPRMessenger(launchOptions = {}, onDismiss) { 

  const chatInitialisationContext = { 

    disableHeader: false, // Default: false. To disable Sprinklr's header, set to true 

    isRenderedAsFullView: true // Default: true. If set to false, the brand must manage device top insets 

 

  }; 

  return ( 

    <MessengerView 

      launchOptions={launchOptions} 

      onDismiss={onDismiss} 

      chatInitialisationContext={chatInitialisationContext} 

    /> 

); 

 

21) Implement Back Button Handling to Control Hardware Back Button 

Utilize the below method to handle the back action within your chat application. This function allows users to seamlessly navigate back to the previous screen, enhancing the overall user experience by providing intuitive and efficient navigation 

import MessengerClient from '@sprinklrjs/chat-native-client'; 

MessengerClient.goBack(); 

 

22) Close Conversation 

Use the method below to close a conversation on live chat. This feature allows brands to efficiently handle conversation endings, providing control over when and how interactions are closed. Apply this method only on the conversation screen when the case is open to ensure a seamless transition for users as conversations end. 

import MessengerClient from '@sprinklrjs/chat-native-client'; 

MessengerClient.closeConversation(); 

 

23) Close All Conversations 

Use the method below to close all conversation on live chat. This option is visible to users with open cases, if there are no cases or all existing cases are already closed then user will not be able to see this option.

import MessengerClient from '@sprinklrjs/chat-native-client';

MessengerClient.closeAllConversations();

 

24) Delete Conversation 

Use this method to delete a conversation in live chat. This feature allows brands to efficiently remove interactions as needed, providing control over conversation deletions.  Apply this method only on the conversation screen to manage deletions effectively. 

import MessengerClient from '@sprinklrjs/chat-native-client'; 

MessengerClient.deleteConversation(); 

25) Delete All Conversations 

Use this method to delete all the conversations in live chat. This feature allows brands to efficiently remove interactions as needed, providing control over conversation deletions. Apply this method only on the home screen to manage deletions effectively.

import MessengerClient from '@sprinklrjs/chat-native-client';

MessengerClient.deleteAllConversations();

 

26) Clear User Session

You can now enable users to clear their session details. When a user clears their session, any new conversations will be treated as if they are from a completely new user. This feature is especially useful for users interacting with your brand in public spaces or over a public network.

import MessengerClient from '@sprinklrjs/chat-native-client';

MessengerClient.clearSession();

27) Use a Custom Font

You can use a custom font in your Live Chat app to ensure consistent branding across your applications. 

​To use a custom font in Live Chat, follow these steps:

  1. Link your custom font files in your iOS and Android projects natively, such that the fonts are available throughout the project. For steps, see iOS and Android documentation.

  2. Open a Sprinklr support ticket at tickets@sprinklr.com. In the support ticket, mention the font file names and the supported font weights for the texts. Refer to the following table for the supported font weights.

Note: Ensure you provide at least one of the supported font weights in the support ticket. If you provide a single font weight, it will be applied throughout the app, overriding all the other font weights. 

Similarly, if any of the font weights are not mentioned in the support ticket, the font weight closest to the non-mentioned font weight will be applied in the app.

Supported font weights​

The following table lists the supported font weights:

Font weight

Description

Light

The light font weight is for subtle accents, secondary text, and areas where minimal emphasis is required.

Regular

The standard font weight for most text elements.

Medium

Medium is used for subheadings, labels, or emphasis on certain text sections without the bold impact.

Semibold

Works well for headings, button labels, or any text that needs more attention but doesn’t require bold styling.

Bold

Bold is designed for titles, primary headings, and call-to-action elements.

Step 3 - Push Notifications

For more details on mobile push notifications, please refer here

Prerequisite

  1. Android: Google service.json file

  2. iOS: APNS certificate (P12) along with its credentials

Note:

  • Google service.json file can be different for staging/prod env

  • APNS certificate (P12) and its credentials must be different for staging/prod env

  • If you are testing the push notification setup on prod mobile application(iOS), plesae ensure to use test flight build

  • If the Google service.json file is different sandbox/prod env and you are testing the push notification setup on prod mobile application(Android), plesae ensure to use test flight build

Configuration

To enable push notifications, please raise a support ticket to tickets@sprinklr.com with the following information:

  1. Google service.json file

  2. APNS certificate (P12) along with its credentials

  3. Live Chat AppID

  4. Partner ID

  5. Env

1) Register/Unregister for push notifications

You can register the messenger for sending push notifications by providing push token received from apns/fcm as below:

import MessengerClient from '@sprinklrjs/chat-native-client'

MessengerClient.updatePushToken('f30c3b0835ecd378a134c74bce8cea866df8c5b6e12a8c219c9bb288f7270e22')

You can unregister for messenger push notifications by sending empty token as below:

import MessengerClient from '@sprinklrjs/chat-native-client'

MessengerClient.updatePushToken('');

2) Handle Messenger Push Notifications

Once you have registered for messenger push notifications then you might receive notifications from your platform as well as messenger. To check if notification is messenger notification you can check as below:

import MessengerClient from '@sprinklrjs/chat-native-client'

let isMessengerNotification = MessengerClient.canHandlePushNotification(notification); // Returns a bool which indicates whether the notification is messenger notification or not

Once you have identified if notification is messenger notification you need to follow certain steps to handle messenger notification as mentioned below:

import MessengerClient from '@sprinklrjs/chat-native-client'

// when push notification is received from server
function onNotificationReceived(notification) {
  if (MessengerClient.canHandlePushNotification(notification)) { // check if notification is messenger notification
    if (!notification.foreground) { // handle notifications when application was background/killed
      // when app is in background/inactive state then user has already seen and tapped the notification to see messenger conversation and hence we need to jump on to conversation corresponding to notification
      handleMessengerPushNotification(notification);
    }
    return;
  }
  // not a messenger notification.. write your custom logic here to handle your platform notification
}

function handleMessengerPushNotification(notification) {
  if (MessengerClient.isMessengerMounted()) { // check if messenger is already presented or not
    MessengerClient.handlePushNotification(notification); // show conversation corresponding to notification
  } else {
    // open sprinklr messenger view with launch options
    const launchOptions = { type: 'NOTIFICATION', data: notification };
    presentMessengerView(launchOptions); // provide your presentMessengerView.. we need to open conversation in messenger corresponding to the notification
  }
}

3) Open live chat Messenger

  • Open live chat view with initial notification: Messenger view can be presented with initial notification as the result of opening from notifications or in-app notification banners:

import { MessengerView } from '@sprinklrjs/chat-native-client';

function SPRMessenger(launchOptions = {}, onDismiss) {
return (
  <MessengerView
    launchOptions={launchOptions}
    onDismiss={onDismiss}
  />
);
}

Customizing Peer Dependencies

Why Customization is required?

In some cases, you might already be using specific libraries for functionalities like SVG rendering, web views, and network information in your existing codebase. Switching to the peer dependencies mentioned in the Sprinklr SDK documentation could lead to potential conflicts and disrupt your current setup.

To maintain consistency and avoid these issues, the Sprinklr SDK allows you to inject your own implementations for certain dependencies. This flexibility ensures that you can integrate the SDK seamlessly without having to replace your preferred libraries. By doing so, you can continue to use the libraries that best suit your needs while still leveraging the capabilities of the Sprinklr SDK.

You can inject custom implementations for the peer dependencies mentioned above. However, some of these dependencies are mandatory, while others support customization.

Mandatory Peer Dependencies

To ensure the Sprinklr SDK functions properly, the following dependencies are absolutely necessary and cannot be customized. The versions must also be greater than or equal to the specified ones:

List of Custom Dependencies

Below is a list of all possible custom dependencies along with their implementation types and their dependency key. Each implementation type can be imported from @sprinklrjs/chat-native-client:

Example Import

Here’s an example of how to import an implementation type and the entire dependency key object:

import { SPRCustomStorage, EXTERNAL_DEPENDENCY } from '@sprinklrjs/chat-native-client';

Note: The above code is just an example for SPRCustomStorage and is not the actual implementation

Registering Custom Implementations

To provide custom implementations for the dependencies, follow these steps: 

  1. Identify the Dependency Key: Each custom implementation corresponds to a specific dependency key. 

  2. Import the Implementation Type: Import the required implementation type from @sprinklrjs/chat-native-client to check the expected implementation. 

  3. Import MessengerDependenciesManager from @sprinklrjs/chat-native-client and register the dependencies along with its implementation for which you want to inject custom implementations:

import { EXTERNAL_DEPENDENCY, MessengerDependenciesManager } from '@sprinklrjs/chat-native-client'; 
 
MessengerDependenciesManager.getInstance().registerDependencies({ 
 [EXTERNAL_DEPENDENCY.ASYNC_STORAGE]: { 
   getItem: (key) => Promise.resolve(''), 
   setItem: (key, value) => Promise.resolve(), 
   removeItem: (key) => Promise.resolve() 
 }, 
}); 

Note: The above code is just an example for SPRCustomStorage and is not the actual implementation

You can also use the registerDependency method if you want to inject a custom implementation for a single dependency: 

import { EXTERNAL_DEPENDENCY, MessengerDependenciesManager } from '@sprinklrjs/chat-native-client'; 
 
MessengerDependenciesManager.getInstance().registerDependency(EXTERNAL_DEPENDENCY.ASYNC_STORAGE, { 
 getItem: (key) => Promise.resolve(''), 
 setItem: (key, value) => Promise.resolve(), 
 removeItem: (key) => Promise.resolve() 
}); 

Note: The above code is just an example for SPRCustomStorage and is not the actual implementation

Unregistering Custom Implementations

There are methods available to remove the implementation of all custom dependencies (unregisterDependencies) or a particular dependency (unregisterDependency)

import { EXTERNAL_DEPENDENCY, MessengerDependenciesManager } from '@sprinklrjs/chat-native-client'; 
MessengerDependenciesManager.getInstance().unregisterDependency(EXTERNAL_DEPENDENCY.ASYNC_STORAGE); 

MessengerDependenciesManager.getInstance().unregisterDependencies(); 

Troubleshooting

1) LiveChat not showing up while passing authenticated user details

Check the expected hash for any authenticated user passed inside chat settings.

  • Hover over the Options icon alongside your Live Chat Application and select Validate User Hash.

  • On the Validate User Hash window, enter User ID, Profile Image URL, First Name, Last Name, Phone Number and Email. Click Copy Generated Hash and verify it with the hash generated by you.

2) If app crashes while rendering MessengerView, where UIViewControllerBasedStatusBarAppearance should be ‘False’ 

If your app screens depend on UIViewControllerBasedStatusBarAppearance to be true, and changing its value is not possible, please follow the below steps to overwrite it: 

  • We have exposed a MessengerUIManagerProvider that you will need to wrap around the MessengerView. Then you can pass the implementation of the StatusBar as it follows: 

    import { MessengerUIManagers } from '@sprinklrjs/chat-native-client'; 
     
    const { 
      Provider: MessengerUIManagersProvider, 
      UI_MANAGER_TYPES: MESSENGER_UI_MANAGER_TYPES, 
    } = MessengerUIManagers; 
     
    const statusBarManager = useMemo(() => { 
      return { 
        pushStackEntry: props => { 
          // custom implementations 
        }, 
        popStackEntry: props => { 
          // custom implementations 
        }, 
        replaceStackEntry: (propsToReplace, props) => { 
          // custom implementations 
        }, 
        setHidden: (hidden, animation) => { 
          // custom implementations 
        }, 
        setBarStyle: (barStyle, animated) => { 
          // custom implementations 
        }, 
        setBackgroundColor: (backgroundColor, animation) => { 
          // custom implementations 
        }, 
        setTranslucent: translucent => { 
          // custom implementations 
        }, 
      }; 
    }, []); 
     
    const uiManagers = useMemo( 
      () => ({ 
        [MESSENGER_UI_MANAGER_TYPES.STATUS_BAR]: statusBarManager, 
      }), 
      [statusBarManager], 
    ); 
     
    return ( 
      <MessengerUIManagersProvider value={uiManagers}> 
        <MessengerView 
          onDismiss={navigation?.pop} 
          launchOptions={route?.params?.launchOptions} 
          chatInitialisationContext={route?.params?.chatInitialisationContext} 
        /> 
      </MessengerUIManagersProvider> 
    ); 

3) Check if correct FCM Server key is being used for push notifications using Open API of FCM

​Please use the following curl with your FCM server key and registration device token, to check if the FCM Server key is correct or not:

/curl --location 'https: //fcm.googleapis.com/fcm/send' \--header 'Content-Type: application/json' \--header 'Authorization: key=<YOUR_FCM_SERVER_KEY>' \--data '{    "to": "<REGISTERED_DEVICE_TOKEN>",    "data": {        "title": "Title", //Title of the push notification        "message": "New Message" //Message of the push notification    }}'

​4) Disable Autolinking of peer dependencies

​If you encounter issues that might be caused by autolinking, you can disable autolinking for the @sprinklrjs/chat-native-client package on Android.

To do this, create a react-native.config.js file in your project’s root directory if it doesn't already exist.

Add the following configuration to the file to prevent autolinking for the Android platform:

module.exports = {
dependencies: {
   '@sprinklrjs/chat-native-client': {
     platforms: {
       android: null, // disable Android platform, other platforms will still autolink if provided
     },
   },
},
};

After adding this configuration, perform a clean installation using yarn and then rebuild your app to apply the changes.