Developers

SDK JS-Client

Introduction

Inbenta's Live Chat solution is integrated with the Chatbot SDK using an Adapter to allow easy integration. This fulfills the needs of the majority of integrations. However, if you need to add additional logic to your system, customize features or even make a completely customized new integration, this Javascript client helps you reach this objective.

This client allows you to easily use the HyperChat API and WebSockets connection and events. This way, you only need to take care of your app's logic, without having to worry aboupost communicating with the service.

Setup

Integration

First, you must include the Inbenta HyperChat JS-client script in your page:

<script src="https://sdk.inbenta.chat/<version>/icf.sdk.js"></script>
Important

Please keep in mind that Inbenta APIs accept HTTPS requests only. If you need to send API requests using other protocols, the only way to do this is to set up a proxy to convert those protocols to the HTTPS protocol before the requests reach the API.

Versions

When you set up the SDK for your Inbenta product, you must specify the version, like this:

<script src="https://sdk.inbenta.chat/<version>/icf.sdk.js"></script>

Versions are written in MAJOR.MINOR.PATCH format.

Important:

  • Do NOT cache or store these files, otherwise you will not benefit from bug fixing and minor upgrades.
  • Inbenta strongly recommends that you use a MAJOR.MINOR.PATCH version.

Examples

  • If only MAJOR is set, this script will use the highest available MINOR version.
    <script src="https://sdk.inbenta.chat/1/icf.sdk.js"></script>
  • If MAJOR.MINOR are set, this script will use the highest available PATCH version.
    <script src="https://sdk.inbenta.chat/1.2/icf.sdk.js"></script>
  • If you specify the full version, only this exact version will be used.
    <script src="https://sdk.inbenta.chat/1.2.1/icf.sdk.js" integrity="sha384-HX7URD8h+vFpkF4+HLCIo1iWxlX77LYpn+idlbT186yWaietugo0I0ghEhFr0nPH" crossorigin="anonymous"></script>

Note: An SRI check is available for this SDK. For more information, see the SDK Subresource Integrity page. Remember that SRI only works with full versions.

Initialization

Next, initialize the client (ICF) using your HyperChat app id and the region the app belongs to.

ICF.init({
    appId: '<appId>',
    region: '<region>',
});
Asynchronous load and initialization script

Alternatively, you can also use the following script to load the SDK script and initialize the client asynchronously:

<script>
   const icfAsyncInit = () => {
        ICF.init({
            appId: '<appId>',
            region: '<region>',
        });
    };

    const version = '1'; // this is the version that will be downloaded
    (function(d, s, id, v){
        let js, ijs = d.getElementsByTagName(s)[0];
        if (d.getElementById(id)) {return;}
        js = d.createElement(s); js.id = id;
        js.src = '//sdk.inbenta.chat/'+v+'/icf.sdk.js';
        js.onload=icfAsyncInit;
        ijs.parentNode.insertBefore(js, ijs);
    }(document, 'script', 'inbenta-jssdk', version));
</script>

Using the client

Signing up a user

You can signup as a new user by making the following request:

ICF.Api.request('/users/', 'POST', { name: "<your user name>" })
    .then((response) => {
        console.log('User successfully created!', response.data);
    })
    .catch((error) => {
        console.error('Some error occurred…', error);
    });

The response object on success will have the following structure:

{
  "data": {
    "user": {
      "created": 1476712613,
      "name": "<your user name>",
      "contact": "unknown@chat.inbenta.com",
      "status": "online",
      "provider": "inbenta",
      "providerId": "",
      "extraInfo": {},
      "invitations": [],
      "rejections": [],
      "chats": [],
      "lastActivity": 1476712613,
      "id": "<your_user_id>"  // This is your user id, you'll need it later
    },
    "session": {
      "token": "<your_brand_new_session_token>",  // This is your session token, you might need this as well
      "expiration_date": <timestamp>
    }
  }
}
Initializing the user's Lobby

