Developers

SDK JS-Client

Introduction

Instead of loading the SDK, you can use this helper in javascript to use the API.

Setup

Before you use the js-client, see Finding your API credentials in the Help Center to obtain your credentials. These credentials are project-specific. For more information, see the Authorization section.

Please review the API documentation carefully before using the helper.

Note

All examples shown are set in a Production environment.

Integration

  1. First, include the javascript file somewhere on your page:

    • If you need compatibility with IE11 browsers, use the version with polyfills:

      <script src="https://sdk.inbenta.io/chatbot/1/inbenta-chatbot-sdk.js"></script>
    • If you do not need compatibility with IE11 browsers, you can use the version without polyfills:

      <script src="https://sdk.inbenta.io/chatbot/1/inbenta-chatbot-sdk-no-polyfills.js"></script>
  2. Then, proceed with the authorization, just as if you were using the SDK.

    Caution

    Your Secret must remain confidential. To prevent third parties from accessing your API, always perform this request in a server-side environment. Never expose your secret in client-side integrations.

    After performing the authorization, you get an access token with the following format:

      AuthResponse={
      <your_access_token>
      <expiration>
      };

Creation

If you completed the authorization server-side, you can now initiate the API client:

You can now define the API Configuration, which sets the headers, environment, userType and bot configuration. For more information, see the /conversation endpoint section.

The following example shows how to define which Chatbot App attributes the API returns after a user asks a question, and the maximum number of related contents that should appear:

APIConfig = {
  answers:{
    answerAttributes: ['ANSWER_TEXT'],
    sideBubbleAttributes: ['SIDEBUBBLE_TEXT'],
    maxRelatedContents: 3
  },
};
  APIPromise = InbentaChatbotSDK.apiClient(<AuthResponse>,<APIConfig>,<your_API_key>);

Using the client

Now that the API client is created, you need to wait for the API Promise to be ready, which will complete the set-up returning the chatbotAPI object:

  APIPromise.then((chatbotAPI) => {
   //API calls start here
   }

You can then execute startConversation, which will use the bot configuration used to create the API Client. For more information on available configurations, see the payload/conversation endpoint section.

chatbotAPI.startConversation().then(function()
{
  //start asking the API with conversation method
}

Finally, after completing the session set-up, you can start asking the API questions:

ChatbotAPI.conversation('My first question');

Full Application example code

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Demo</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" />
      <script src="https://sdk.inbenta.io/chatbot/1/inbenta-chatbot-sdk.js"></script>
</head>
<body>
</body>
</html>
<script>
  var accessToken={
    accessToken:<your_access_token> //Response form server-side Authorization
  };
  botConfig = {
    environment: "development",
    lang:'en',
    answers:{
      answerAttributes: ['ANSWER_TEXT'],
      sideBubbleAttributes: ['SIDEBUBBLE_TEXT'],
      maxRelatedContents: 3
    },
  };

  var queryForPolarQuestion = 'baggage';
  var queryForMultipleChoiceQuestion = 'special meals';
  var queryForSimpleAnswer = 'vegan meals';

  APIPromise = InbentaChatbotSDK.apiClient(accessToken,botConfig,"<?echo $key?>");
  APIPromise.then((chatbotAPI)=> {
    chatbotAPI.startConversation().then(function(response){
      // set a variable
      chatbotAPI.addVariable('first_name', 'NewName', true);
      // send a message
      chatbotAPI.conversation(queryForSimpleAnswer).then(function(response){
        console.log(response.data);
        // get the last answer
        var lastAnswer = response.data;
        // if there are many answers choose only the last one
        if(response.data.answers) {
          lastAnswer = response.data.answers[response.data.answers.length-1];
        }
        // console.log(lastAnswer);
        switch (lastAnswer.type) {
          case "multipleChoiceQuestion":
            console.log("multiple choice question received");
            // choose one option randomly
            var options = lastAnswer.options;
            var choosedOption = options[Math.floor(Math.random() * options.length) % options.length];
            console.log(choosedOption);
            chatbotAPI.conversation(choosedOption.label, choosedOption.value).then(function(response){
              console.log("'"+choosedOption.label+"' selected");
              console.log(response.data);
              // rate the content
              if(response.data.parameters.contents.trackingCode) {
                chatbotAPI.rateContent(response.data.parameters.contents.trackingCode.rateCode, 1);
              }
            });
            break;
          case "polarQuestion":
            console.log("polar question received");
            // choose yes
            var choosedOption = "yes";
            chatbotAPI.conversation(choosedOption, choosedOption).then(function(response){
              console.log("'yes' selected");
              console.log(response.data);
            });
            break;
          case "answer":
            console.log("simple answer received");
            break;
          default:
            break;
        }
      });
    });
  });

</script>

API Config

The client configuration will affect all the methods.

Name Type Default Description
userType integer 0 Defines the profile identifier from the Chatbot App's Knowledge Base. It will be used in the client as a x-inbenta-user-type header to make API requests. For more information about this header, see the API Routes.
environment String production Defines source environment from the Chatbot App's Knowledge Base. It will be used in the client as a x-inbenta-env header. For more information about this header, see the API Routes.

Methods

The methods page is available here.

Libraries and Browser Support

The JavaScript SDK depends on:

  • vue 2.7.14
  • axios 0.26.1
  • CORS

The following browsers are supported:

  • IE 11+ (only in the Chatbot SDK version with polyfills)
  • Last version of self-updating browsers:
    • Chrome
    • Firefox
    • Safari
    • Edge