NAV Navigation
Shell Node.js HTTP

Alvaria™ Cloud Streaming Public Chat Client REST API v2.0.1

Scroll down for code samples, example requests and responses. Select a language for code samples from the tabs above or the mobile navigation menu.

Overview

The Alvaria™ Cloud Streaming Public Chat Client REST APIs enable a custom Chat application to register for, and receive events from, the Alvaria™ Cloud system. Events are retrieved by long polling, the session will be dropped by the server if a call to getEvents has not been received within the inactivityDelay (default 60 seconds). Backoff procedures should be implemented for when error conditions occur (e.g. network outages, throttling, etc).

Note: These endpoints are for unauthenticated customers, not authenticated Agents. Agent sessions are defined in Alvaria™ Cloud Streaming REST API

Steps to establish a Chat session

Get Web Token

The first step is to get an Alvaria™ Web Token, which provides organization and IP based rate limiting without requiring a user login. The return value's tokenId is used as the Bearer token in all subsequent REST calls.

The Alvaria™ Web Token is defined in Alvaria™ Cloud Web Token REST API.

  // Alvaria™ Web Token example response
  {
    "tokenId": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJvcmdJZCI6InBhdHMiLCJpYXQiOjE1NzYxNzc1MDQsImV4cCI6MTU3NjE4MTEwNH0.5AGaoYV0bw6bwC6NiIIK0eS5-yMbszHHN3Cnf1PMvOE",
    "expirationTime": "2020-06-02T20:28:30Z"
  }

Establish a Streaming session

// Alvaria™ Public Web Streaming Create Session example response
{
  "sessionId": "ab7dbcbc-c041-4ac0-8ca0-5a0961f7be5",
  "creationTime": "1985-04-12T23:20:50.525Z",
  "inactivityDelay": 60
}

The end-user's browser receives server-side messages (from an agent or a self-service script) using long polling. This is initialized by creating a Streaming session to the Create Session endpoint, which responds with a Streaming sessionId. Each poll request must contain this Streaming sessionId and previously created Alvaria Web Token tokenId.

To create a Streaming sessionId, the following endpoint requires the newly created tokenId. The Streaming endpoint will internally validate the tokenId before returning a 200 OK and the Streaming sessionId. We have a default server-side Streaming session timeout of 60 seconds, which will clean up server-side session information if the end-user's browser is closed and stops polling for messages. This timeout is of particular importance to mobile web browsers and desktop browsers where the end-user will navigate to a different tab or window. Each browser implements power saving differently, so there is no guarantee a browser will continue to send long polling messages if the current browser tab/window is not active. The default timeout can be overridden during Streaming session initialization if 60 seconds is insufficient.

After establishing a streaming session, we have a tokenId and a value for via-client-sessionid, which will be passed on all subsequent REST calls to the server.

Long Polling

// jQuery example
function LongPoll() {
  var orgId = "viademo"
  var tokenURL = new URL("https://" + orgId + ".via.aspect-cloud.net/via/v2/organizations/" + orgId + "/streaming/events/webClient?maxEvents=1")
  // Example: https://viademo.via.aspect-cloud.net/via/v2/organizations/viademo/streaming/events/webClient?maxEvents=1

  return $.ajax({
      url: tokenURL,
      type: 'GET',
      dataType: 'json',
      crossDomain: true,
      xhrFields: {
        withCredentials: false          // Needs to be false in order to allow cross domain calls to our endpoint.
      },
      beforeSend: function(xhr) {
        xhr.setRequestHeader('Authorization', 'Bearer ' + tokenId)
      },
      headers: {
        'Accept': 'application/json',
        'x-api-key': string,            // Unique to each organization.
        'via-client-sessionid': string
      },
      success: function(result) {
        if (result.totalItems && result.totalItems > 0) {
          for (const event of result.events) {
            const messageObject = JSON.parse(event.payload)
          }
        }
        // If there are no events on the server side queue after 15 seconds, 
        // the server will respond with "totalItems": 0 in the JSON payload.

        // Either way, time for the next long poll to the server
        LongPoll();
      },
      error: function(error) {
        if (error && error.responseJSON.code == 429 || error.responseJSON.code === 500)) {
          // Too many requests or server side issue - wait and try again
          window.setTimeout(LongPoll(), 5000);
        }
        else {
          // Session was closed server-side. Clean up chat session on client side, s 
          // and stop long polling server.
        }
      }
  });
}

