SDK for connecting to LiveChat as a customer
npm install @livechat/customer-sdkLiveChat Customer SDK is a set of tools that helps you build a custom chat widget. Under the hood, it makes use of the LiveChat Customer Chat API. Customer SDK lets you communicate with LiveChat services directly from the browser environment using JavaScript without the need to develop your backend.
If you need to customize the LiveChat Widget, using LiveChat Customer SDK is
one of the options to do this. If you need a fully customizable solution and you feel
brave, dive into LiveChat Customer SDK. We provide methods and
events for deep integration with the LiveChat environment.
Keep in mind that interacting with this API requires some development skills.
Customer SDK allows you to create frontend apps, so if you're looking for server-side solutions, you should explore the LiveChat Customer Chat API instead.
If you want to dive deeper into the LiveChat Platform, you might find the Platform Overview article handy.
We provide an asynchronous API. Most methods return a Promise. You can subscribe to the emitted events with the on and off methods.
Not familiar with promises? Read this article to learn more.
We authenticate your sessions with the use of
customer-auth package
and expose the created auth object to the returned SDK instance. In general,
you don't have to worry about it or use the exposed object. If you need to
get the authentication token, you can get it through the SDK like this:
``js`
customerSDK.auth.getToken().then(token => {
console.log(token)
})
If you have any questions, you can start a chat with our 24/7 Support.
This tutorial is here to help you get started with LiveChat Customer SDK.
First, you need to create an application in
Developer Console (select the _Web app (frontend,
e.g. JavaScript)_ type). Then, you will have to give it the access to the customers:own scope and the correct URI to the Redirect URI whitelist.
You can use the LiveChat Customer SDK in two different ways:
npm install --save @livechat/customer-sdk
Import the SDK in your code:
import * as CustomerSDK from '@livechat/customer-sdk'
Or use the node-style require call:
const CustomerSDK = require('@livechat/customer-sdk')
If you just want to look around and play with the SDK, check out our
sample chat widget implementation.
For the time being you need to register your application in the Developers Console
as a "Web app (frontend, eg. JavaScript)" type. Then, you have to pass the configured redirectUri to the init, along with the regular required properties (organizationId and clientId).
To use the API you will first need to create an instance using the init function.
You will need to provide your organizationId and clientId when creating a Customer SDK instance.
Other optional configuration parameters are also available:
| parameters | type | default | description |
| -------------------- | ------------------ | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| organizationId | string | | Your Organization ID, you receive this value when creating a new livechat account. |
| clientId | string | | Your client id, you receive this value when you register your application in the LiveChat Developer Console. |
| autoConnect | boolean | true | Optional; should the library try to reconnect on it's own. |
| groupId | number | 0 | Optional; the id of the group you wish to connect to. |
| uniqueGroups | boolean | false | Optional; by default, the customer's identity is the same for all groups. If you want to create a separate customer identity for each group, set this parameter to true. When set to true, passing a groupId is required. |updateCustomer()
| region | 'dal' \| 'fra' | 'dal' | Optional; the server region your license is at. |
| redirectUri | string | | Optional; should only be used inside ReactNative, this is the URI which your webview is redirected to after authorization. |
| customerDataProvider | () => CustomerData | | Optional; should only be used if you need to send customer data during login. In general, should be prefered for sending customer data. |
| identityProvider | () => CustomerAuth | | Optional; allows for providing own instance of the CustomerAuth object which contains the customer access token handlers. See Custom Identity Provider for more information. |
| page | object | | Optional; customer page information. |
| page.url | string | | Optional; customer page url. |
| page.title | string | | Optional; customer page title. |
| referrer | string | | Optional; page referrer |
CustomerData:
| parameters | type | description |
| ------------- | ------ | ---------------- |
| name | string | Optional |
| email | string | Optional |
| sessionFields | object | Key: value pairs |
CustomerAuth:
| parameters | type | description |
| ------------- | ---------------------- | -------------------------------------------------------------------------------------- |
| getFreshToken | () => Promise
| getToken | () => Promise
| hasToken | () => Promise
| invalidate | () => Promise
The init function will return a Customer SDK instance:
`js`
const customerSDK = CustomerSDK.init({
organizationId: ORGANIZATION_ID,
clientId: CLIENT_ID,
})
With customerSDK, you can attach events:
`js`
customerSDK.on('new_event', newEvent => {
console.log(newEvent)
})
Or execute methods:
`js`
const chatId = 'OU0V0P0OWT'
customerSDK
.sendEvent({
chatId,
event: {
type: 'message',
text: 'Hi!',
},
})
.then(response => {
console.log(response)
})
.catch(error => {
console.log(error)
})
If you want to use LiveChat Customer SDK in React Native, keep in mind that we
use cookies to authenticate your sessions, so we need some sort of browser
environment for that. We've prepared a special wrapper for you to use in React
Native. It opens a WebView component to get an authentication token. All you
have to do is import it from our authentication package (no need to install
it - the SDK depends on it, so you already have it) and mount it in your React
Native application:
`js
import { AuthWebView } from '@livechat/customer-auth'
import { init } from '@livechat/customer-sdk'
export default class App extends React.Component {
customerSDK = null
componentDidMount() {
this.customerSDK = init({
organizationId: ORGANIZATION_ID,
clientId: CLIENT_ID,
redirectUri: REDIRECT_URI,
})
// you can start using customerSDK from now
}
render() {
return (
)
}
}
`
If you are looking for something simpler, you can use a LiveChat for React Native library. This is a React Native component to easily add the LiveChat Widget with basic functionality to your application.
The LiveChat system includes four basic types of entities - users, chats, threads, and events.
- Chats consist of threads and threads consist of events.
- Threads are parts of chats.
- Users can add events to chats, which then are automatically added to threads.
- Users can participate in many chats at the same time.
Threads are a vital part of the LiveChat architecture.
Grouping events in threads allows us to provide the continuous chat experience (i.e. the Customer always has the option to continue the conversation) while still maintaining smaller, logical chunks of events (e.g. for reporting and caching purposes).
Handling operations such as loading archival events from the chat history can be challenging, but you won't have to worry about managing threads most of the time.
Customer SDK provides wrappers for common tasks and most methods expect to receive chat IDs.
You will only get notified about thread metadata if you explicitly ask for it.
You can read more about key concepts of the LiveChat messaging in the Messaging Overview.
`js`
{
id: 'ed9d4095-45d6-428d-5093-f8ec7f1f81b9',
type: 'agent',
name: 'Jane Doe',
jobTitle: 'Agent',
avatar: 'https://cdn.livechat.com/cloud/?uri=https://livechat.s3.amazonaws.com/default/avatars/a7.png',
}
`js`
{
id: 'ed9d0195-45d6-428d-5093-f8ec7f1471b9',
type: 'customer',
name: 'Jon Doe',
avatar: 'https://cdn.livechat.com/cloud/?uri=https://livechat.s3.amazonaws.com/default/avatars/a6.png',
fields: {
custom_property: 'BasketValue=10usd',
}
}
`js`
{
id: 'OU0V0P0OWT',
users: [{
id: 'ed9d4095-45d6-428d-5093-f8ec7f1f81b9',
// ... more user properties
}],
lastSeenTimestamps: {
'ed9d4095-45d6-428d-5093-f8ec7f1f81b9': 1503062591000, // might be null
},
threads: ['OU0V0U3IMN'],
}
`js`
{
type: 'message',
text: 'hi!',
author: 'ed9d4095-45d6-428d-5093-f8ec7f1f81b9', // assigned by server
id: 'OU0V0U3IMN_1', // assigned by server
timestamp: 1503062591000, // assigned by server
customId: '814.3316641404942', // optional
thread: 'OU0V4R0OXP',
properties: {},
}
`js`
{
id: 'OU0V0U3IMN',
active: true,
order: 3,
users: ['ed9d4095-45d6-428d-5093-f8ec7f1f81b9'],
lastSeenTimestamps: {
'ed9d4095-45d6-428d-5093-f8ec7f1f81b9': 1503062591000, // might be null
},
events: [ / events / ],
}
You can use this method to inform that a Customer has seen a greeting. Based on that, the Reports section displays only the greetings seen by Customers instead of all the sent greetings. If a Customer started a chat from a greeting but you didn't execute acceptGreeting method, the greeting counts as seen in Reports anyway.
As arguments to this method you should use uniqueId & greetingId received in the incoming_greeting or connected event.
`js`
customerSDK
.acceptGreeting({
greetingId: 7,
uniqueId: 'Q10X0W041P',
})
.then(response => {
console.log(response)
})
.catch(error => {
console.log(error)
})
Parameters:
| parameters | type |
| ---------- | ------ |
| greetingId | number |
| uniqueId | string |
- GREETING_NOT_FOUND - a given uniqueId couldn't be found on the server
Cancels a greeting (an invitation to the chat). For example, Customers could cancel greetings by clicking close icon on the displayed greeting.
`js`
customerSDK
.cancelGreeting({
uniqueId: 'Q10X0W041P',
})
.then(response => {
console.log(response)
})
.catch(error => {
console.log(error)
})
Parameters:
| parameters | type |
| ---------- | ------ |
| uniqueId | string |
- GREETING_NOT_FOUND - given uniqueId could not be found on the server
Cancels rate-related thread properties.
`js`
customerSDK
.cancelRate({
chatId: 'ON0X0R0L67',
properties: ['score', 'comment'],
})
.then(response => {
console.log(response)
})
.catch(() => {
console.log(error)
})
- MISSING_CHAT_THREAD - the targeted chat is empty and has no threads.
Starts the connection process to our servers. It is needed when:
- The autoConnect: false argument has been passed to the init method.
`js
const customerSDK = CustomerSDK.init({
licenseId: LICENSE_ID,
clientId: CLIENT_ID,
autoConnect: false,
})
/ later in the code... /
customerSDK.connect()
`
- You get disconnected for a reason that suspends reconnection attempts (e.g. inactivity_timeout).
`js`
customerSDK.on('disconnected', ({ reason }) => {
if (reason === 'inactivity_timeout') {
customerSDK.connect()
}
})
`js`
customerSDK
.deactivateChat({ id: 'ON0X0R0L67' })
.then(response => {
console.log(response)
})
.catch(error => {
console.log(error)
})
Parameters:
| parameters | type | description |
| ---------- | ------ | ----------------------------------------- |
| id | string | Chat ID in which thread should get closed |
Returned value:
| properties | type |
| ---------- | ------- |
| success | boolean |
Deletes given chat properties.
`js`
customerSDK
.deleteChatProperties({
id: 'ON0X0R0L67',
properties: {
property_namespace: ['sample'],
},
})
.then(response => {
console.log(response)
})
.catch(error => {
console.log(error)
})
Parameters:
| parameters | type | description |
| ---------- | ------ | --------------------------------------------------- |
| id | string | ID of the chat whose properties you want to delete. |
| properties | object | Chat properties to delete |
Returned value:
| properties | type |
| ---------- | ------- |
| success | boolean |
Deletes given event properties.
`js`
customerSDK
.deleteEventProperties({
chatId: 'ON0X0R0L67',
threadId: 'OS0C0W0Z1B',
eventId: 'Q50W0A0P0Y',
properties: {
property_namespace: ['sample'],
},
})
.then(response => {
console.log(response)
})
.catch(error => {
console.log(error)
})
Parameters:
| parameters | type | description |
| ---------- | ------ | ----------------------------------------------------- |
| chatId | string | ID of the chat whose properties you want to delete. |
| threadId | string | ID of the thread whose properties you want to delete. |
| eventId | string | ID of the event whose properties you want to delete. |
| properties | object | Properties to delete |
Returned value:
| properties | type |
| ---------- | ------- |
| success | boolean |
Deletes given chat thread properties.
`js`
customerSDK
.deleteThreadProperties({
chatId: 'ON0X0R0L67',
threadId: 'OS0C0W0Z1B',
properties: {
property_namespace: ['sample'],
},
})
.then(response => {
console.log(response)
})
.catch(error => {
console.log(error)
})
Parameters:
| parameters | type | description |
| ---------- | ------ | ----------------------------------------------------- |
| chatId | string | ID of the chat whose properties you want to delete. |
| threadId | string | ID of the thread whose properties you want to delete. |
| properties | object | Properties to delete |
Returned value:
| properties | type |
| ---------- | ------- |
| success | boolean |
Clears any stored resources, removes all listeners, and disconnects from the network.
After using this method, you won't be able to use the destroyed Customer SDK instance.
`js`
customerSDK.destroy()
Disconnects from the server.
`js`
customerSDK.disconnect()
Returns the chat data about the requested chat ID together with a single thread's data. If the method is called with the threadId parameter, then this particular thread is being returned. If no threadId is given, the latest thread is automatically returned.
`js`
customerSDK
.getChat({
chatId: 'ON0X0R0L67',
})
.then(chat => {
const { id, access, users, properties, thread } = chat
console.log({ id, access, users, properties, thread })
})
.catch(error => {
console.log(error)
})
Parameters:
| parameters | type | description |
| ---------- | ------ | ----------- |
| chatId | string | |
| threadId | string | optional |
Returned value:
| properties | type | description |
| ---------- | -------- | ------------------------------------ |
| id | string | Chat ID |
| access | object | Chat initial access |
| users | object[] | Users objects referenced in the chat |
| properties | object | Chat properties |
| thread | object | |
Helps loading in historical thread events.
First, call getChatHistory to access the history object of a particular chat.history
The returned object has only one method, next, which gives you a Promise with a { done, value } object.
- done - indicates if there is anything more to loadvalue
- - an object with an array of threads, each containing an array of its events
Then, you can keep calling history.next() multiple times to load previous historical events. They're going to be grouped into threads and might require merging with already loaded events.next
This is useful for implementing an infinite scroll or otherwise showing your Customer's archival chats.
Keep in mind, though, that you generally shouldn't call while the history is loading - we queue those requests, so the previous one must resolve before we proceed with the next one.
The structure such as our history object is called an async iterator.
`js
let wholeChatHistoryLoaded = false
const history = customerSDK.getChatHistory({ chatId: 'OU0V0P0OWT' })
history.next().then(result => {
if (result.done) {
wholeChatHistoryLoaded = true
}
const { threads } = result.value
const events = threads
.map(thread => thread.events || [])
.reduce((acc, current) => acc.concat(current), [])
console.log(events)
})
`
Parameters:
| parameters | type | description |
| ---------- | ------ | --------------------------------------- |
| chatId | string | Chat ID of the requested history object |
Returns the info about the Customer requesting it.
`js`
customerSDK
.getCustomer()
.then(customer => {
console.log(customer)
})
.catch(error => {
console.log(error)
})
Returned value:
| properties | type | description |
| --------------------------------- | ---------- | -------------------- |
| type | 'customer' | |
| id | string | |
| name | string | Returned only if set |
| email | string | Returned only if set |
| avatar | string | Returned only if set |
| sessionFields | object | |
| statistics | object | |
| statistics.chatsCount | number | |
| statistics.threadsCount | number | |
| statistics.visitsCount | number | |
| statistics.pageViewsCount | number | |
| statistics.greetingsShownCount | number | |
| statistics.greetingsAcceptedCount | number | |
Allows you to fetch a form template for a given group and form type.
`js`
customerSDK
.getForm({
groupId: 0,
type: 'prechat',
})
.then(response => {
if (response.enabled) {
// prechat form is enabled for this group in the configurator
console.log(response.form)
}
})
.catch(error => {
console.log(error)
})
Parameters:
| parameters | type |
| ---------- | --------------------------------- |
| groupId | number |
| type | 'prechat', 'postchat' or 'ticket' |
Returned value:
| properties | type | description |
| ----------- | -------- | ------------------------------------------- |
| enabled | boolean | |
| form | object | Available only when a given form is enabled |
| form.id | string | |
| form.fields | object[] | |
`js`
customerSDK
.getPredictedAgent({
groupId: 0,
})
.then(agent => {
console.log(agent)
})
.catch(error => {
console.log(error)
})
Parameters:
| parameters | type | description |
| ---------- | ------ | ----------- |
| groupId | number | Optional |
Returned value:
| properties | type | description |
| -------------- | ------- | ------------------------------------------------------------- |
| agent | object | |
| agent.id | string | |
| agent.name | string | |
| agent.jobTitle | string | |
| agent.type | 'agent' | |
| agent.isBot | boolean | |
| queue | boolean | True when the current group has reached concurrent chat limit |
- GROUP_OFFLINE - the requested group is offline, and it was not possible to return a predicted Agent for it.GROUP_UNAVAILABLE
- - thrown when manual routing is enabled for the group and a predicted Agent is requested for it. If you call startChat or resumeChat accordingly, you'll end up in the queue.
It returns the info on a given URL.
`jsThe title of requested URL is: ${urlDetails.title}
customerSDK
.getUrlInfo({ url: 'https://www.livechat.com' })
.then(urlDetails => {
if (urlDetails.title) {
console.log()The description of requested URL is: ${urlDetails.description}
}
if (urlDetails.description) {
console.log(
,The preview image of requested URL is available under: ${urlDetails.imageUrl}
)
}
if (urlDetails.imageUrl) {
console.log(
,Its width is: ${urlDetails.imageWidth}
)
if (urlDetails.imageWidth && urlDetails.imageHeight) {
console.log()Its height is: ${urlDetails.imageHeight}
console.log()`
}
}
})
.catch(error => {
console.log(error)
})
Parameters:
| parameters | type |
| ---------- | ------ |
| url | string |
Returned value:
| properties | type | description |
| ----------- | ------ | ----------- |
| url | string | |
| title | string | Optional |
| description | string | Optional |
| imageUrl | string | Optional |
| imageWidth | number | Optional |
| imageHeight | number | Optional |
Unsubscribes from emitted events, which are described here.
Subscribes to emitted events, which are described here.
Subscribes to emitted events, which are described here. Unsubscribes immediately after the callback gets called.
It returns summaries of the chats a Customer participated in.
`js`
customerSDK
.listChats({
pageId: 'MTU5MTEwMTUxNDM5NTk5OTpkZXNj',
limit: 10,
})
.then(({ chatsSummary, totalChats }) => {
console.log(chatsSummary)
console.log(totalChats)
})
.catch(error => {
console.log(error)
})
Parameters:
| parameters | type | description |
| ---------- | ------ | ------------------------------------------------------------------------------- |
| pageId | string | Optional; the cursor returned from the previous listChats calls |
| limit | number | Optional; the limit of returned results. Default is set to 10 and maximum is 25 |
Returned value:
| properties | type | description |
| --------------------------------- | -------- | ---------------------------------------------- |
| chatsSummary | object[] | |
| chatsSummary[].id | string | Chat ID |
| chatsSummary[].active | boolean | |
| chatsSummary[].users | object[] | Users objects referenced in the chat |
| chatsSummary[].lastEvent | object | Event |
| chatsSummary[].lastEventsPerType | object | Map of event types to event objects |
| chatsSummary[].lastSeenTimestamps | object | Map of user IDs to optional lastSeenTimestamps |
| chatsSummary[].lastThread | string | Thread ID |
| totalChats | number | |
Returns availability statuses of the requested groups.
`jsStatus of the group 3: ${statusMap[3]}
customerSDK
.listGroupStatuses({
groupIds: [3, 10],
})
.then(statusMap => {
console.log()Status of the group 10: ${statusMap[10]}
console.log()`
})
.catch(error => {
console.log(error)
})
Parameters:
| parameters | type | description |
| ---------- | -------- | ---------------------------------------------------------- |
| groupsIds | number[] | Optional; if omitted, statuses of all groups are returned. |
Returned value:
| properties | type | description |
| ---------- | ------ | --------------------------------------------- |
| statusMap | object | Map of group numbers to availability statuses |
Returns a list of thread objects together with the previous and next page ID cursors that can be used to load more threads.
If you want to load consecutive events, consider using getChatHistory.
`js`
customerSDK
.listThreads({
chatId: 'ON0X0R0L67',
})
.then(response => {
console.log(response.threads)
console.log(response.previousPageId)
console.log(response.nextPageId)
})
.catch(error => {
console.log(error)
})
Parameters:
| parameters | type | description |
| -------------- | --------------- | ------------------------------------------------------------------- |
| chatId | string | |
| pageId | string | Optional, the cursor returned from the previous listThreads calls |minEventsCount
| sortOrder | 'desc' \| 'asc' | Optional, default: 'desc' |
| limit | number | Optional, default: 3, can't be used together with |limit
| minEventsCount | number | Optional, can't be used together with |
Returned value:
| properties | type | description |
| ------------------------ | -------- | -------------------------------------------------------------------------- |
| threads | object[] | |
| threads[].id | string | Thread ID |
| threads[].chatId | string | Chat ID |
| threads[].active | boolean | Active state |
| threads[].createdAt | string | Thread creation date in RFC 3339 date-time format |
| threads[].userIds | string[] | User IDs |
| threads[].events | object[] | Events |
| threads[].properties | object | Chat properties |
| threads[].access | object | |
| threads[].queue | object | Optional |
| threads[].queue.position | number | Current position in the queue |
| threads[].queue.waitTime | number | Estimated waiting time for an agent to be assigned to the chat, in seconds |
| threads[].queue.queuedAt | string | RFC 3339 date-time format |
| previousPageId | string | |
| nextPageId | string | |
Marks events as seen by the current Customer up to the given date.
`js`
customerSDK
.markEventsAsSeen({
chatId: 'ON0X0R0L67',
seenUpTo: '2017-10-12T15:19:21.010200Z',
})
.then(response => {
console.log(response)
})
.catch(error => {
console.log(error)
})
Parameters:
| parameters | type | description |
| ---------- | ------ | ---------------------------------------------------------------------------------------- |
| chatId | string | ID of the chat in which you want to mark events as seen. |
| seenUpTo | string | RFC 3339 date-time format; you should use the event's createdAt value as the argument. |
Returned value:
| properties | type |
| ---------- | ------- |
| success | boolean |
Sends chat rating and a comment for the most recent chat thread.
`js`
customerSDK
.rateChat({
chatId: 'ON0X0R0L67',
rating: {
score: 1,
comment: 'Agent helped me a lot!',
},
})
.then(() => {
console.log('Rating has been set')
})
.catch(error => {
console.log(error)
})
Parameters:
| parameters | type | description |
| -------------- | ------ | -------------------------------------------------------- |
| chatId | | Destination chat ID |
| rating | | |
| rating.score | 0 or 1 | Rating value: 0 for a bad rating and 1 for a good rating |
| rating.comment | string | Optional comment |
Returned value:
| properties | type |
| ---------- | ------- |
| success | boolean |
- MISSING_CHAT_THREAD - the targeted chat cannot be rated because it has no threads.
Resumes an archived chat.
`js`
customerSDK
.resumeChat({
chat: {
id: 'OU0V0P0OWT',
thread: {
events: [],
},
},
})
.then(chat => {
console.log(chat)
})
.catch(error => {
console.log(error)
})
Parameters:
| parameters | type | description |
| --------------------------- | ------- | ----------------------------------------------------------------------------------------------------------------- |
| data.active | boolean | Optional; defaults to true but can be used to create threads that are immediately inactive |
| data.continuous | boolean | Optional |
| data.chat.id | string | |
| data.chat.access | Access | Optional |
| data.chat.properties | object | Optional, Default properties docs |
| data.chat.thread.events | Event[] | Optional; you can pass initial events which will immediately become part of the created thread. |
| data.chat.thread.properties | object | Optional, Default properties docs |
- CHAT_ALREADY_ACTIVE - the chat is already active and you can't activate it again.GROUPS_OFFLINE
- - a group in the targeted chat is offline. It can happen when asynchronous communication is disabled.
Sends a provided object as an event with a specified type.
`js
const event = {
type: 'message',
// ... other properties specific for the event's type
}
customerSDK
.sendEvent({
chatId: 'ON0X0R0L67',
event,
})
.then(event => {
console.log(event)
})
.catch(error => {
console.log(error)
})
`
Parameters:
| parameters | type | description |
| ------------------ | ------- | ------------------- |
| chatId | string | Destination chat ID |
| event | | |
| event.type | string | Type of the event |
| attachToLastThread | boolean | Optional |
Sends information to the server about a user's interaction with a rich message button.
`js`
customerSDK
.sendRichMessagePostback({
chatId: 'ON0X0R0L67',
threadId: 'OS0C0W0Z1B',
eventId: 'OS0C0W0Z1B01',
postback: {
id: 'OS0C0W0Z1B01002',
toggled: true,
},
})
.then(() => {
console.log('success')
})
.catch(error => {
console.log(error)
})
Parameters:
| parameters | type | default | description |
| ---------------- | ------- | ------- | ------------------ |
| chatId | string | | postback chat ID |
| threadId | string | | postback thread ID |
| eventId | string | | postback event ID |
| postback | | | |
| postback.id | string | | Postback button ID |
| postback.toggled | boolean | true | Postback toggled |
Sends the request to set customer's session fields. They are available for the duration of the session.
`js`
customerSDK.setCustomerSessionFields({
sessionFields: {
foo: 'bar',
test: 'qwerty',
},
})
Parameters:
| parameters | type |
| ------------- | ------ |
| sessionFields | object |
You can use it to update the sneak peek in the Agent App.
It is sent to the server only if the target chat is active. This method doesn't return a promise.
`js`
customerSDK.setSneakPeek({
chatId: 'ON0X0R0L67',
sneakPeekText: 'what is the price for your ',
})
Parameters:
| parameters | type | description |
| ------------- | ------ | ---------------------------------------- |
| chatId | string | Target chat ID |
| sneakPeekText | string | Message preview broadcasted to the Agent |
Starts a new chat. For one Customer, you can only start one chat.
In order to activate a previously started chat, use resumeChat.
`js`
customerSDK
.startChat({
chat: {
thread: {
events: [],
},
},
})
.then(chat => {
console.log(chat)
})
.catch(error => {
console.log(error)
})
Parameters:
| parameters | type | description |
| ---------------------- | ------- | ----------------------------------------------------------------------------------------------------------------- |
| active | boolean | Optional, defaults to true but can be used to create threads that are immediately inactive |
| continuous | boolean | Optional |
| chat.access | access | Optional |
| chat.properties | object | Optional, Default properties docs |
| chat.thread.events | event[] | Optional; initial events that will immediately become a part of the created thread. |
| chat.thread.properties | object | Optional, Default properties docs |
- CHAT_LIMIT_REACHED - the maximum limit of chats per Customer has been reached, and it's not possible to start a new one. You should activate one of the existing chats. The limit is 1.GROUPS_OFFLINE
- - a group in the targeted chat is offline. It can happen when asynchronous communication is disabled.
`js`
const properties = {
property_namespace: {
sample: 'property',
},
}
customerSDK
.updateChatProperties({ id: 'ON0X0R0L67', properties })
.then(response => {
console.log(response)
})
.catch(error => {
console.log(error)
})
Parameters:
| parameters | type | description |
| ---------- | ------ | ------------------------------------------------------------------------------------------------------- |
| id | string | ID of the chat whose properties you want to update. |
| properties | object | Default properties docs |
Updates the specified Customer properties and fields.
`js`
const properties = {
name: 'John Doe',
email: 'john.doe@example.com',
sessionFields: {
custom_property: 'BasketValue=10usd',
any_key_is_ok: 'sample custom field',
},
}
customerSDK.updateCustomer(properties)
Parameters:
| parameters | type | description |
| ------------------------ | ------ | ------------------------------------------ |
| properties | | |
| properties.name | string | Optional |
| properties.email | string | Optional |
| properties.sessionFields | object | Optional; custom fields with string values |
- CUSTOMER_SESSION_FIELDS_LIMIT_REACHED - total amount of session fields would have been exceeded after requested update
Updates information about the Customer page using the provided page object.
`js`
const page = {
url: 'https://developers.livechat.com/',
title: 'LiveChat for Developers',
}
customerSDK.updateCustomerPage(page)
Parameters:
| parameters | type |
| ---------- | ------ |
| page | |
| page.url | string |
| page.title | string |
Updates given properties of an event.
`js`
const properties = {
property_namespace: {
sample: 'property',
},
}
customerSDK
.updateEventProperties({
chatId: 'ON0X0R0L67',
threadId: 'OS0C0W0Z1B',
eventId: 'Q50W0A0P0Y',
properties,
})
.then(response => {
console.log(response)
})
.catch(error => {
console.log(error)
})
Parameters:
| parameters | type | description |
| ---------- | ------ | ------------------------------------------------------------------------------------------------------- |
| chatId | string | ID of the chat whose properties you want to update. |
| threadId | string | ID of the thread whose properties you want to update. |
| eventId | string | ID of the event whose properties you want to update. |
| properties | object | Default properties docs |
`js`
const properties = {
property_namespace: {
sample: 'property',
},
}
customerSDK
.updateThreadProperties({
chatId: 'ON0X0R0L67',
threadId: 'OS0C0W0Z1B',
properties,
})
.then(response => {
console.log(response)
})
.catch(error => {
console.log(error)
})
Parameters:
| parameters | type | description |
| ---------- | ------ | -------------------------------------------------------------------------------------------------------- |
| chatId | string | ID of the chat whose properties you want to update. |
| threadId | string | ID of the thread whose properties you want to update. |
| properties | object | Default properties docs. |
Returns both a promise and a cancel. You can use cancel to abort a file upload.onProgress
It also lets you pass the callback function. Keep in mind that the maximum accepted file size is 10 MB.
It returns a URL that expires after 24 hours unless the URL is used in sendEvent
`jsupload progress: ${progress}
const { promise, cancel } = customerSDK.uploadFile({
file,
onProgress: progress => console.log(),
})
document.getElementById('cancel-upload').onclick = () => {
cancel()
}
promise
.then(response => {
console.log(response.url)
})
.catch(error => {
console.log(error)
})
`
Parameters:
| parameters | type | description |
| ---------- | -------- | ------------------------- |
| file | blob | |
| onProgress | function | Receives a progress value |
onProgress parameters:
| parameters | type | min | max |
| ---------- | ------ | --- | --- |
| progress | number | 0 | 1 |
Returned value:
| properties | type |
| ---------- | ------ |
| url | string |
In React Native, instead of passing a blob you need to pass an object of
such a shape:
`js`
const file = {
uri: uriFromCameraRoll,
type: 'image/jpeg', // optional
name: 'photo.jpg', // optional
}
You can listen for emitted events by subscribing to them using the on method with your custom callback.
For example, your function can be executed every time a message is received.
Informs about a changed availability status.
`js`
customerSDK.on('availability_updated', ({ availability }) => {
console.log('availability_updated', availability)
})
Payload:
| properties | type | description |
| ------------ | ------ | --------------------- |
| availability | string | 'online' or 'offline' |
Informs that thread has been closed.
`js`
customerSDK.on('chat_deactivated', payload => {
const { chatId } = payload
console.log('chat_deactivated', { chatId })
})
Payload:
| properties | type | description |
| ---------- | ------ | ----------- |
| chatId | string | Chat ID |
Informs about deleted chat properties.
`js`
customerSDK.on('chat_properties_deleted', payload => {
const { chatId, properties } = payload
console.log('chat_properties_deleted', { chatId, properties })
})
Payload:
| properties | type | description |
| ---------- | ------ | --------------- |
| chatId | string | Chat ID |
| properties | object | Chat properties |
Informs about updated chat properties.
`js`
customerSDK.on('chat_properties_updated', payload => {
const { chatId, properties } = payload
console.log('chat_properties_updated', { chatId, properties })
})
Payload:
| properties | type | description |
| ---------- | ------ | --------------- |
| chatId | string | Chat ID |
| properties | object | Chat properties |
Informs that a chat was transferred to a different group or an Agent.
`js`
customerSDK.on('chat_transferred', payload => {
const { chatId, threadId, transferredTo } = payload
console.log('chat_transferred', {
chatId,
threadId,
transferredTo,
})
})
Payload:
| properties | type | description |
| ---------------------- | -------- | -------------------------------------------------------------------------- |
| chatId | string | |
| threadId | string | |
| reason | string | |
| requesterId | string | returned only if reason is equal to 'manual' |
| transferredTo | | |
| transferredTo.agentIds | string[] | optional |
| transferredTo.groupIds | number[] | optional |
| queue | | optional |
| queue.position | number | Current place in the queue |
| queue.waitTime | number | Estimated waiting time for an agent to be assigned to the chat, in seconds |
| queue.queuedAt | string | RFC 3339 date-time format |
Informs that the connection has been established.
`js`
customerSDK.on('connected', payload => {
const { customer, availability, greeting } = payload
console.log('connected', { customer, availability, greeting })
})
Payload:
| argument | type | description |
| ------------ | -------- | ---------------------------------------------------------------------------- |
| customer | object | Customer object, the same as the response from getCustomer |
| availability | string | 'online' or 'offline' |
| greeting | greeting | Optional greeting received before the thread started |
Greeting:
| argument | type | description |
| ------------------ | ------- | ------------------------------------ |
| id | number | Greeting template identifier |
| text | string | Text content of the greeting message |
| uniqueId | string | Unique event ID of the greeting |
| displayedFirstTime | boolean | |
| accepted | boolean | |
| agent.id | string | |
| agent.name | string | |
| agent.avatar | string | |
| agent.jobTitle | string | |
| agent.isBot | boolean | |
Informs that Customer SDK has recovered from an "unstable" connection state. It's always preceded by the "connection_unstable" event.
`js`
customerSDK.on('connection_recovered', () => {
console.log('connection_recovered')
})
This event doesn't carry any additional payload.
Informs that Customer SDK has detected that connection quality is poor. It doesn't mean that it has disconnected from the server just yet.
`js`
customerSDK.on('connection_unstable', () => {
console.log('connection_unstable')
})
This event doesn't carry any additional payload.
Informs about the ID of the Customer.
`js`
customerSDK.on('customer_id', id => {
console.log('customer id is', id)
})
Payload:
| argument | type |
| -------- | ------ |
| id | string |
The Customer moved to another page, for example by following a link on your website.
`js`
customerSDK.on('customer_page_updated', payload => {
const { url, title, openedAt } = payload
console.log('customer_page_updated', { url, title, openedAt })
})
Payload:
| properties | type | |
| ---------- | ------ | ---------------------------------------------------- |
| url | string | URL of the Customer current website |
| title | string | Title of the Customer current website |
| openedAt | string | Date of the last update in RFC 3339 date-time format |
Informs that Customer's data was updated.
Each property in payload is available only if it was updated.
`jsName got updated to: ${customer.name}
customerSDK.on('customer_updated', customer => {
if (customer.name) {
console.log()Email got updated to: ${customer.email}
}
if (customer.email) {
console.log()Avatar got updated to: ${customer.avatar}
}
if (customer.avatar) {
console.log()Fields got updated:
}
if (customer.fields) {
console.log()`
console.log(customer.fields)
}
})
Payload:
| properties | type |
| ---------- | ------ |
| name | string |
| email | string |
| avatar | string |
| fields | object |
Informs that SDK has disconnected from the server. The event provides the disconnection reason.
`js`
customerSDK.on('disconnected', payload => {
const { reason } = payload
console.log('disconnected', { reason })
})
Payload:
| properties | type | description |
| ---------- | ------ | ----------------------------------------------- |
| reason | string | disconnection reasons |
Informs about the event properties that were deleted.
`js`
customerSDK.on('event_properties_deleted', payload => {
const { chatId, threadId, eventId, properties } = payload
console.log('event_properties_deleted', {
chatId,
threadId,
eventId,
properties,
})
})
Payload:
| properties | type | description |
| ---------- | ------ | ---------------- |
| chatId | string | Chat ID |
| threadId | string | Thread ID |
| eventId | string | Event ID |
| properties | object | Event properties |
Informs about the event properties that were updated.
`js`
customerSDK.on('event_properties_updated', payload => {
const { chatId, threadId, eventId, properties } = payload
console.log('event_properties_updated', {
chatId,
threadId,
eventId,
properties,
})
})
Payload:
| properties | type | description |
| ---------- | ------ | ---------------- |
| chatId | string | Chat ID |
| threadId | string | Thread ID |
| eventId | string | Event ID |
| properties | object | Event properties |
Informs that an event was updated.
`js`
customerSDK.on('event_updated', payload => {
const { chatId, threadId, event } = payload
console.log('event_updated', { chatId, threadId, event })
})
Payload:
| properties | type | description |
| ---------- | ------ | ------------------------ |
| chatId | string | Chat ID |
| threadId | string | Thread ID |
| event | object | The entire updated event |
Informs that the events were seen by the particular user.
`js`
customerSDK.on('events_marked_as_seen', payload => {
const { chatId, userId, seenUpTo } = payload
console.log('events_marked_as_seen', { chatId, userId, seenUpTo })
})
Payload:
| properties | type | description |
| ---------- | ------ | ------------------------- |
| chatId | string | Chat ID |
| userId | string | User ID |
| seenUpTo | string | RFC 3339 date-time format |
Informs about a greeting accepted by the Customer.
`js`
customerSDK.on('greeting_accepted', payload => {
console.log('greeting_accepted', payload.uniqueId)
})
Payload:
| properties | type |
| ---------- | ------ |
| uniqueId | string |
Informs about a greeting canceled by the Customer. It is also emitted when a new greeting automatically cancels the currently displayed one.
`js`
customerSDK.on('greeting_canceled', payload => {
console.log('greeting_canceled', payload.uniqueId)
})
Payload:
| properties | type |
| ---------- | ------ |
| uniqueId | string |
Informs about a newly started chat thread.
The payload contains the chat data structure and an object describing the new thread.
If the chat was started with some initial events, they will be included in the thread object.
`js`
customerSDK.on('incoming_chat', payload => {
const { chat } = payload
const { id, access, users, properties, thread } = chat
console.log('incoming_chat', { id, access, users, properties, thread })
})
Payload:
| properties | type | description |
| --------------- | -------- | ------------------------------------ |
| chat.id | string | Chat ID |
| chat.access | object | Chat initial access |
| chat.users | object[] | Users objects referenced in the chat |
| chat.properties | object | Chat properties |
| chat.thread | object | |
Informs about an incoming event sent to a chat.
You should distinguish received events by their types.
`js`
customerSDK.on('incoming_event', payload => {
const { chat, event } = payload
switch (event.type) {
case 'message':
console.log('new message - ', event.text)
break
default:
break
}
})
Payload:
| properties | type | description |
| ---------- | ------ | ---------------- |
| type | string | Event type |
| ... | | Other properties |
Informs about an incoming greeting.
`jsReceived a greeting with "${text}" text content from ${name}.
customerSDK.on('incoming_greeting', payload => {
const { text, agent } = payload
const { name } = agent
console.log()`
})
Payload:
| properties | type | description |
| ------------------ | ------- | ----------------------------------------------------------- |
| id | number | Greeting template ID |
| text | string | Greeting text content |
| uniqueId | string | Greeting unique ID |
| displayedFirstTime | boolean | Describes if the greeting was generated for the first time. |
| accepted | boolean | Chat properties |
| agent | object | Agent user |
Informs about an incoming rich message postback.
`js`
customerSDK.on('incoming_rich_message_postback', payload => {
const { chatId, threadId, eventId, userId, postback } = payload
console.log('incoming_rich_message_postback', {
chatId,
threadId,
eventId,
userId,
postback,
})
})
Payload:
| properties | type | description |
| ---------------- | ------- | ------------------------------------------- |
| chatId | string | Chat ID of the sent postback |
| threadId | string | Thread ID of the sent postback |
| eventId | string | Event ID of the sent postback |
| userId | number | User who has sent a rich message postback |
| postback.id | boolean | ID of the sent postback |
| postback.toggled | boolean | Describes if the sent postback was toggled. |
Informs that one of the chat users is currently typing a message.
The message hasn't been sent yet.
The push payload contains the typing indicator object.
`jsuser with ${payload.typingIndicator.authorId} id is writing something in ${payload.chatId}
customerSDK.on('incoming_typing_indicator', payload => {
if (payload.typingIndicator.isTyping) {
console.log(
,user with ${payload.typingIndicator.authorId} id stopped writing in ${payload.chatId}
)
} else {
console.log(
,`
)
}
})
Payload:
| properties | type | description |
| ------------------------ | ------- | ----------- |
| chatId | string | Chat ID |
| typingIndicator | | |
| typingIndicator.authorId | string | User ID |
| typingIndicator.isTyping | boolean | |
Informs that the queue position has been updated.
`js`
customerSDK.on('queue_position_updated', payload => {
console.log(payload.chatId)
console.log(payload.threadId)
console.log(payload.queue.position)
console.log(payload.queue.waitTime)
})
Payload:
| properties | type | description |
| -------------- | ------ | -------------------------------------------------------------------------- |
| chatId | string | Chat ID |
| threadId | string | Thread ID |
| queue | | |
| queue.position | number | Current place in the queue |
| queue.waitTime | number | Estimated waiting time for an agent to be assigned to the chat, in seconds |
Informs about deleted thread properties.
`js`
customerSDK.on('thread_properties_deleted', payload => {
const { chatId, threadId, properties } = payload
console.log('thread_properties_deleted', { chatId, threadId, properties })
})
Payload:
| properties | type | description |
| ---------- | ------ | ---------------------- |
| chatId | string | Chat ID |
| threadId | string | Thread ID |
| properties | object | Chat thread properties |
Informs about updated thread properties.
`js`
customerSDK.on('thread_properties_updated', payload => {
const { chatId, threadId, properties } = payload
console.log('thread_properties_updated', { chatId, threadId, properties })
})
Payload:
| properties | type | description |
| ---------- | ------ | ----------------- |
| chatId | string | Chat ID |
| threadId | string | Thread ID |
| properties | object | Thread properties |
Informs that a user was added to a chat.
`js``
customerSDK.on('user_added_to_chat', payload => {
const { chatId, user, present } = payload
console.log('user_added_to_chat', { chatId, user, present })
})
Payload:
| properties | type | description |
| ---------- | ------- | ----------- |
| chatId | string | Chat ID |
| user | object | User