Giter VIP home page Giter VIP logo

cordovamessagingsdksample's Introduction

Cordova LivePerson Messaging Plugin

Examples of how to interact with the LivePerson Messaging SDK

Versioning

Current Version: v2.9

Running with the following versions of the LivePerson Messaging SDK

Untested Features

The following new SDK features have not been tested for Cordova plugin compatibility.

  • Secure Form

General Limitations / Unsupported Features

  • Fragment mode on Android
  • ViewController mode on iOS

In both of the above cases these might be solvable with more iOS/Android expertise but this has not been achieved yet with the current plugin.

Attempt to integrate the SDK in these modes at your own risk

  • Branding

Customisations of both SDKs in terms of look and feel can still be achieved through editing the related native class files on iOS/Android - but support for such config changes via a web layer across platforms is NOT in scope/available

  • Callbacks / Event Limitations

Whilst we support and expose a number of delegate callbacks and events to the web layer (see API reference section below), these are not 1:1 parity across both platforms due to differences in the SDK and platforms they run on. Please check the documentation below to understand which events apply to each platform.

Requiring additional brand specific events will require you to modify the code and classes as you see fit.

PLEASE NOTE -- XCODE UPGRADE REQUIRED!!

  • iOS SDK v2.9.x requires XCODE v9.1 and above to use Swift 4.0
    • You will need macOS Sierra in order to install this.

Installing / Getting started

"Where do I find the latest version of the plugin?"

Repo has been restructured. The plugin is now here:

/plugins/MessagingSDKPlugin

If you need to reinstall the plugin to your app, make sure you pull it from this folder.

e.g if you were working in the sampleapp01 example folder

cd apps/sampleapp01
cordova plugin remove com.liveperson.messagingSDK
cordova plugin add ../../plugins/MessagingSDKPlugin

iOS

Prerequisites

To use the LivePerson In-App Messaging SDK, the following are required:

  • XCode 9.1 or later
  • Swift 4.0 or later, or Objective-C

For latest information please refer to LivePerson Developers Site

The SDK is also compatible with CocoaPods, a dependency manager for Swift and Objective-C Cocoa projects. CocoaPods has thousands of libraries and is used in over 2 million apps. It can help you scale your projects elegantly and provides a standard format for managing external libraries.

  1. Install cocoapods using the following command:
$ gem install cocoapods
  1. Navigate to your project folder and init new pod using the following command:
$ pod init
  1. Podfile should be created under your project’s folder.

To integrate Liveperson Messaging SDK into your Xcode project using CocoaPods, specify it in your Podfile:

https://developers.liveperson.com/consumer-experience-ios-sdk-sampleapp.html#add-lpmessagingsdk-to-your-podfile

# Uncomment the next line to define a global platform for your project
# platform :ios, '9.0'

source 'https://github.com/CocoaPods/Specs.git'
source 'https://github.com/LivePersonInc/iOSPodSpecs.git'

target '<YourApplicatioName>' do
  # Comment the next line if you're not using Swift and don't want to use dynamic frameworks
  use_frameworks!

  # Pods for <YourApplicatioName>
  pod 'LPMessagingSDK','~>2.8.0.9'

  target '<YourApplicatioName>Tests' do
    inherit! :search_paths
    # Pods for testing
  end

  target '<YourApplicatioName>UITests' do
    inherit! :search_paths
    # Pods for testing
  end
end
  1. Run the following command in the terminal under your project folder:
$ pod install
  1. Incase you wish to upgrade to the latest SDK version and you have already ran 'pod install', Run the following command:
$ pod update

SDK 2.5

Xcode 8:

SDK 2.7

Xcode 8:

Xcode 9:

SDK 2.8

Xcode 9 only:

Installation of iOS Libraries by Copying to Xcode Project

Copy all framework and bundle files into the project, including the bundle file In project settings, navigate to the General tab, and add all Framework files to the Embedded Binaries section.

Installation notes

In project settings, navigate to the Build Phases tab, and click the + button to add a New Run Script Phase. Add the script below in order to loop through the frameworks embedded in the application and remove unused architectures (used for simulator). This step is a workaround for known iOS issue http://www.openradar.me/radar?id=6409498411401216 and is necessary for archiving your app before publishing it to the App Store.

