iOS

Updated 

Step 1 - Getting Started

1.) Creating Live Chat controller, adding live chat URL and injecting javascript to listen to webview events

Important - http://prod-live-chat.sprinklr.com/page?appId=65afb12b62317d2d4a58bfad_app_1866548&device=MOBILE&enableClose=true&zoom&skin=MODERN&webview=true


In the above URL, 

appId=60c1d169c96beb5bf5a326f3_app_950954 →  It indicates the live chat application ID; please ask Sprinlr 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.

skin = MODERN →  It indicates modern theme of live chat widow 

webview = true →  It indicates sprinklr code that implemetation is webview and based on this flag we can handle the webview specific things seperately i.e. To support downloading of the attachement.

Please check with success team on the environment you are part of, it can be prod, prod2, prod4 etc. and use the URL accordingly.


NOTE → Example Projects can be viewed here


let liveChatUrl = "http://prod-live-chat.sprinklr.com/page?appId=60c1d169c96beb5bf5a326f3_app_950954&device=MOBILE&enableClose=true&zoom=false"; // example url, use one provided by sprinklr


let jsString = """
        (function() {
            window.sprChat('onLoad', (error) => {
              if(!error) {
                  window.webkit.messageHandlers.onLoadError && window.webkit.messageHandlers.onLoadError.postMessage("");
              }
            });

            window.sprChat('onClose', () => {
                window.webkit.messageHandlers.Close && window.webkit.messageHandlers.Close.postMessage("");
            });

            window.sprChat('onUnreadCountChange', (count) => {
                window.webkit.messageHandlers.OnUnreadCountChange && window.webkit.messageHandlers.OnUnreadCountChange.postMessage(count);
            });

            window.sprChat('onExternalEvent', (event) => {
                window.webkit.messageHandlers.OnExternalEventReceived && window.webkit.messageHandlers.OnExternalEventReceived.postMessage(event);
            });
        })();
    """ //js to inject inside webview to listen to close, webview load, notification count events and handle external events

  

override func viewDidLoad() {
        super.viewDidLoad()
       
        // defining delegate method names for js events
        let contentController = WKUserContentController()
        contentController.add(self, name: "Close")
        contentController.add(self, name: "onLoadError")
        contentController.add(self, name: "OnUnreadCountChange")

        contentController.add(self, name: "OnExternalEventReceived")
       
        let jsScript = WKUserScript(source: jsString, injectionTime: .atDocumentEnd, forMainFrameOnly: false)
        contentController.addUserScript(jsScript) // inject js inside webview

        let webConfiguration = WKWebViewConfiguration()
        webConfiguration.userContentController = contentController;
        webConfiguration.websiteDataStore = WKWebsiteDataStore.default();

 

        // this is required to allow video streaming through webview

        webConfiguration.allowsInlineMediaPlayback = true;
       
        let preferences = WKPreferences()
        preferences.javaScriptEnabled = true;

        webConfiguration.preferences = preferences

        let screenSize = UIScreen.main.bounds
        let screenWidth = screenSize.width
        let screenHeight = screenSize.height
       
        webView = WKWebView(frame: CGRect(x: 0, y: 0, width: screenWidth, height: screenHeight), configuration: webConfiguration) // Setting webview frame to use full device dimensions
        webView.uiDelegate = self
        webView.navigationDelegate = self

        let url = URL(string: liveChatUrl)!
        let urlRequest = URLRequest(url: url)

        webView.load(urlRequest) //Adding live chat url to webview
        view.addSubview(webView)
    }
    

func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {// edit: changed fun to func
        print(message.name)
        if ((message.name == "Close")){
            dismiss(animated: true) // Close view controller
        }
       
        if(message.name == "onLoadError") {
            // You can show some ui error
        }
       
        if(message.name == "OnUnreadCountChange") {
            // You can show the notification count using this, message.body will give count to you
        }
       
        if(message.name == "OnExternalEventReceived") {
            // Handle external event here
        }
    }

 


2.) Add these permissions if you want to support uploading and downloading of media


Include the following permissions in info plist file:

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

 


3.) 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 -

http://prod-live-chat.sprinklr.com/page?appId=65afb12b62317d2d4a58bfad_app_1866548&device=MOBILE&enableClose=true&zoom

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

http://prod-live-chat.sprinklr.com/page?appId=65afb12b62317d2d4a58bfad_app_1866548&device=MOBILE&enableClose=true&zoom&user_id=12345&user_firstName=John&user_lastName=Doe&user_profileImageUrl=https://example.com/profilePic.jpg&user_email=John.Doe@example.com&user_phoneNo=9876543210&user_hash=29862e418f58273af0f7fcd0f24652e11ec1ff6c2213b2db7f6e754e59778fc3


In the above URL,

  • 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. scenario 3

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";

$userId = "12345";
$firstName = "John";
$lastName = "Doe";
$profileImageUrl = "https://example.com/profilePic.jpg";
$phoneNo = "9876543210";
$email = "John.Doe@example.com";

