Unverified Commit e393b9f6 authored by Gabriel Engel's avatar Gabriel Engel Committed by gitbook-bot
Browse files

GitBook: [master] 563 pages modified

parent 0ecdb19f
This diff is collapsed.
# Livechat Widget API
## Usage
Livechat Widget API code must be inserted after the Livechat Widget installation script and wrapped as a callback of `RocketChat();` function.
You can call multiple Livechat Widget APIs on the same page.
### Methods
#### _Set custom field_
To set a custom field for a visitor, you can use the following code:
```javascript
RocketChat(function() {
this.setCustomField('fieldName1', 'Any value you want to store');
this.setCustomField('fieldName2', 'A value set just once', false); // you can pass false as the third parameter to not overwrite an already set value
});
```
#### _Set theme options_
To change the online color of the Livechat widget, use the following code:
```javascript
RocketChat(function() {
this.setTheme({
color: '#04436A', // widget title background color
fontColor: '#FFFFFF', // widget title font color
iconColor: '#1d74f5', // widget icon color
title: "Welcome to Rocket.Chat", // default widget title when the status of service is online
offlineTitle: "Service is offline", // default widget title when the status of service is online
});
});
```
#### _Assign chats to a specific department_
To automatically assign a Livechat widget to a specific department \(for example, to use a unique Livechat widget on more than one website\), use the following code:
```javascript
RocketChat(function() {
this.setDepartment('FILL HERE DEPARTMENT NAME - case sensitive');
});
```
#### _Set visitor token_
To set an external token for a visitor, you can use the following code:
```javascript
RocketChat(function() {
this.setGuestToken('FHwaLnp8fzjMupSAj');
});
```
#### _Set name field_
To set the visitor name field, you can use the following code:
```javascript
RocketChat(function() {
this.setGuestName('visitor name');
});
```
#### _Set email field_
To set the visitor email field, you can use the following code:
```javascript
RocketChat(function() {
this.setGuestEmail('sample@rocket.chat');
});
```
#### _Register visitor_
To register the visitor without using the registration form, you can use the following code:
```javascript
RocketChat(function() {
this.registerGuest({
token: 'FHwaLnp8fzjMupSAj', // The token field is not required. If it is not passed, a new token will be generated
name: 'visitor Name',
email: 'sample@rocket.chat',
department: 'my_department', // The department field is not required,
customFields: [ // The customFields field is not required. If it is passed it needs to be an Array, where each item needs to be an object with key and value fields
{key: 'my_custom_field_a', value: 'my_custom_field_a_value'},
{key: 'my_custom_field_b', value: 'my_custom_field_b_value'}
]
});
});
```
#### _Set Language for Widget_
There are number of language options, which you can choose from to set language for your widget. To check supported languages refer [here](https://github.com/RocketChat/Rocket.Chat.Livechat/tree/dev/src/i18n). To set language of widget use the following code.
```javascript
RocketChat(function() {
this.setLanguage('af');
});
```
#### _Set a default Agent before starting a new conversation_
The widget allows setting a specific agent before the conversation starts, to do this follow these steps:
```javascript
RocketChat(function() {
this.setAgent({
_id: 'h24yNtyoCmvp96wgt',
username: 'rocket.chat',
});
});
```
#### _Initialize the widget by configuring all available properties in just one call_
The widget allows configuring all the settings in just one method, the following properties are acceptable:
```javascript
RocketChat(function() {
this.initialize({
theme: {
color: '#04436A',
fontColor: '#FFFFFF',
iconColor: '#1d74f5',
title: "Welcome to Rocket.Chat",
offlineTitle: "Service is offline",
},
department: 'sales',
guestToken: 'FHwaLnp8fzjMupSAj',
language: 'en',
});
});
```
#### _Change widget visibility_
You can either hide or show widget in your website. To hide widget use the following code:
```javascript
RocketChat(function() {
this.hideWidget();
});
```
To show widget use the following code.
```javascript
RocketChat(function() {
this.showWidget();
});
```
#### _Change widget window state_
You can either open or close then widget in your website. To open widget\(default state\) use the following code:
```javascript
RocketChat(function() {
this.maximizeWidget();
});
```
To close the widget use the following code.
```javascript
RocketChat(function() {
this.minimizeWidget();
});
```
### Events
#### _onChatMaximized_
Fired when the chat widget is maximized.
```javascript
RocketChat(function() {
this.onChatMaximized(function() {
// do whatever you want
console.log('chat widget maximized');
});
});
```
#### _onChatMinimized_
Fired when the chat widget is minimized.
```javascript
RocketChat(function() {
this.onChatMinimized(function() {
// do whatever you want
console.log('chat widget minimized');
});
});
```
#### _onChatStarted_
Fired when the chat is started \(the first message was sent\).
```javascript
RocketChat(function() {
this.onChatStarted(function() {
// do whatever you want
console.log('chat started');
});
});
```
#### _onChatEnded_
Fired when the chat is ended either by the agent or the visitor.
```javascript
RocketChat(function() {
this.onChatEnded(function() {
// do whatever you want
console.log('chat ended');
});
});
```
#### _onPrechatFormSubmit_
Fired when the pre-chat form is submitted.
```javascript
RocketChat(function() {
this.onPrechatFormSubmit(function(data) {
// data is an object containing the following fields: name, email and deparment (the department _id)
// do whatever you want
console.log('pre-chat form submitted');
});
});
```
#### _onOfflineFormSubmit_
Fired when the offline form is submitted.
```javascript
RocketChat(function() {
this.onOfflineFormSubmit(function(data) {
// data is an object containing the following fields: name, email and message
// do whatever you want
console.log('offline form submitted');
});
});
```
#### _onWidgetHidden_
Fired when widget is hidden.
```javascript
RocketChat(function() {
this.onWidgetHidden(function(data) {
// do whatever you want
console.log('chat widget hidden');
});
});
```
#### _onAssignAgent_
Fired when an agent is assigned to the chat.
```javascript
RocketChat(function() {
this.onAssignAgent(function(data) {
// data is an object containing the following fields: name, username and status
// do whatever you want
console.log('Agent assigned');
});
});
```
#### _onWidgetShown_
Fired when widget is shown.
```javascript
RocketChat(function() {
this.onWidgetShown(function(data) {
// do whatever you want
console.log('chat widget shown');
});
});
```
#### _onAgentStatusChange_
Fired when the status of the current agent changes.
```javascript
RocketChat(function() {
this.onAgentStatusChange(function(data) {
// data is an object containing the following fields: name, username and status
// do whatever you want
console.log('The status of the agent has changed');
});
});
```
## Change Log
| Version | Description |
| :--- | :--- |
| 3.1.0 | Added `setAgent` and `initialize` methods. Also, improved the `setTheme` method adding more options to customize the widget |
| 2.2.0 | Added `maximizeWidget` and `minimizeWidget` methods. |
| 1.3.0 | Added `onAssignAgent` and `onAgentStatusChange` methods. |
| 1.1.0 | Added `showWidget` and `hideWidget` methods along with `onWidgetHidden` and `onWidgetShown` events |
| 1.0.0 | Added `setLanguage` method |
| 0.66.0 | Added `setGuestToken`, `setGuestName`, `setGuestEmail` and `registerGuest` methods. |
| 0.53.0 | Added callback events and the ability to pass a flag to `setCustomField` so the value passed does not get wrote if there is already an existing value. |
| 0.36.0 | Added `setTheme` method |
| 0.26.0 | Added `setCustomField` method |
# Two Factor Authentication
Visit [the Two Factor Authorization page](../../guides/developer-guides/two-factor.md) for general information about Two Factor Authorization.
## Errors
When a call that requires two factor is made it will return an error `totp-require`. The details object will list the method that has been required \(email on this example\) so it's possible to inform the user to check his email for the code.
* **method**: The method selected by the server. Useful to inform the user where to look for the code.
* **codeGenerated**: Email only. Used to inform if the code was generated or if there are tokens available already.
* **codeCount**: \(optional\) Email only. The number of available codes already sent via email.
* **codeExpires**: \(optional\) Email only. A list of expiration dates of the tokens.
* **availableMethods**: The list of available methods for Two Factor. When calling an api it's possible to define the method to use.
```javascript
{
"msg": "result",
"id": "1",
"error": {
"isClientSafe": true,
"error": "totp-required",
"reason": "TOTP Required",
"details": {
"method": "email",
"codeGenerated": false,
"codeCount": 1,
"codeExpires": [
"2019-12-31T22:05:22.159Z"
],
"availableMethods": [
"email"
]
},
"message": "TOTP Required [totp-required]",
"errorType": "Meteor.Error"
}
}
```
## Calling a method with Two Factor
After receive the error it's necessary to pass the informed code to the API. For that we need to call a new method called `callWithTwoFactorRequired` passing the information as an object:
### Request
* **code**: \(string\) The code informed by the user;
* **ddpMethod**: \(string\) The original method called;
* **method**: \(string\) The desired method to check the Two Factor, usually the same from the error;
* **params**: \(any\[\]\) An array of parameters used for the original method;
### Result
* If the two factor was accepted the **result** and the **error** will came from the original method;
* If the two factor was not accepted the **error** `totp-invalid` will be returned;
### Example
```javascript
Meteor.call('callWithTwoFactorRequired', { code, ddpMethod, method, params: args }, (error, result) => {});
```
## Requesting a new email code
If the user didn't receive the code it's possible to request the server to send a new code via email by calling the DDP Method `sendEmailCode` passing the user's email or username. It's required to pass the email or username because this Method can be called when the user is not logged in.
### Request
* **sendEmailCode**: \(string\) The user's username or email
### Result
* If success: **array of emails** to where the code was sent;
* If error: **error-parameter-required** if the parameter `emailOrUsername` was not provided;
* If error: **error-invalid-user** if the user was not found with the provided `emailOrUsername`;
### Example
```javascript
Meteor.call('sendEmailCode', emailOrUsername, (error, result) => {});
```
## Enabling the Two Factor via Email
It's possible to enable the email check by calling the Method `2fa:enable-email`. Note that the two factor via email will only work if the user has at least one verified email.
### Result
* If success: **true** is returned;
* If error: **not-authorized** if the user is not logged in;
### Example
```javascript
Meteor.call('2fa:enable-email', (error, result) => {});
```
## Disabling the Two Factor via Email
It's possible to disabled the email check by calling the Method `2fa:disable-email`. Note this Method requires the two factor to be executed.
### Result
* If success: **true** is returned;
* If error: A two factor verification error is returned;
### Example
```javascript
Meteor.call('2fa:disable-email', (error, result) => {});
```
# Realtime API
Point your client to the Websocket of the server you want to connect to:
```text
wss://[ABC.DOMAIN.COM]/websocket
```
Our real-time API is composed of two elements: [Method Calls](method-calls/) and [Subscriptions](subscriptions/). Both of them are supported directly in the websocket connection.
To make it possible to have everything working on the same connection we use RPC with the following format.
```javascript
{
"msg": "type-of-communication",
"id": "unique-id",
... // per call defined data
}
```
The type of communication is defined according to the call:
* [Method Calls](method-calls/): `method`
* [Subscriptions](subscriptions/): `sub`
Please note, the server will send you "ping" and you must respond with "pong" otherwise the server will close the connection.
Before requesting any method / subscription you have to send a connect message:
```javascript
{
"msg": "connect",
"version": "1",
"support": ["1"]
}
```
## Resources
* A basic example script that uses the 'ddp' NodeJS package to subscribe to the Realtime-API stream of a Group/Channel here [https://github.com/jszaszvari/rocketchat-ddp-listener](https://github.com/jszaszvari/rocketchat-ddp-listener)
* [Rocket.Chat.RealTime.API.RxJS](https://github.com/inf3cti0n95/Rocket.Chat.RealTime.API.RxJS) Abstraction for Utilizing [Rocket.Chat](https://rocket.chat/)'s [Realtime API](https://rocket.chat/docs/developer-guides/realtime-api) Methods with [RxJS](http://reactivex.io/rxjs/). [https://github.com/inf3cti0n95/Rocket.Chat.RealTime.API.RxJS](https://github.com/inf3cti0n95/Rocket.Chat.RealTime.API.RxJS)
# Livechat Realtime API
This API is intended to be used for having a Livechat conversation;
* First of all you need to generate a visitor token \(any random string\);
* Call [livechat:getInitialData](getinitialdata.md) passing `visitorToken` as first argument, the response will be an object containing a Livechat [configuration object](getinitialdata.md#response) with following properties:
| Field | Type | Description |
| :--- | :--- | :--- |
| `enabled` | `Boolean` | If whether Livechat is enabled for that server or not |
| `title` | `String` | The Livechat widget title |
| `color` | `Hexadecimal` | The hexadecimal color of the Livechat widget title bar when the Livechat is online |
| `registrationForm` | `Boolean` | If the registration form should be displayed or not. |
| `room` | `Object` | The current conversation room for the current guest user |
| `visitor` | `Object` | The current guest user |
| `triggers` | `Array` | Array of Livechat triggers. |
| `departments` | `Array` | Array of Livechat departments. |
| `allowSwitchingDepartments` | `Boolean` | If client-side department switching is allowed |
| `online` | `Boolean` | If there are Livechat agents online |
| `offlineColor` | `Hexadecimal` | The hexadecimal color of the Livechat widget title bar when the Livechat is offline |
| `offlineMessage` | `String` | The message that will be displayed on the Livechat offline form |
| `offlineSuccessMessage` | `String` | The message that will be displayed after send a message using the offline form |
| `offlineUnavailableMessage` | `String` | The message that will be displayed when the Livechat is offline |
| `displayOfflineForm` | `Boolean` | If the offline form will be displayed when the Livechat is offline |
| `videoCall` | `Boolean` | If the VideoCall feature is available |
| `conversationFinishedMessage` | `Boolean` | The system message that will be send to the current guest user when the conversation is closed |
| `nameFieldRegistrationForm` | `Boolean` | If the name field will be displayed on Livechat registration form |
| `emailFieldRegistrationForm` | `Boolean` | If the email field will be displayed on Livechat registration form |
| `offlineTitle` | `String` | The title of the widget when the Livechat is offline |
| `language` | `String` | The default user language to be set in the Livechat widget |
| `transcript` | `Boolean` | If the Livechat widget will ask the current guest user if they would like a transcript after the conversation is closed |
| `transcriptMessage` | `String` | The message to be displayed when asking about transcript |
| `agentData` | `Object` | The current agent attending the chart |
* Call [livechat:registerGuest](registerguest.md) to register guest and get the response containing the visitor's data.
* Before sending the first message you have to generate a random `room _id`;
* Now you can send messages to method [sendMessageLivechat](sendmessagelivechat.md)
* Subscribe to: [stream-room-messages](../subscriptions/stream-room-messages.md) and `stream-livechat-room`
* Get agent info by calling `livechat:getAgentData`
# Method: livechat:getInitialData
## DDP message
```javascript
{"msg":"method","method":"livechat:getInitialData","params":["7T4jzes7rX3Fr6cQ2"],"id":"1"}
```
## Response
```javascript
{
enabled: true,
title: 'Rocket.Chat',
color: '#C1272D',
registrationForm: true,
room: null,
visitor: undefined,
triggers: [],
departments: [],
allowSwitchingDepartments: true,
online: true,
offlineColor: '#666666',
offlineMessage: 'We are not online right now. Please leave us a message:',
offlineSuccessMessage: '',
offlineUnavailableMessage: '',
displayOfflineForm: true,
videoCall: false,
offlineTitle: 'Leave a message',
language: '',
transcript: false,
transcriptMessage: 'Would you like a copy of this chat emailed?',
agentData: undefined,
conversationFinishedMessage: 'Conversation finished',
nameFieldRegistrationForm: true,
emailFieldRegistrationForm: true
}
```
# Method: livechat:registerGuest
## DDP message
```javascript
{"msg":"method","method":"livechat:registerGuest","params":[{"token":"TF5rZ7BZ9mZCSq3xN","name":"Guest Name","email":"guest@rocket.chat","department":"3jMKjTQJxCDxwxxtx"}],"id":"5"}
```
## Response
```javascript
{
userId: 'G3DukvFBhDkDnw6uS',
visitor: {
name: 'Guest Name',
token: 'TF5rZ7BZ9mZCSq3xN',
username: 'guest-1',
visitorEmails: [{
address: 'guest@rocket.chat'
}]
}
}
```
# Method: sendMessageLivechat
## DDP message
```javascript
{"msg":"method","method":"sendMessageLivechat","params":[{"_id":"XqEEHhQHvhFmK3Zoz","rid":"TT9iMmzusfcLq8sv2","msg":"test","token":"7T4jzes7rX3Fr6cQ2"}],"id":"11"}
```
The property `_id` should be generated randomly before sending the message.
## Response
```javascript
{
"_id":"XqEEHhQHvhFmK3Zoz",
"rid":"TT9iMmzusfcLq8sv2",
"msg":"test",
"token":"7T4jzes7rX3Fr6cQ2",
"alias":"poqiqwp1o2",
"ts":{
"$date" :1494874057495