The user's Lobby handles chats for a user (invitations actions and events and other events). It is initialized like this:

ICF.Lobby.init({
    id: "<userId>",
    token: "<sessionToken>",
})
    .then(() => {
        // Lobby has been initialized
    });

After initializing the Lobby, calling ICF.Connection.me() should have an object with the user information.

Initializing a chat

To initialize a chat, you can pass the room as your target room:

ICF.Chat.init({
    'room': '1',
}).then((chat) => {
    console.log('Your brand new chat:', chat);
}).catch((err) => {
    console.log('Some error occurred…', err);
});

To see all the parameters that you can pass to the chat initialization method, and the response object, click here

Sending messages

You can send a message like this:

ICF.Lobby.chats["<chatId"].sendMessage('Hello world!')
    .then((msg) => {
      console.log('Just sent a message:', msg);
    })
    .catch((err) => {
      console.log('Some error occurred…', err);
    });
Listening to Chat events

A chat eventually emits events that contain data. For example, this is how you can handle a 'message:received' event:

ICF.Lobby.chats["<chatId>"]
    .on('message:received', (data) => {
        console.log("Let's show this message in our interface!", data);
    });

For more information about Chat events and related information, click here

Listening to Lobby events

The Lobby eventually emits events that contain data. For example, this is how you can handle a 'chat:remove' event:

ICF.Lobby.addEventListener('chat:remove', (data) => {
    console.log("Let's handle a chat removal!", data);
});

For more information about Lobby events and related information, click here

Full working example

<!DOCTYPE HTML>
<html>
    <head>
        <meta charset="utf-8" />
    </head>
    <body>
        <script type="text/javascript">
            var sdkVersion = '1'; // this is the version that will be downloaded

            function icfAsyncInit() {
                ICF.init({
                    appId: '{appId}'
                }).then(() => {
                    if (ICF.isInit) {
                        window.ICF = ICF;
                        window.dispatchEvent(new Event('icf-ready'));
                    }
                });
            }

            (function(d, s, id, v){
                var js, ijs = d.getElementsByTagName(s)[0];
                if (d.getElementById(id)) {return;}
                js = d.createElement(s); js.id = id;
                js.src = "https://sdk.inbenta.chat/"+v+"/icf.sdk.js";
                js.onload=icfAsyncInit;
                ijs.parentNode.insertBefore(js, ijs);
            }(document, 'script', 'inbenta-jssdk', sdkVersion));

        </script>

    </body>
    <script>
        window.addEventListener('icf-ready', function (e) {

            ICF.Api.request('/users', 'POST', { name: "chatman" })
                .then((response) => {
                    console.log('User successfully created!', response);
                    let userId = response.data.user.id;
                    let token = response.data.session.token;
                    return { userId, token };
                })
                .then((data) => {
                    // initialize user Lobby (this opens a socket connection)
                    return ICF.Lobby.init({
                        id: data.userId,
                        token: data.token
                    });
                })
                .then(() => {
                    // start a chat
                    return ICF.Chat.init({
                        'room': '1',
                        'lang':'en'
                    });
                })
                .then((chat) => {
                    console.log('Chat successfully created!', chat);
                    // if Queue Mode is not active, look for an agent.
                    // with queue mode active, agent search is handled automatically in the server
                    return chat.searchAgent();
                })
                .then((res) => {
                    ICF.Logger.log("Agent " + res.agent.name + " (" + res.agent.id + ") assigned!");
                })
                .catch(err => console.error('Error!', err));

        }, false);
    </script>
</html>

Methods, events and properties

The methods, events and properties page for the Chat object are available here.

The methods, events and properties page for the Lobby object are available here.

The methods, events and properties page for the API object are available here.

The methods, events and properties page for the Events object are available here.

The methods, events and properties page for the Diagnoser object are available here.

The JS client has a Helper object with useful functions. The methods page for the Helper object is available here.