$userDetails = $userId."_".$firstName."_".$lastName."_".$profileImageUrl."_".$phoneNo."_".$email;

$userHash = hash_hmac('sha256',$userDetails,$key);

Run the above PHP code online - https://repl.it/@AbhishekPriyam/HMACPHPExample

Python 2.7/3.6.1

import hmac
import hashlib

userId = "12345"
firstName = "John"
lastName = "Doe"
profileImageUrl = "https://example.com/profilePic.jpg"
phoneNo = "9876543210"
email = "John.Doe@example.com"

userDetails = userId+"_"+firstName+"_"+lastName+"_"+profileImageUrl+"_"+phoneNo+"_"+email

def create_sha256_signature(key, data):
  byte_key = key.encode()
  data= data.encode()
  return hmac.new(byte_key, data, hashlib.sha256).hexdigest()

userHash=create_sha256_signature("acf32e61-14a6-291b-3a1b-cc8854134ea1", userDetails)

Run the above Python code online - https://repl.it/@AbhishekPriyam/HMACPythonExample

Ruby (Rails)

require 'openssl'

key = 'acf32e61-14a6-291b-3a1b-cc8854134ea1'
userId = "12345"
firstName = "John"
lastName = "Doe"
profileImageUrl = "https://example.com/profilePic.jpg"
phoneNo = "9876543210"
email = "John.Doe@example.com"

userDetails = userId+"_"+firstName+"_"+lastName+"_"+profileImageUrl+"_"+phoneNo+"_"+email

digest = OpenSSL::Digest.new('sha256')

userHash = OpenSSL::HMAC.hexdigest(digest, key, userDetails)

Run the above Ruby code online - https://repl.it/@AbhishekPriyam/HMACRubyExample

Java

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.security.NoSuchAlgorithmException;
import java.security.InvalidKeyException;
import javax.xml.bind.DatatypeConverter;

class Main {
public static void main(String[] args) {
try {
      String key = "acf32e61-14a6-291b-3a1b-cc8854134ea1";
      String message = "12345_John_Doe_https://example.com/profilePic.jpg_9876543210_John.Doe@example.com";

      Mac hasher = Mac.getInstance("HmacSHA256");
      hasher.init(new SecretKeySpec(key.getBytes(), "HmacSHA256"));
      byte[] hash = hasher.doFinal(message.getBytes());
 
      System.out.println((DatatypeConverter.printHexBinary(hash)).toLowerCase());
  }
  catch (NoSuchAlgorithmException e) {}
  catch (InvalidKeyException e) {}
}
}

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');

var key = 'acf32e61-14a6-291b-3a1b-cc8854134ea1';
var userDetails = '12345_John_Doe_https://example.com/profilePic.jpg_9876543210_John.Doe@example.com';

var hash = crypto.createHmac('sha256', key).update(userDetails);

hash.digest('hex');

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.) 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 - http://prod-live-chat.sprinklr.com/page?appId=65afb12b62317d2d4a58bfad_app_1866548&device=MOBILE&enableClose=true&zoom&locale=en

In the above URL,
locale = en It indicates the locale which you want to send for this app ID 


2.) 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 - http://prod-live-chat.sprinklr.com/page?appId=65afb12b62317d2d4a58bfad_app_1866548&device=MOBILE&enableClose=true&zoom&locale=en


Scenario 2: Directly landing on the new conversation screen

URL -

http://prod-live-chat.sprinklr.com/page?appId=65afb12b62317d2d4a58bfad_app_1866548&device=MOBILE&enableClose=true&zoom&locale=en&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 -

http://prod-live-chat.sprinklr.com/page?appId=65afb12b62317d2d4a58bfad_app_1866548&device=MOBILE&enableClose=true&zoom&locale=en&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


3.) 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 -

http://prod-live-chat.sprinklr.com/page?appId=65afb12b62317d2d4a58bfad_app_1866548&device=MOBILE&enableClose=true&zoom&locale=en&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 -

http://prod-live-chat.sprinklr.com/page?appId=65afb12b62317d2d4a58bfad_app_1866548&device=MOBILE&enableClose=true&zoom&locale=en&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

4.) Blocking URLs which does not contain live chat URL domain to open it in the external browser

  let domainsToWhiteList = ["prod-live-chat.sprinklr.com", "live-chat-static.sprinklr.com"] // urls to whitelist

func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
       
        let url = navigationAction.request.url
        let host = url?.host
        var isWhitelistUrl = false;
        for domain in domainsToWhiteList {
            if((host?.hasPrefix(domain)) ==true) {
                isWhitelistUrl = true
            }
        }
       
        if let url = navigationAction.request.url,
            !isWhitelistUrl,
            UIApplication.shared.canOpenURL(url) {
            UIApplication.shared.open(url)
            print(url)
            print("Redirected to browser. No need to open it locally")
            decisionHandler(.cancel)
        } else {
            print("Open it locally")
            decisionHandler(.allow)
        }
    }