To retrieve server-side messages, a long polling loop should be implemented. If no messages are available after 15 seconds, the REST GET request will return with an empty event array (see below for examples with and without an event from the server). Another GET request should be sent immediately after the response. If there are server-side messages to be retrieved within the 15 second window, it will be immediately returned and another GET request should also be sent immediately.

Multiple events can be requested from the server in each request using the URL parameter maxEvents, which will return an array of events, but for this example we will request one event.

Connect to Messaging

  // Example connect body for Web Chat sessions
  requestBody = {
    "workTypeId": 79,
    "contactName": "Ryan Tucker",
    "contactEmail": "Ryan.Tucker@alvaria.com",
    "contactDataCollection": [{
      "contactDataKey": "szUserDefined1",
      "contactDataValue": "12345"
    }]
  }

To send messages to the server, the Alvaria Messaging endpoint is used. The Alvaria Web Token and Streaming sessionId from the previous two steps needs to be passed in each message.

Messaging for WebChat

For Web Chat sessions, the Connect message body must contain the workTypeId so the session can be properly routed and a contactName to be displayed to the Agent. Optional fields include an contactEmail address and an array of up to 20 UserDefined fields.

Messaging for scheduling a Voice Call Back

// Example scheduleCallBack body for Voice Call Back
requestBody = {
  "workTypeId": 32,
  "contactName": "Joe Bloggs",
  "digits": "555 1234",
  "callBackTime": "2017-11-12T18:00:00.000Z",
  "delayStartDuration": 30,
  "contactDataCollection": [{
    "contactDataKey": "Account Number",
    "contactDataValue": "1234-5678-9999"
  }]
}

For Voice Call Back, the Schedule message body must contain the workTypeId so the session can be properly routed to an Outbound Voice WorkType, a contactName to be displayed to the Agent, a phone number (digits) the agent should call, and either a specific timestamp (callBackTime) when, or number of minutes (delayStartDuration) until, the call should be made. Optionally, an array of up to 20 UserDefined fields can be added.

Alvaria™ Messaging is defined in Alvaria™ Cloud Messaging Public Chat Client REST API.

Ending a WebChat session

The client can end a Web Chat session one of two ways. The preferred method is to send a POST to the messaging Disconnect endpoint, which will immediately send a wrap message to the Agent (if there is one in the session), and properly dispose server-side resources related to the session. The other method is to stop sending long poll GET requests for more than sixty seconds or the value of the inactivityDelay override parameter optionally passed on session initialization. In this case, the server will wait the specified inactivityDelay seconds before cleaning up the session.

Use cases for the second method include the customer closing the browser/tab associated with the long polling requests, network disconnect, or the browser entering a sleep/power save state due to the end-user no longer focusing on the browser/tab. See Create Session for more details.

Troubleshooting

If you receive 401 status from the GET Get Events endpoint and it contains the content shown in the panel to the right:

  {
    "message": "Invalid or expired session"
  }

You must create a new streaming session using the POST Create Session endpoint. Do not use the sessionId that caused the error in any further streaming API calls.

More Information

To see all Alvaria™ Cloud API documentation, see the Alvaria™ Cloud REST API Developer's Guide.

Base URLs:

License: License: Creative Commons Attribution 4.0 International Public License

Authentication

Session

Create Streaming Session

Code samples

# You can also use wget
curl -X POST https://org.via.aspect-cloud.net/via/v2/organizations/{orgId}/streaming/session/webClient \
  -H 'Content-Type: application/json' \
  -H 'Accept: application/json' \
  -H 'x-api-key: string' \
  -H 'Authorization: API_KEY'

const fetch = require('node-fetch');
const inputBody = [
  {
    "propertyName": "Context",
    "propertyValue": "ba8a90bc000d1e"
  }
];
const headers = {
  'Content-Type':'application/json',
  'Accept':'application/json',
  'x-api-key':'string',
  'Authorization':'API_KEY'
};