If frameworks installed using CocoaPods, use the following script:

bash "${SRCROOT}/Pods/LPMessagingSDK/LPMessagingSDK/LPInfra.framework/frameworks-strip.sh"

If frameworks installed using copy to Xcode project, use the following script:

bash "${BUILT_PRODUCTS_DIR}/${FRAMEWORKS_FOLDER_PATH}/LPInfra.framework/frameworks-strip.sh"

Manual Framework installation Notes

Follow the usual steps for adding the embedded binary .frameworks and .bundle files into the iOS app via Xcode. Check the Video Link for examples of how this can be done.

  • Add SDK plugin with latest version
---- DO NOT RUN cordova build ios on CLI until you have been into XCODE! ---
  • Open project workspace in XCODE

    • accept all recommend project settings
    • select project
    • add embedded binaries for the SDK and frameworks
    • CLEAN PROJECT!
    • BUILD PROJET! == should pass & you will warnings about missing cordova libs as we have not "built in cordova" yet!
  • go back to CLI

  • run cordova build ios command which should now succeed

  • run in xcode or CLI

if you get a build/run error about missing simulators, then edit this file -- <your app folder>/platforms/ios/cordova/lib/start-emulator and change the default iOS emulator to run or add iPhone 5s to your list of emulated devices


Android

The plugin itself does NOT include any copies of the Android SDK aars libraries. You should download the latest version of the Android SDK from here on github.

https://developers.liveperson.com/android-quickstart.html

BUT ALWAYS CHECK GITHUB RELEASES LINK ABOVE FOR THE LATEST VERSION


Sample Apps Included

Within the apps/ folder at the root of this repo you will find some sample apps demoing the plugin. Here is a breakdown.

apps/sampleapp01 -- iOS Only

Has been created as reference app using iOS frameworks.

This app does NOT include an Android application - refer to SampleApp03 for the latest Android example app.

Includes a basic iOS Cordova App with Messaging integration and the PhoneGap Push plugin installed - but not with Simulator as restrictions prevent this...you will need to run on physical device.

screen shot 2017-04-20 at 22 50 14

apps/sampleapp03 -- Android -- Authentication and Push Plugin

  • includes authentication for both platforms
  • phone gap push plugin RC 2.0 for Android and iOS
    • working on Android

Api Reference

filename: plugins/MessagingSDKPlugin/www/LPMessagingSDK.js

This is where we expose the different function names within the wrapper to call the native code for starting, configuring a messaging conversation. In the current version there is just one function exposed which takes in an "action" arg for telling the native code what to do. You must also supply a successCallback js func / errorCallback js func / account id (clone or prod) + any arguments needed by the function.

API Function definition

lp_conversation_api: function(action, args, successCallback, errorCallback)

Supported values for action :


*************************** NEW IN v2.9.x *************************************

"close_conversation_screen"

sample call:

lpMessagingSDK.lp_conversation_api(
  'close_conversation_screen', [accountNumber],
  function (data) {
    var eventData = JSON.parse(data);
    console.log('@@@ js ... unique close_conversation_screen SDK callback');
  },
  function (data) {
    var eventData = JSON.parse(data);
    console.log('@@@ js ... unique close_conversation_screen SDK error callback');
  }
);

can be triggered if the callbacks you bind to trigger an error response and you want to close the conversation screen as a result and provide the user with instructions within the web layer.


"lp_sdk_init"

Must be called before trying to use any other methods. Requires the account number to be passed within args parameter

sample call...

var success = function(message) {
    console.log("OnEvent JS: " + message);
}

var failure = function() {
    console.log("Error calling lp_conversation_api Plugin");
}

lpMessagingSDK.lp_conversation_api("lp_sdk_init", ["123456"], success, failure);

"register_pusher"

Used to register device tokens with the SDK for handling push notifications

  • api method : lpMessagingSDK.lp_conversation_api

  • action : 'register_pusher'

  • args : [accountId,deviceToken]

    • deviceToken should be obtained by your app using relevant cordova plugin
  • Reccomend this method is called within the success callback of lp_sdk_init to ensure SDK is ready to receive the token.