5.) 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 ->  

  1. “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 

  2. “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: 

  1. Strip the “livechat-app:url=” prefix. 

  2. From the remaining URL, extract and remove the “fileName” query parameter. Use its value to name your file. 

  3. 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.  

  1. Strip the prefix to get “https://prod-sprcdn-assets.sprinklr.com/1234/sample.pdf?signature=XYZ& fileName=sample_name.pdf”  

  2. Extract fileName query param and name the file sample_name.pdf. 

  3. Use the remaining URL “https://prod-sprcdn-assets.sprinklr.com/1234/sample.pdf?signature=XYZ” to download file. 

func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {  

    let url = navigationAction.request.url; 

    var urlString = url?.absoluteString;         

     

    if(urlString == nil){ 

        urlString=""; 

    }  

    if (urlString != nil && urlString!.starts(with: "livechat-app:")) { 
let strippedUrl = urlString.replacingOccurrences(of: "livechat-app:url=", with: "") 

  

        if var urlComponents = URLComponents(string: strippedUrl) { 

            var fileName: String? 

            if let queryItems = urlComponents.queryItems { 

                for queryItem in queryItems { 

                    if queryItem.name == "fileName" { 

                        fileName = queryItem.value 

                        break 

                    } 

                } 

            } 

  

            urlComponents.queryItems = urlComponents.queryItems?.filter { $0.name != "fileName"} 

  

            let cdnUrl = urlComponents.url?.absoluteString ?? "" 

  

        // put your download logic here 

        }  
        return; 

    }  

    decisionHandler(.allow); 

Step 3 - Push Notifications

For more details on mobile push notifications, please refer here

Prerequisite

  1. Android: FCM Servey Key

  2. 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:

  1. FCM Server Key (copy it from your Firebase Console)

  2. APNS certificate (P12) along with its credentials

  3. Live Chat AppID

  4. Partner ID

  5. Env

1) Register for push notifications 


You can register the messenger for sending push notifications by providing push token received from apns/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.


    func asString(jsonDictionary: AnyObject) -> String {
      do {
        let data = try JSONSerialization.data(withJSONObject: jsonDictionary, options: .prettyPrinted)
        return String(data: data, encoding: String.Encoding.utf8) ?? ""
      } catch {
        return ""
      }
    }

   
    @objc func onRegister(sender : UIButton){
        let clientContext = ["mobileClientType": "IPHONE", "appVersion": "1", "deviceId": "123", "deviceName": "IPHONE_DEVICE", "deviceToken": "8A72039D97781CBC69263C833D9C7DA2BC09A14FEA35444A25CAC29CB127408D"] as AnyObject
       
       
        let stringifiedJson = asString(jsonDictionary: clientContext);
       
        let jsonString = "(function() {"+"window.sprChat('registerDevice'," + stringifiedJson + ");})();"
       
        webView.evaluateJavaScript(jsonString);
    }

2) Unregister for push notifications 

If you ever want to stop receiving notifications, then you can deregister your device in the following way:



    func asString(jsonDictionary: AnyObject) -> String {
      do {
        let data = try JSONSerialization.data(withJSONObject: jsonDictionary, options: .prettyPrinted)
        return String(data: data, encoding: String.Encoding.utf8) ?? ""
      } catch {
        return ""
      }
    }

   
    @objc func onUnregister(sender : UIButton){
        let clientContext = ["mobileClientType": "IPHONE", "appVersion": "1", "deviceId": "123", "deviceName": "IPHONE_DEVICE"] as AnyObject
       
       
        let stringifiedJson = asString(jsonDictionary: clientContext);
       
        let jsonString = "(function() {"+"window.sprChat('unregisterDevice'," + stringifiedJson + ");})();"
       
        webView.evaluateJavaScript(jsonString);
    }

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:


    let et = userInfo["et"] as? String
    let isMessengerNotification = et == "LIVE_CHAT_MOBILE_NOTIFICATION";
   
    if (isMessengerNotification) {
        handleNotification(userInfo: userInfo);
    }

Once you have identified if the notification is messenger notification you need open the messenger and call handle notification method as described below:

    @objc func handleNotification(userInfo : NSDictionary){
        let stringifiedJson = asString(jsonDictionary: userInfo);
       
        let jsonString = "(function() {"+"window.sprChat('onNotification'," + stringifiedJson + ");})();"
       
        webView.evaluateJavaScript(jsonString);
    }



Troubleshooting

Issue 1: Sprinklr webview URL is not working

  1. Check network connections establishing or not; to verify this you can simply try to open google.com in your webview

  2. Check whitelisng is done properly inn live chat builder in Sprinklr platform.

    Steps: Sprinklr Service → Live Chat Care → “ three dots” next to your Live chat Application → Edit → Application Configuration Screen

  3. 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: Attachment icon not working

  1. Please check is user is having permission like camera and photo

    Please check step 1.3