fetch('https://org.via.aspect-cloud.net/via/v2/organizations/{orgId}/streaming/session/webClient',
{
  method: 'POST',
  body: JSON.stringify(inputBody),
  headers: headers
})
.then(function(res) {
    return res.json();
}).then(function(body) {
    console.log(body);
});

POST https://org.via.aspect-cloud.net/via/v2/organizations/{orgId}/streaming/session/webClient HTTP/1.1
Host: org.via.aspect-cloud.net
Content-Type: application/json
Accept: application/json
x-api-key: string

POST /via/v2/organizations/{orgId}/streaming/session/webClient

Creates a new Streaming Session

Body parameter

[
  {
    "propertyName": "Context",
    "propertyValue": "ba8a90bc000d1e"
  }
]

Parameters

Name In Type Required Description
orgId path string true Name of customer organization.
x-api-key header string true Alvaria-provided value used to track API endpoint usage
body body NewSession false Name/Value pairs that will be stored within the Session and can be accessed for channel specific functionality.

Example responses

200 Response

{
  "sessionId": "ab7dbcbc-c041-4ac0-8ca0-5a0961f7be5",
  "creationTime": "1985-04-12T23:20:50.525Z",
  "inactivityDelay": 60
}

Responses

Status Meaning Description Schema
200 OK OK SessionResponse
400 Bad Request Bad Request ErrorResponse
401 Unauthorized Unauthorized None
404 Not Found Not Found ErrorResponse
405 Method Not Allowed Method Not Allowed ErrorResponse
429 Too Many Requests Too Many Requests ErrorResponse
500 Internal Server Error Internal Server Error ErrorResponse

Response Headers

Status Header Type Format Description
200 Access-Control-Allow-Origin string none

Delete Streaming Session

Code samples

# You can also use wget
curl -X DELETE https://org.via.aspect-cloud.net/via/v2/organizations/{orgId}/streaming/session/webClient \
  -H 'Accept: application/json' \
  -H 'x-api-key: string' \
  -H 'via-client-sessionid: string' \
  -H 'Authorization: API_KEY'

const fetch = require('node-fetch');

const headers = {
  'Accept':'application/json',
  'x-api-key':'string',
  'via-client-sessionid':'string',
  'Authorization':'API_KEY'
};

fetch('https://org.via.aspect-cloud.net/via/v2/organizations/{orgId}/streaming/session/webClient',
{
  method: 'DELETE',

  headers: headers
})
.then(function(res) {
    return res.json();
}).then(function(body) {
    console.log(body);
});

DELETE https://org.via.aspect-cloud.net/via/v2/organizations/{orgId}/streaming/session/webClient HTTP/1.1
Host: org.via.aspect-cloud.net
Accept: application/json
x-api-key: string
via-client-sessionid: string

DELETE /via/v2/organizations/{orgId}/streaming/session/webClient

Deletes an existing Streaming Session

Parameters

Name In Type Required Description
orgId path string true Name of customer organization.
x-api-key header string true Alvaria-provided value used to track API endpoint usage
via-client-sessionid header string true Identifier representing a long-lived HTTP interchange between Alvaria™ Cloud and an entity when the entity is a contact, external client application, or authenticated user. This interchange is called the streaming session. Streaming sessions are used for operations such as exchanging text messages and retrieving events related to user activity.

Example responses

400 Response

{
  "code": 404,
  "message": "",
  "errors": [
    {
      "scope": "scope",
      "reason": "reason",
      "message": "message"
    }
  ]
}

Responses

Status Meaning Description Schema
204 No Content No Content None
400 Bad Request Bad Request ErrorResponse
401 Unauthorized Unauthorized None
404 Not Found Not Found ErrorResponse
405 Method Not Allowed Method Not Allowed ErrorResponse
429 Too Many Requests Too Many Requests ErrorResponse
500 Internal Server Error Internal Server Error ErrorResponse

Response Headers

Status Header Type Format Description
204 Access-Control-Allow-Origin string none

Events

Retrieve Events

Code samples

# You can also use wget
curl -X GET https://org.via.aspect-cloud.net/via/v2/organizations/{orgId}/streaming/events/webClient \
  -H 'Accept: application/json' \
  -H 'via-client-sessionid: string' \
  -H 'x-api-key: string' \
  -H 'Authorization: API_KEY'