lpMessagingSDK.lp_conversation_api(
    "lp_sdk_init", [this.settings.accountId, sdkConfig],
    function(data) {
        var eventData = JSON.parse(data);
        console.log("@@@ js ... unique lp_sdk_init SDK callback");
        lpMessagingSDK.lp_conversation_api(
            "register_pusher", [app.settings.accountId,app.deviceToken],
            function(data) {
                //var eventData = JSON.parse(data);
                console.log("@@@ js ... unique register_pusher SDK callback .."+data);
            },
            function(data) {
                // var eventData = JSON.parse(data);
                console.log("@@@ js ... unique register_pusher SDK error callback ..."+data);
            }
        );
    },
    function(data) {
        var eventData = JSON.parse(data);
        console.log("@@@ js ... unique lp_sdk_init SDK error callback");
    }
);

"start_lp_conversation"

Used to open the Messaging conversation window and connect to LivePerson.

Includes support for authentication JWT token for implicit flow

var authenticationCode = "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIrOTcyLTMtNTU1NS01NTUiLCJpc3MiOiJodHRwczovL2lkcC5saXZlcGVyc29uLm5ldCIsImF1ZCI6ImFjYzpxYTU3MjIxNjc2IiwiZXhwIjoxNTM0OTcxOTMwLCJpYXQiOjE0NzE4OTk5NDIsIm5hbWUiOiJFaXRhbiJ9.Fh0sG-iu-VMZRFRbUNK0kEzb7Y1BXtQHOKaHL2y40y_c4mBvmQDCOYNWJ1ZEeayTNuLboYx6L8xEoC5xZIFnVv2N4a36BBU88fNuhe9Em2b5qNdVbdBtIJQoBY5ep5O2geAaCVA7A7oS8ysWVGn9CV4btH_D5sU2jGr3ml8yfJA"

lpMessagingSDK.lp_conversation_api(
    "start_lp_conversation", 
    [
        "123456",
        authenticationCode
    ],
    success,
    failure);

authenticationCode is optional arg parameter. If omitted then the conversation will be unauthenticated

"lp_clear_history_and_logout"

Used to clear the current user data and unregister the device from push notifications.

PLEASE NOTE: Impact on Push Notifications

Calling this method will mean the device is no longer going to receive push notifications until the next user logs back in and opens the conversation screen to send the latest JWT token to the SDK and establish a connection. After that point the device will receive push notifications again for that user when not viewing the conversation screen.

  • When the customer logs out of your app, call this method to clear the local device SDK history and unregister the device from push notifications.
  • Then once the next user logs in, remember to call lp_sdk_init before starting a new conversation for the next user when you supply the updated and relevant JWT token
  • see example below for doing this in the callback for logout ready for the next user.
  • You must supply the account id for your LivePerson account number into this method
lpMessagingSDK.lp_conversation_api(
    "lp_clear_history_and_logout", [this.settings.accountId],
    function(data) {
        var eventData = JSON.parse(data);
        console.log("@@@ js ... unique clearDeviceHistoryAndLogout SDK callback ...data => "+data);
        console.log("@@@ js ... post logout...now auto reinitialise the SDK for next user to save button press in demo!");
        app.lpMessagingSdkInit();

    },
    function(data) {
        var eventData = JSON.parse(data);
        console.log("@@@ js ... unique clearDeviceHistoryAndLogout SDK error callback ...data => "+data);
    }
);
  • callback event name : LPMessagingSDKClearHistoryAndLogout

"reconnect_with_new_token"

  • args : [token]
    • in that specific order!
    • accountId is required for iOS version of the function

within your javascript successCallback function, you must listen for the specific eventName that tells you the SDK has detected that the customer JWT has expired and must be refreshed.

  • Listen for the correct event in your successCallback method and call your relevant app function to get the new token
successCallback: function(data) {

    var eventData = JSON.parse(data);

    if (eventData.eventName == 'LPMessagingSDKTokenExpired') {
        console.log("authenticated token has expired...refreshing...");
        this.lpGenerateNewAuthenticationToken();
    }

},
  • generate your new token calling your IDP / JWT service via javascript
