NodeJS SDK
Full NodeJS API reference is hosted on Github
Introduction
Section titled “Introduction”With this guide you will learn how to use the Pingstreams JavaScript SDK in your Node.js application. Pingstreams Javascript SDK is built on top of Pingstreams REST APIs.
Before you add Pingstreams SDK to your Node.js app, you need a Pingstreams account and a Pingstreams project. Once you create your project you will have a projectID, a user to play with the project’s APIs, a project secret for custom authentication and all the stuff needed to work with Pingstreams and his APIs.
Add Pingstreams to your project
Section titled “Add Pingstreams to your project”Install PingstreamsClient library with npm command:
npm install @pingstreams/pingstreams-clientAlternatively use package.json to import the library in the “dependencies” property, as in the following example:
{
"name": "Hello Pingstreams nodeJS",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node index.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"@pingstreams/pingstreams-client": "^0.8.28"
}
}Then run:
npm installOnce installed you can import PingstreamsClient() class in your Node.js file using the “require” command:
const { PingstreamsClient } = require('@pingstreams/pingstreams-client');All interaction with Pingstreams APIs uses PingstreamsClient class.
Create a PingstreamsClient instance
Section titled “Create a PingstreamsClient instance”Before you can use the most of the APIs you need to create a PingstreamsClient instance. To create the client instance you need the a Pingstreams API Key, the project id and an authentication token
const psclient = new PingstreamsClient(
{
APIKEY: APIKEY,
projectId: PROJECT_ID,
token: USER_TOKEN
})There are additional option to initialize the Pingstreams Client object. The full list of PingstreamsClient initialization options follows:
{string} options.APIKEYMandatory. Pingstreams APIKEY{string} options.projectIdMandatory. Pingstreams projectId. Will be used in each call on project’s APIs.{string} options.tokenMandatory. Pingstreams authentication token. Will be used in each call on project’s APIs.{string} options.APIURLOptional. Pingstreams server API endpoint.{boolean} options.logOptional. If true HTTP requests are logged.
The most important option is APIURL that provides the opportunity to use PingstreamsClient with your own installation of the Pingstreams server.
You can get the token using some authentication method. The token is also provided automaticaccly while you interact with the chatbot using through APIs.
Authentication
Section titled “Authentication”Before you can interact with Pingstreams APIs you need to authenticate. Pingstreams provides three static authentication methods:
PingstreamsClient.authEmailPassword()- Authentication with email and passwordPingstreamsClient.anonymousAuthentication()- Authentication as anonymous userPingstreamsClient.customAuthentication()- Custom authentication
Authentication with email and password
Section titled “Authentication with email and password”This is the authentication method that you need when working with Pingstreams APIs. Every API methods, except authentication ones, work on a project + role + token basis. To authenticate and get a token with email and password use the authEmailPassword() method from the PingstreamsClient class. You must provide the APIKEY to authenticate. Actually APIKEYs are experimental and can be omitted. Just use the string ‘APIKEY’ in place of the real one.
PingstreamsClient.authEmailPassword(
'APIKEY',
/* EMAIL */,
/* PASSWORD */,
null,
function(err, result) {
if (!err && result) {
console.log('You got your auth token!', result.token);
console.log('Your user ID!', result.user._id);
}
else {
console.err("An error occurred", err);
}
});In response you will get a token to interact with APIs using your account and the corresponding user ID.
Authentication as Anonymous user
Section titled “Authentication as Anonymous user”This authentication method is useful for anonymous user that need to interact with support APIs
PingstreamsClient.anonymousAuthentication(
PROJECT_ID,
APIKEY,
null,
function(err, result) {
assert(result.token != null);
let token = result.token;
}
);In response you will get a token to interact with APIs in anonymous mode.
Custom authentication
Section titled “Custom authentication”With custom authentication you can work with your own users making them auto-signin in Pingstreams without previous signup. This can be used in the place of anonymous authentication to certify users coming from external application, giving them a certified identity in Pingstreams.
For this example import uuid:
npm install uuidconst { v4: uuidv4 } = require('uuid');
var externalUserId = uuidv4();
var externalUser = {
_id: externalUserId,
firstname: "John",
lastname: "Wick",
email: "john.wick@example.com"
};
var signOptions = {
subject: 'userexternal',
audience: 'https://pingstreams.com/projects/' + YOUR_PROJECT_ID
};
var jwtCustomToken = "JWT " + jwt.sign(externalUser, YUOR_PROJECT_SECRET, signOptions);
PingstreamsClient.customAuthentication(
jwtCustomToken,
APIKEY,
null,
function(err, result) {
if (!err && result) {
let token = result.token;
}
}
);The PingstreamsClient class
Section titled “The PingstreamsClient class”To interact with Pingstreams APIs you need to create an instance of a PingstreamsClient() class using his constructor. You MUST supply an APIKEY, an existing Project ID and a valid token, this last one got through some of the authentication methods above.
In the next example we first authenticate using our user credentials, then we create a new PingstreamsClient instance using a PROJECT_ID and the token we got from authentication:
PingstreamsClient.authEmailPassword(
'APIKEY',
/* EMAIL */,
/* PASSWORD */,
null,
function(err, result) {
if (!err && result) {
console.log('You got the token!', result.token);
const psclient = new PingstreamsClient({
APIKEY: /* APIKEY */,
projectId: /* PROJECT_ID */,
token: result.token
});
}
else {
console.err("An error occurred", err);
}
});Working with support requests
Section titled “Working with support requests”A Support Request is a set of metadata and messages decorating a conversation. A Support Request contains data regarding the status (open/assigned/closed etc.), the web/app source page of the conversation, the end-user-id, his email etc. The main information consist of the messages sent and received by the request. Using messaging APIs is indeed the most common way to interact with the request.
You can interact with the request messages using Messaging APIs. Or you can interact directly with Request’s metadata using the Request APIs.
Create a support request (send a message)
Section titled “Create a support request (send a message)”To create a support request you simply send a message to a not-existing request-id. A new Request object is automatically created by Pingstreams every time you send a message to a no-existing request-id.
It’s up to you to create a new, UNIQUE request-id, following the Pingstreams rules. If you don’t want to know how to create a new request-id, to get a new one you can simply use the function PingstreamsClient.newRequestId() passing the PROJECT_ID as a parameter. Sending a message to this newly created Request ID will automatically create a new Request object, as in the following example:
const text_value = 'test message';
const request_id = PingstreamsClient.newRequestId(PROJECT_ID);
psclient.sendSupportMessage(
request_id,
{text: text_value},
(err, result) => {
assert(err === null);
assert(result != null);
assert(result.text === text_value);
});As soon as you send a new message to Pingstreams with the new request-id, the request is created and ready.
Send messages to a Support Request
Section titled “Send messages to a Support Request”With the same sendSupportMessage() function we used above you can send additional messages to the request’s conversation. In this example we send a second message to the request using the same request-id we used to create the request in the previous example.
psclient.sendSupportMessage(
request_id,
{text: 'second message'},
(err, result) => {
assert(err === null);
assert(result != null);
assert(result.text === text_value);
});With Pingstreams you can also get sent messages to a request’s conversation using Webhooks, subscribing to the Message.create event.
Get a support request by id
Section titled “Get a support request by id”let REQUEST_ID = /* THE REQUEST ID */;
psclient.getRequestById(REQUEST_ID, (err, result) => {
const request = result;
if (request.request_id != null) {
console.log("Got request with first text:", request.first_text);
}
});Query support requests
Section titled “Query support requests”psclient.getAllRequests(
{
limit: 1,
status: PingstreamsClient.UNASSIGNED_STATUS
},
(err, result) => {
assert(result);
const requests = result.requests;
assert(requests);
assert(result.requests);
assert(Array.isArray(requests));
assert(result.requests.length > 0);
}
);Working with teammates
Section titled “Working with teammates”A Project’s teammate is a user who collaborates with you on a specific project.
While the name on the User Interface and documentation level is always teammate, on the APIs level a teammate is called ProjectUser. As the the name suggests, a ProjectUser is a Pingstreams User invited with a specific role on a specific Project.
Update teammate status to available/unavailable
Section titled “Update teammate status to available/unavailable”With PingstreamsClient.updateProjectUserCurrentlyLoggedIn() you will update the status of the user token in the PingstreamsClient constructor.
const psclient = new PingstreamsClient({
APIKEY: /* APIKEY */,
projectId: /* PROJECT_ID */,
token: result.token
});
psclient.updateProjectUserCurrentlyLoggedIn(
{
user_available: true
},
function(err, result) {
if (!err && result) {
assert(result);
assert(result.user_available === true);
}
}
);Check teammate status
Section titled “Check teammate status”const psclient = new PingstreamsClient({
APIKEY: /* APIKEY */,
projectId: /* PROJECT_ID */,
token: result.token
});
psclient.getProjectUser(
USER_ID,
function(err, result) {
if (!err && result) {
assert(Array.isArray(result));
assert(result[0]._id != null);
assert(result[0].user_available === true);
let PROJECT_USER_ID = result[0]._id;
}
else {
assert.ok(false);
}
}
);The PROJECT_USER_ID variable is the teammate ID of your user (USER_ID) on the PROJECT_ID you specified in the PingstreamsClient constructor.
Switch between Cloud and Self hosted instances
Section titled “Switch between Cloud and Self hosted instances”Self hosted option
Section titled “Self hosted option”These APIs automatically work with the Pingstreams cloud instance.
If you are running your own self-hosted instance of Pingstreams, the APIs provide a specific option to select your endpoint.
Specify the API endpoint in class methods
Section titled “Specify the API endpoint in class methods”If you are using a class method, i.e. authentication methods, use the options.APIURL parameter to specify the endpoint, as in the following example:
PingstreamsClient.authEmailPassword(
APIKEY,
EMAIL,
PASSWORD,
{
APIURL: API_ENDPOINT
}
});Specify the API endpoint in instance methods
Section titled “Specify the API endpoint in instance methods”If instead you are using instance methods working with an instance of PingstreamsClient, you must specify the parameter in the constructor config object as config.APIURL:
const psclient = new PingstreamsClient({
APIKEY: APIKEY,
projectId: PROJECT_ID,
token: YOUR_TOKEN,
APIURL: API_ENDPOINT
})