React Native
Updated
Step 1 - Getting Started
1.) Creating Webview and adding live chat URL
Before you begin,
Important - http://prod-live-chat.sprinklr.com/page?appId=65afb12b62317d2d4a58bfad_app_1866548&device=MOBILE&enableClose=true&zoom
In the above URL,
appId=60c1d169c96beb5bf5a326f3_app_950954 → It indicates the live chat application ID; please ask the Sprinklr services team to get you the correct app ID.
device=MOBILE → It indicates that the page is Mobile Responsive.
enableClose = true → It indicates a close button has been added to live chat, on pressing that close button onClose sdk will be called. You will need to set enableClose to true before you try to access it.
zoom = false → It indicates zoom has been disabled inside the webview.
Please check with the success team on the environment you are part of, it can be prod, prod2, prod4 etc. and use the URL accordingly.
In Your Webview Page component, add the following code snippet.
Import WebView from react-native-webview
import { WebView } from 'react-native-webview';
const liveChatUrl = 'http://prod-live-chat.sprinklr.com/page?appId=60c1d169c96beb5bf5a326f3_app_950954&device=MOBILE&enableClose=true&zoom=false&webview=true'; // example url, use one provided by sprinklr
Render WebView with JS, DomStorage, Cache enabled
render() { |
2.) Adding Back button handling to control hardware back button inside the webview
Clicking the back button will take you back to the last page within the Live Chat web view.
const goBackJavascript = `(function() { |
Handle this event in onMessage of WebView
onMessage = event => { |
Listen to hardware back press on Android:
componentDidMount = () => { |
To achieve the best user experience, it is recommended to hide and show webview instead of completely destroying it. Also the webview should be loaded in the background to avoid showing loading state to the user on first launch.
3.) Add Permissions
Android
Include the following permissions in AndroidManifest.xml if you are supporting upload media functionality in messenger:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> <!-- For android 13 and above --!> <uses-permission android:name="android.permission.READ_MEDIA_IMAGES" /> |
iOS
Include the following permissions in info plist file if you are supporting upload media functionality in messenger:
<key>NSCameraUsageDescription</key> |
4.) Initialize Messenger
Sprinklr Messenger can be initialized for both unauthenticated and authenticated users:
For Anonymous Users:
If a user is not logged into your mobile app, you can open live chat without passing user information. The profile created into sprinklr will be an anonymous user.
URL -
For Authenticated Users:
If a user is already logged into your mobile app, you can pass the authenticated details securely to the chat to authenticate the user on the chat itself. This process is called pre-authentication. In pre-authentication you can pass following information securely from the mobile app to the chat -
URL -
Note:
appId, environment and locale are mandatory parameters.
user_id = “pass required value” → It indicates the ID which is passed to profile of user
user_firstName = “pass required value” → It indicates the first name which is passed to profile of user
user_lastName = “pass required value” → It indicates the last name which is passed to profile of user
user_profileImageUrl = “pass required value” → It indicates the profile image which is passed to profile of user
user_email = “pass required value” → It indicates the email ID which is passed to profile of user
user_phoneNo = “pass required value” → It indicates the phone number which is passed to profile of user
user_hash = “pass required value” → It indicates the hash generated for profile of user
Note: If you want to pass more values, please use user context i.e. 2. Configuration Step 3. |
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
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 given below for following languages - PHP, Python 2.7, Python 3.6.1, Ruby (Rails), Java, Node.js
PHP
$key = "acf32e61-14a6-291b-3a1b-cc8854134ea1"; |
Run the above PHP code online - https://repl.it/@AbhishekPriyam/HMACPHPExample
Python 2.7/3.6.1
import hmac |
Run the above Python code online - https://repl.it/@AbhishekPriyam/HMACPythonExample
Ruby (Rails)
require 'openssl' |
Run the above Ruby code online - https://repl.it/@AbhishekPriyam/HMACRubyExample
Java
import javax.crypto.Mac; |
Run the above Java code online - https://repl.it/@AbhishekPriyam/HMACJavaExample
C#
using System; using System.Security.Cryptography; using System.Text;
class Program { static void Main(string[] args) { string key = "acf32e61-14a6-291b-3a1b-cc8854134ea1"; string userId = "12345"; string firstName = "John"; string lastName = "Doe"; string profileImageUrl = "https://example.com/profilePic.jpg"; string phoneNo = "9876543210"; string email = "John.Doe@example.com";
string userDetails = $"{userId}_{firstName}_{lastName}_{profileImageUrl}_{phoneNo}_{email}";
using (HMACSHA256 hmac = new HMACSHA256(Encoding.UTF8.GetBytes(key))) { byte[] hashBytes = hmac.ComputeHash(Encoding.UTF8.GetBytes(userDetails)); string userHash = BitConverter.ToString(hashBytes).Replace("-", "").ToLower();
Console.WriteLine(userHash); } } } |
Run the above Java code online - https://replit.com/@RoshanDash1/HmacCExample
Node.js
var crypto = require('crypto'); |
Run the above Node.js code online - https://repl.it/@AbhishekPriyam/HMACNodeExample
Note:
firstName, hash and one of email or phoneNumber are mandatory
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 |
Step 2 - Configurations
1) Update User
User attributes can be updated by calling, below is the sample configuration example -
const updateUserSettingsJavascript = (payload) => { const userPayload = JSON.stringify({ user: payload }); return `window.sprChat('updateUserSettings', ${userPayload});`; }; const payload = { |
Note: firstName, hash and either of email or phone number are mandatory parameters and hash should be generated for every change in user object.
2) Update Custom User
Custom User attributes can be updated by calling, below is the sample configuration example:
const updateCustomUserJavascript = (payload) => { const userPayload = JSON.stringify({ customUser: payload }); return `window.sprChat('updateUserSettings', ${userPayload});`; }; const updateUserSettings = () => { const payload = { tokenA: tokenA, tokenB: tokenB, hash: hash }; const javascriptCode = updateCustomUserJavascript(payload); this.webviewRef?.webviewRef?.injectJavaScript?.(javascriptCode); }; |
3) Update language
To update the user language use below function:
const updateLocaleJavascript = (locale) => `(function() { window.sprChat('updatelocale', '${locale}'); })();`; const updateLocale = () => { this.webviewRef?.injectJavaScript?.(updateLocaleJavascript('hr')); } |
Sprinklr messenger 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) Localization support
To achieve localization in live chat via webview approach, you can pass certain “locale” string in query parameters of URL; this will be in addition to ones discussed in Step 1
URL -
https://prod-live-chat.sprinklr.com/page?appId=60c1d169c96beb5bf5a326f3_app_950954&device=MOBILE&enableClose=true&zoom=false& locale=en
In the above URL,
locale = en → It indicates the locale which you want to send for this app ID
5) Opening live chat with different landing screen
To open live chat in different states at different locations, you can use pass the relevant string in the query parameters of URL; this will be in addition to ones discussed in Step 1
Scenario 1: Directly landing on the home screen
URL - https://prod-live-chat.sprinklr.com/page?appId=60c1d169c96beb5bf5a326f3_app_950954&device=MOBILE&enableClose=true&zoom=false&locale=en
By Default we open Home screen.
Scenario 2: Directly landing on the new conversation screen
URL - https://prod-live-chat.sprinklr.com/page?appId=60c1d169c96beb5bf5a326f3_app_950954&device=MOBILE&enableClose=true&zoom=false&landingScreen=NEW_CONVERSATION&scope=CONVERSATION
In the above URL,
scope = CONVERSATION → It indicates the the scope of live chat is limited to conversation screen
landingScreen = NEW_CONVERSATION → It indicates the landing screen i.e. new conversation is opened
Scenario 3: Directly landing on the last conversation screen
URL - https://prod-live-chat.sprinklr.com/page?appId=60c1d169c96beb5bf5a326f3_app_950954&device=MOBILE&enableClose=true&zoom=false&landingScreen=LAST_CONVERSATION&scope=CONVERSATION
In the above URL,
scope = CONVERSATION → It indicates the the scope of live chat is limited to conversation screen
landingScreen = LAST_CONVERSATION → It indicates the landing screen i.e. last conversation is opened
Note: landingScreen: "LAST_CONVERSATION allows brands to get users to land the customer on the last interacted open conversation. If there are no open conversations, the customer lands on a new conversation window |
6) Passing contextual information of users to live chat from mobile
Scenario 1: Capture customer context from the mobile app on all cases of the user
Sometimes you might want to pass some contextual information in case custom fields for all conversations started by the user. (clientContext)
URL - https://prod-live-chat.sprinklr.com/page?appId=60c1d169c96beb5bf5a326f3_app_950954&device=MOBILE&enableClose=true&zoom=false&landingScreen=LAST_CONVERSATION&scope=CONVERSATION&context_fieldId=value
In the above URL,
context_fieldId = “pass required value” → It indicates the context which is passed to all cases of user
Scenario 2: Update the profile context from mobile app on profile of user
Sometimes you might want to capture some context on the profile/user during the conversation or after the conversation. (userContext)
URL - https://prod-live-chat.sprinklr.com/page?appId=60c1d169c96beb5bf5a326f3_app_950954&device=MOBILE&enableClose=true&zoom=false&landingScreen=LAST_CONVERSATION&scope=CONVERSATION&userContext_fieldId=value
In the above URL,
userContext_fieldId = “pass required value” → It indicates the context which is passed to profile of user
7) 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,
Create the case custom fields and note down their field name1.
Whenever you want to update the case custom field, call the following JavaScript function (5e291d040844e435b is the custom field name).
const updateConversationContextJavascript = () => { const payload = JSON.stringify({ context: { "5e291d040844e435b": ["450.32"] } }); return `(function() { window.sprChat('updateConversationContext', ${payload}); })();`;}; const updateConversationContext = () => { |
8) 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,
Create the profile custom fields and note down their field name.
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.
const updateUserContextJavascript = () => { const payload = JSON.stringify({ "_c_5e291d040844e435b": ["450.32"] }); return `(function() { window.sprChat('updateUserContext', ${payload}); })();`;}; const updateUserContext = () => { this.webviewRef?.injectJavaScript?.(updateUserContextJavascript()); } |
9) Blocking URLs which does not contain live chat URL domain to open it in the external browser
Add Webview client to your webview and override shouldOverrideUrlLoading to block all URL which do not contain live chat url domain, inside onCreate method.
const originWhiteList = ['https://prod-live-chat.sprinklr.com', 'https://live-chat-static.sprinklr.com']; |
10) Listening to webview events
onMessage = event => case 'onLoad': { |
Adding javascript channels to your webview
Injecting Javascript
const jsChannels = `(function () { window.ReactNativeWebView.postMessage(JSON.stringify({type: 'onLoad'})); } |
11) 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 webview URL
12) Update Theme Mode for User on demand
You can update the theme mode ondemand:
const updateThemeModeJavascript = (mode) => `(function() { window.sprChat('updateThemeMode', '${mode}'); })();`; const updateThemeMode = () => { this.webviewRef?.injectJavaScript?.(updateThemeModeJavascript('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
13) 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:
const updateWidgetJavascript = (payload) => { const stringifiedPayload = JSON.stringify(payload); return `(function() { window.sprChat('updateWidget', ${stringifiedPayload}); })();`;}; const 'updateWidget' = () => { const payload = { id: 'status_card_1', details: { title: 'Status: %%[status]', description: 'Updated At %%[updatedAt]', status: 'SERVICE_UNDER_MAINTENANCE', updatedAt: 1668161693545, langVsTranslatedFieldValues: { 'ar': { title: '%%[status] : حالة ', description: ' %%[updatedAt] : تم التحديث في' }, 'es': { title: 'Estado : %%[status]', description: 'Actualizado en: %%[updatedAt]' }} } }; this.webviewRef?.injectJavaScript?.(updateWidgetJavascript(payload)); } |
You can use the following placeholders for title and description:
%%[updatedAt] --> Placeholder for formatted time
%%[status] --> Placeholder for Status, mentioned below in the table as SPRStatus
14) Add support to download attachment
Whenever user clicks on the download button, we will redirect to a URL which contains fileUrl and fileName which looks like this ->
“livechat-app:url=${fileUrl}?fileName=${fileName}” [when there are no query parameters present in the fileUrl, fileName is added as a new query parameter]
OR“livechat-app:url=${fileUrl}&fileName=${fileName}” [when there are query parameters present in the fileUrl already, fileName is added as an extra query parameter]
You need to intercept the requests that have URLs starting with the “livechat-app:” prefix and parse these URLs to properly download the attachment. The steps to parse are:
Strip the “livechat-app:url=” prefix.
From the remaining URL, extract and remove the “fileName” query parameter. Use its value to name your file.
Using the remaining URL to fetch and download content.
Please note: While extracting the file URL we need to strip the fileName query Param from the original query because if we do not remove the fileName query parameter then it will lead to signature mismatch and will throw SignatureDoesNotMatch error or BlobNotFound error.
For Example, when receiving a URL like “livechat-app:url= https://prod-sprcdn-assets.sprinklr.com/1234/sample.pdf?signature=XYZ&fileName=sample_name.pdf”, follow the above steps i.e.
Strip the prefix to get “https://prod-sprcdn-assets.sprinklr.com/1234/sample.pdf?signature=XYZ& fileName=sample_name.pdf”
Extract fileName query param and name the file sample_name.pdf.
Use the remaining URL “https://prod-sprcdn-assets.sprinklr.com/1234/sample.pdf?signature=XYZ” to download file.
Step 3 - Push Notifications
For more details on mobile push notifications, please refer here
Prerequisite
Android: FCM Servey Key
iOS: APNS certificate (P12) along with its credentials
Note:
FCM Server key 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 FCM server key is different sandbox/prod env and you are testing the push notification setup on prod mobile application(Android), plesae ensure to use Android release build.
Configuration
To enable push notifications, please raise a support ticket to tickets@sprinklr.com with the following information:
FCM Server Key (copy it from your Firebase Console)
APNS certificate (P12) along with its credentials
Live Chat AppID
Partner ID
Env
1) Register for push notifications
You can register the messenger for sending push notifications by providing push token received from fcm as below:
Create a function in the following way and pass token, deviceId and deviceName as arguments to it to register your device for push notification.
function getTokenRegistrationJSChannel(token, deviceId, deviceName) { |
registerPushNotifications = () => { |
2) Unregister for push notifications
If you ever want to stop receiving notifications, then you can deregister your device in the following way:
function getTokenUnRegistrationJSChannel(token, deviceId, deviceName) { |
unRegisterPushNotifications = () => { |
3) 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:
Note: When the user is on the Live Chat app, they will always receive the Live Chat messenger push notifications. However, you can define whether users should receive the messenger notifications when they are on the brand app and not the Live Chat app. That is, the brand app is in the foreground and the Live Chat app is running in the background.
To do that, you can check whether the notification is a Live Chat notification and handle it according to brand requirements. For example, you can choose not to display Live Chat notifications when the user is on the brand app.
const et = notification?.et ?? ''; |
Once you have identified if the notification is messenger notification you need open the messenger and call handle notification method as described below:
handleNotification = notification => { |
Troubleshooting
Issue 1: Sprinklr webview URL is not working
Check network connections establishing or not; to verify this you can simply try to open google.com in your webview
Check whitelisng is done properly in live chat builder in Sprinklr platform
Steps: Sprinklr Service → Live Chat Care → “ three dots” next to your Live chat Application → Edit → Application Configuration Screen
Check example URL are loading like https://prod0-live-chat.sprinklr.com/page?appId=app_1000073145
Issue 2: 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.
Issue 3: Reply box is not showing with keypad
Check and add one configuration in AndroidManifest.xml android:windowSoftInputMode="adjustResize"
Refer here for more details: https://developer.android.com/develop/ui/views/touch-and-input/keyboard-input/visibility#Respond