lpGenerateNewAuthenticationToken: function() {
    // code to generate new fresh JWT would go here...
    // this example uses a hard coded JWT which has the new expiry time.
    var jwt = "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJUQUxLVEFM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poC7CzaUrih8IycB2X4FuKuxL9mOg";

    // pass the 
    lpMessagingSDK.lp_conversation_api(
        "reconnect_with_new_token", [jwt,app.settings.accountId],
        this.successCallback,
        this.errorCallback
    );
    console.log('lpGenerateNewAuthenticationToken completed --> new jwt -->  ', jwt);
},
  • once you have the new token pass it back down into the native application using the following cordova API call
lpMessagingSDK.lp_conversation_api(
    "reconnect_with_new_token", 
    [jwt,app.settings.accountId],
    this.successCallback,
    this.errorCallback
);
  • The SDK will pass the token back to LivePerson using the reconnect method of the SDK to refresh the token and continue authenticated conversations.

"set_lp_user_profile"

Used to send unauthenticated customer information to the agent where authenticated equivalents are not being sent.

PLEASE NOTE : unclear which of these values are still being used on server side so subject to change/deprecation in subsequent versions.

args array parameter mapping:

(Android Deprecated in v2.5 - value will be ignored - send null if not applicable)

(iOS still supported in v2.5)

  • 5 : customer phone number : "555-444-12345"

(iOS Only)

  • 6 : uid : "UID123145"
  • 7 : employeeID : "employeeId123123123"

^ Both of the above seemingly not being read on server side for iOS so use with caution.

lpMessagingSDK.lp_conversation_api(
  'set_lp_user_profile', 
  [
    accountId,
    'John',
    'Doe',
    'NickName:JD',
    'https://s-media-cache-ak0.pinimg.com/564x/a2/c7/ee/a2c7ee8982de3bae503a730fe4562cf9.jpg',
    'tel:555-444-12345',
    'uid_5678',
    'employeeId_1234'
  ],
  function(data) {
    var eventData = JSON.parse(data);
    console.log('@@@ js ... unique set_lp_user_profile SDK callback');
  },
  function(data) {
    var eventData = JSON.parse(data);
    console.log('@@@ js ... unique set_lp_user_profile SDK error callback');
  }
);

Sending Secure Information via JWT tokens

If you wish to send secure, authenticated information about the customer to your agent, it should be encoded and encrypted within your JWT token

https://s3-eu-west-1.amazonaws.com/ce-sr/CA/security/Authenticated+Interactions+with+oAuth+2.0.pdf

For a list of supported engagement attributes within a JWT token payload, see the following example JWT:

{
  "sub": "MY_UNIQUE_CUSTOMER_IDENTIFIER_GOES_HERE",
  "iss": "https://www.talktalk.co.uk",
  "exp": 1514718671,
  "iat": 1487159337,
  "phone_number": "+1-10-344-3765333",
  "lp_sdes": [
    {
      "type": "ctmrinfo",
      "info": {
        "cstatus": "cancelled",
        "ctype": "vip",
        "customerId": "138766AC",
        "balance": -400.99,
        "socialId": "11256324780",
        "imei": "3543546543545688",
        "userName": "user000",
        "companySize": 500,
        "accountName": "bank corp",
        "role": "broker",
        "lastPaymentDate": {
          "day": 15,
          "month": 10,
          "year": 2014
        },
        "registrationDate": {
          "day": 23,
          "month": 5,
          "year": 2013
        }
      }
    },
    {
      "type": "personal",
      "personal": {
        "firstname": "AN",
        "lastname": "Other",
        "age": {
          "age": 34,
          "year": 1980,
          "month": 4,
          "day": 15
        },
        "contacts": [
          {
            "email": "[email protected]",
            "phone": "+1 212-788-8877"
          }
        ],
        "gender": "MALE"
      }
    }
  ]
}

HOWTO : Update iOS Frameworks in your existing app

This video shows step by step how to replace the existing iOS frameworks and bundles in your app when their is a new version / hotfix released and you do not want to have to remove and add the plugin back into the app again...

Video Link


Cordova Plugin Callback Names

The following callbacks are fired from the iOS / Android apps back up into the Cordova plugin for processing / actions in Javascript

Register your Global Async Callback Handler

API Function definition

lpMessagingSDK.lp_register_event_callback: function(args, successCallback, errorCallback)
  • register your global async callback handler for monitoring these events.
lpMessagingSDK.lp_register_event_callback(
    [accountId],
    this.globalAsyncEventsSuccessCallback,
    this.globalAsyncEventsErrorCallback
);