const fetch = require('node-fetch');

const headers = {
  'Accept':'application/json',
  'via-client-sessionid':'string',
  'x-api-key':'string',
  'Authorization':'API_KEY'
};

fetch('https://org.via.aspect-cloud.net/via/v2/organizations/{orgId}/streaming/events/webClient',
{
  method: 'GET',

  headers: headers
})
.then(function(res) {
    return res.json();
}).then(function(body) {
    console.log(body);
});

GET https://org.via.aspect-cloud.net/via/v2/organizations/{orgId}/streaming/events/webClient HTTP/1.1
Host: org.via.aspect-cloud.net
Accept: application/json
via-client-sessionid: string
x-api-key: string

GET /via/v2/organizations/{orgId}/streaming/events/webClient

Retrieve events from an existing Streaming Session, this operation will return immediately if any events are available, or will wait for up to 15 seconds for an event to become available.

Parameters

Name In Type Required Description
orgId path string true Name of customer organization.
via-client-sessionid header string true Identifier representing a long-lived HTTP interchange between Alvaria™ Cloud and an entity when the entity is a contact, external client application, or authenticated user. This interchange is called the streaming session. Streaming sessions are used for operations such as exchanging text messages and retrieving events related to user activity.
x-api-key header string true Alvaria-provided value used to track API endpoint usage
maxEvents query integer false Maximum no of events to return (default 1, max 10)

Example responses

200 Response

{
  "kind": "",
  "totalItems": "",
  "events": ""
}

Responses

Status Meaning Description Schema
200 OK OK EventResponse
400 Bad Request Bad Request ErrorResponse
401 Unauthorized Unauthorized None
404 Not Found Not Found ErrorResponse
405 Method Not Allowed Method Not Allowed ErrorResponse
429 Too Many Requests Too Many Requests ErrorResponse
500 Internal Server Error Internal Server Error ErrorResponse

Response Headers

Status Header Type Format Description
200 Access-Control-Allow-Origin string none

Schemas

Error

{
  "scope": "scope",
  "reason": "reason",
  "message": "message"
}

Properties

Name Type Required Restrictions Description
scope string false none none
reason string false none none
message string false none none

ErrorResponse

{
  "code": 404,
  "message": "",
  "errors": [
    {
      "scope": "scope",
      "reason": "reason",
      "message": "message"
    }
  ]
}

Properties

Name Type Required Restrictions Description
code integer false none HTTP error status
message string false none none
errors [Error] false none none

NewSession

[
  {
    "propertyName": "Context",
    "propertyValue": "ba8a90bc000d1e"
  }
]

Properties

Name Type Required Restrictions Description
anonymous [SessionProperty] false none none

SessionProperty

{
  "propertyName": "Context",
  "propertyValue": "ba8a90bc000d1e"
}

Properties

Name Type Required Restrictions Description
propertyName string false none none
propertyValue string false none none

SessionResponse

{
  "sessionId": "ab7dbcbc-c041-4ac0-8ca0-5a0961f7be5",
  "creationTime": "1985-04-12T23:20:50.525Z",
  "inactivityDelay": 60
}

Properties

Name Type Required Restrictions Description
sessionId string false none Alvaria-generated unique identifier for the the Session, to be used in all subsequent Streaming and Messaging api calls.
creationTime string(date-time) false none Time at which the Session was created, specified in ISO 8601 format
inactivityDelay integer false none period of polling inactivity in seconds after which the session will be closed.

EventResponse

{
  "kind": "",
  "totalItems": "",
  "events": ""
}

Properties

Name Type Required Restrictions Description
kind string false none none
totalItems integer false none none
events [EventPayload] false none none

EventPayload

{
  "kind": "",
  "id": "",
  "type": "",
  "eventType": "",
  "publishedTime": "",
  "schemaVersion": "",
  "payload": ""
}

Properties

Name Type Required Restrictions Description
kind string false none none
id string false none Alvaria-generated unique identifier for the event
type string false none Type of the event payload. This property is deprecated. Use eventType instead.
eventType string false none Type of the event payload.
publishedTime string(date-time) false none none
schemaVersion integer false none none
payload string false none none