SuccessCallback Event Object

In your js successCallback function you will receive a data object that must be parsed from a string into JSON

var eventData = JSON.parse(data);

This object has an eventName property which matches the above callbacks we support.

eventData.eventName

There may be other additional data points depending on the callback and context.


iOS + Android Callbacks

Immediate responses

Certain events are now returning immediate responses by triggering the respective, unique success/error callbacks passed into certain API functions.

lpMessagingSDK.lp_conversation_api with the following actions will return success/failure ASAP.

  • action: start_lp_conversation | eventName: LPMessagingSDKStartConversation
    • based on the SDK API call not failing - does not mean the conversation screen has loaded without errors etc, just means we called the method successfully.
  • action: set_lp_user_profile | eventName: LPMessagingSDKSetUserProfile
    • called the API method and did/did not throw errors as a result.
  • action: lp_sdk_init | eventName: LPMessagingSDKInit
    • SDK has initialised successfully based on calling the method and not throwing any errors.
  • action: lp_clear_history_and_logout | eventName: LPMessagingSDKClearHistoryAndLogout
    • SDK has cleared device history and unregistered push notifications for the device.
  • action: register_pusher | eventName: LPMessagingSDKRegisterLpPusher
    • successully registered the push token via the API call. Should only be called once lp_sdk_init has succeeded. Suggest triggering within the success callback of lp_sdk_init
    • Refer to register_pusher section for exact details, usage and implications

Triggering asynchronously

  • This will be the single handler for all the following async events
  • example function that JSON parses the data to get the eventData.eventName property listed below
globalAsyncEventsSuccessCallback: function(data) {
    var eventData = JSON.parse(data);
    console.log(
        '@@@ globalAsyncEventsSuccessCallback --> ' + data
    );
    if (eventData.eventName == 'LPMessagingSDKTokenExpired') {
        console.log("@@@ authenticated token has expired...refreshing...");
        app.lpGenerateNewAuthenticationToken();
    }
},

eventData.eventName values listed below. additional eventData properties are indented

  • "LPMessagingSDKCustomButtonTapped" (iOS Only)
  • "LPMessagingSDKAgentDetails"
    • agentName : String
  • "LPMessagingSDKActionsMenuToggled" (iOS Only)
    • toggled : true|false
  • "LPMessagingSDKHasConnectionError" (iOS Only)
    • error : String
  • "LPMessagingSDKCSATScoreSubmissionDidFinish"
  • "LPMessagingSDKAuthenticationFailed"
    • error : String
  • "LPMessagingSDKTokenExpired"
    • accountId : string
  • "LPMessagingSDKError"
    • error : String
  • "LPMessagingSDKAgentIsTypingStateChanged"
    • isTyping : true|false
  • "LPMessagingSDKConversationStarted"
    • conversationID : string
  • "LPMessagingSDKConversationEnded"
    • conversationID : string
  • "LPMessagingSDKConversationCSATDismissedOnSubmission"
    • conversationID : string
  • "LPMessagingSDKConnectionStateChanged"
    • isReady : true|false
  • "LPMessagingSDKOffHoursStateChanged"
    • isOffHours : true|false
  • "LPMessagingSDKConversationViewControllerDidDismiss" (iOS only)

Immediate response callback execution:

  • "LPMessagingSDKInit"
  • "LPMessagingSDKClearHistoryAndLogout"
  • "LPMessagingSDKSetUserProfile"
  • "LPMessagingSDKReconnectWithNewToken"
  • "token" : new jwt
  • "LPMessagingSDKRegisterLpPusher"
  • "deviceToken" : device token supplied
  • "LPMessagingSDKStartConversation"
    • "type" : "authenticated" | "unauthenticated"

Triggering asynchronously -- register your global async callback handler for monitoring these events.

  • "LPMessagingSDKObseleteVersion" (iOS Only)
  • "LPMessagingSDKCsatDismissed" (Android Only)

!!! Not currently implemented/applicable in callbacks!!!

  • "LPMessagingSDKAgentAvatarTapped"
  • "LPMessagingSDKCSATCustomTitleView"

Refer to native documentation and if you are missing a specific callback pleae let us know!

cordovamessagingsdksample's People

Contributors

dudumrk1 avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.