Reference Guide

Introduction

The IMIconnect SDK for JavaScript contains code and examples designed to enable developers to build applications to programmatically interact with the IMIconnect platform. Using JavaScript SDK you can integrate Real Time and Push Notification messaging capabilities in your web applications.

Overview

The messaging service exposes access to two core message types, Push Notification and Real Time Messaging (RTM).

Push Messaging


The push notification service allows you to send messages to web applications from IMIconnect. The notifications are sent to user’s home screen or to the notification tray. The push notifications are useful for prompting immediate interaction and engaging users that are not currently active in your app.

Real Time Messaging


Real Time Messaging (RTM) service allows you to deliver simple messages to the users application. It uses the publish and subscribe messaging pattern. The senders of the messages are called publishers. The receivers of the messages are called subscribers. The publishers do not program the messages to be sent directly to specific receivers. Instead, they publish the messages to topics.

The app users can subscribe to specific topics. The messages published to specific topics are received by the app users who are subscribed to those topics.

The IMIconnect SDK uses Message Queuing Telemetry Transport (MQTT) protocol to connect with IMIconnect Message Broker and uses publish and subscribe messaging pattern to exchange messages through IMIconnect Message Broker.

All web apps using the IMIconnect SDK are connected to a Message Broker cluster subscribe to a unique channel (user id).

You can use the IMIconnect profile API to query the status of user connection whether connected or disconnected and send relevant messages.

For example, in a banking website, if a customer wish to interact with a customer service team, you can integrate a chat or customer service feedback functionality using the RTM in your website.

Classes

Following are the classes and interfaces of IMIconnect JavaScript SDK:

IMI.Connect


IMIconnect is the core object that interacts with the IMIconnect Message Broker and IMIconnect REST API for messaging service.

Following are the methods available for Push and Real Time Messaging:

Method NamePUSH MessagingReal Time Messaging
connect
disconnect
getPushDetails
getSubscriptions
getTopics
publish
register
sendDRMessage
sendReadReceipt
setConnectReceiver
setLocation
subscribe
unsubscribe

connect


This method is used to initiate a connection between web app and IMIconnect Message Broker to send (publish) or receive real-time messages.

Syntax: connect (userName, password)

📘
  • If the app is not registered, this method will throw NotRegistered error message.

  • If the app is not allowed for real-time messaging, this method will throw FeatureNotSupported error message.
  • If the app is connected to Message Broker, IMIconnect SDK will keep the connection live until you invoke the disconnect() method.

Parameters:

ParameterTypeDescription
userNameStringSpecifies the username to authenticate the user.
passwordStringSpecifies the app secret key to authenticate the user.

Example:

var appId = "webapp6666";
var appSecret = "2016-06-0715:16:58.596";
var userId = "2130";


var options = {
    onConnectionChange: function(msg) {
        console.log("called onConnectionChange :" + msg);


    },
    onMessageArrived: function(msg) {
        console.log(msg);

    }
};

var client = new IMI.Client(appId, appSecret, options);

var isRegistered = client.isRegistered(userId);
console.log(isRegistered);
if (!isRegistered) {
    client.register(userId, {
        success: function(msg) {
            console.log(msg);
            $(".pushdetails").empty();
            if (msg && msg instanceof Object && msg.pushId) {

            }
        },
        failure: function(err) {
            console.log(err);
        }
    });

} else {
    //connect, if registered
    client.connect(userId, appSecret);
}

disconnect


This method is used to disconnect the connection between the web app and the IMIconnect Message Broker.

Syntax: disconnect ()

📘

For any reason, if you disconnect the connection, you must invoke connect() method to reconnect to IMIconnect Message Broker.

Parameters:

None

Example:

try {
    client.disconnect();

} catch (ex) {}

getPushDetails


This method is used to get the web push details of the browser when the app is registered to push. The push details are returned as an object to the callback function.

Syntax: getPushDetails(callbackfunction)

Parameters:

ParameterTypeDescription
callbackfunctionfunctionSpecifies the callback function with a return object. If the app is not registered, the following is returned:
For chrome, Safari, and Firefox:
{
"status":"1",
"description": "app is not registered, please register"
}If the app is registered , the following is returned:
For Chrome and Safari:{ "status":"0", "pushId": "<push id>" }For Firefox:{ "status":"0", "key":"<secret key>", "pushId": "<push id>" }

Returns:

None

Example:

try {
    client.getSubscriptionDetails(function(obj) {
        if (obj.status === "0") {
            //use push details forther operations based on browser
            console.log(obj.pushId);
        } else {
            console.log("push not registered", obj.description);
        }

    });
} catch (ex) {}

getSubscriptions


This method is used to get the subscriptions details of the given topic.

Syntax: getSubscriptions (topic, Callback)

Parameters:

ParameterTypeDescription
topicStringRetrieves the subscriptions of a topic.
CallbackCallbackOptional. Refer to the Callback object.

Returns:

None

Example:

try {

    var callback = new IMI.Callback();
    callback.onSuccess = function(data) {
            //subscriptions details ,to know who subscribed to particualr topic
			/*
            *
            {
                "total": 1,
                "items": [{
                    "_id": {
                        "$oid": "573efb02e4b0e0beba3fe28a"
                    },
                    "appId": "VE19173112",
                    "userId": "1951",
                    "topic": "Updates/ios",
                    "createdDate": {
                        "$date": "2016-05-20T11:54:42.596Z"
                    }
                }],
                "code": 0
            }
          */
        },
        onFailure = function(data) {
            console.log(data);
        }
    client.getSubscriptions("news", callback);
} catch (ex) {
    console.log(ex);
}

getTopics


This method is used to retrieve the topics subscribed by a subscriber based on the access level criteria.

📘

Topics must be configured in IMIconnect platform under channel configuration by an IMIconnect admin.

Syntax: getTopics (accessLevel, callback)

Parameters:

Method

Type

Description

accessLevel

Number

Specifies the permission to subscribe or publish messages. The options are:

  • 0: Both
  • 1: Read
  • 2: Write
callbackCallbackOptional. Refer to the Callback object.

Example:

try {
    var callback = new IMI.Callback();
    callback.onSuccess = function(data) {
            //topics details will 
			/*
            {
                "total": 1,
                "items": [{
                    "topic": "a",
                    "appId": "VE19173112",
                    "createdBy": "[email protected]",
                    "description": "",
                    "accessLevel": 2,
                    "createdOn": "2016-05-25T04:27:34.347",
                    "updatedOn": "2016-05-25T04:27:34.347"
                }]
            }
            */
        };
        callback.onFailure = function(data) {

            console.log(data);
        };

    //here filter means accessLevel(0-BOTH,1-READ,2-WRITE)
    client.getTopics(2, callback); //accessLevel and callback 

} catch (ex) {
    console.log(ex);
}
{
  "items": [
    {
      "_id": {
        "$oid": "5706428fe4b0741cb6ee1dac"
      },
      "appId": "AppIdComesHere",
      "accessLevel": 1,
      "topic": "TopicName",
      "createdBy": "CreatedByName",
      "createdOn": {
        "$date": "2016-04-07T11:20:47.894Z"
      },
      "updatedOn": {
        "$date": "2016-04-07T11:21:34.977Z"
      },
      "subscribe": 1
    }
  ]
}

publish


This method is used to publish a message to a topic. If the app is unable to connect to IMIconnect Message Broker, then this method will throw NotConnected error message.

Syntax: publish (topic, Message, Callback)

Parameters:

ParameterTypeDescription
topicStringThe topic to which the message has to be published.
MessageMessageSpecifies the text message and properties related to the message. Refer to the Message object.
CallbackCallbackOptional. Refer to the Callback object.

Example:

try {
    var dr = new IMI.Message();
    dr.setProperty("message", "Hii");
    dr.setProperty("channel", "rt");
    dr.setProperty("senderId", "NEWS");

    client.publish("news", msg);

} catch (ex) {
    console.log(ex);
}
try {
    var callback = new IMI.Callback();
    callback.onSuccess = function(data) {

    };
    callback.onFailure = function(data) {
        console.log(data);
    };

    var dr = new IMI.Message();
    dr.setProperty("message", "Hii");
    dr.setProperty("channel", "rt");
    dr.setProperty("senderId", "NEWS");

    client.publish("news", msg, callback);

} catch (ex) {
    console.log(ex);
}

register


This method is used to register a user with IMIconnect platform.

Syntax: register (userId, callback)

📘

Before registering customers through web app, a master profile has to be created using

Create Profile API.

Parameters:

ParameterTypeDescription
userIdStringSpecifies the user name for authentication.
callbackCallbackOptional. Callback for response.

Returns:

The response of registered method is returned using Callback.

Example:

var appId = "webapp6666";
var appSecret = "2016-06-0715:16:58.596";
var userId = "2130";


var options = {
    onConnectionChange: function(msg) {
        console.log("called onConnectionChange :" + msg);


    },
    onMessageArrived: function(msg) {
        console.log(msg);
    }
};
var callback = new IMI.Callback();
    callback.onSuccess = function(data) {
            
        },
        callback.onFailure = function(data) {
            
            console.log(data);
        }
var client = new IMI.Client(appId, appSecret, options);

var isRegistered = client.isRegistered(userId);
console.log(isRegistered);
if (!isRegistered) {
    client.register(userId, callback);

}

sendDRMessage


The method is used to send delivery report details to IMIconnect platform with transaction id.

Syntax: sendDRMessage(tid)

Parameters:

ParameterTypeDescription
tidStringSpecifies the transaction id of the delivery report.

Example:

try {
    client.sendDRMessage("12dsd32sdsds343esddsdsdsdds");

} catch (ex) {
    console.log(ex);
}

sendReadReceipt


This method is used to send read receipt details to IMIconnect platform with transaction id.

Syntax: sendReadReceipt (tid)

Parameters:

ParameterTypeDescription
tidStringSpecifies the transaction id of the delivery report.

Example:

try {
    client.sendReadReceipt("12dsd32sdsds343esddsdsdsdds");

} catch (ex) {
    console.log(ex);
}

setConnectReceiver


This method is used to register the callback to listen different types of events provided in the callback.

Syntax: setConnectReceiver(ConnectReceiver)

Parameters:

ParameterTypeDescription
ConnectReceiverConnectReceiverSpecifies the connect receiver callback.

Example:

try {
    var connectReceiver = new IMI.ConnectReceiver();
    connectReceiver.onConnectionChange = function(msg) {
            console.log("called onConnectionChange :" + msg);


        },
        connectReceiver.onMessageArrived = function(msg) {
            console.log(msg);

        }
}

//this method is for setting the callback for message arrvied and connection changes 
client.setConnectReceiver(connectReceiver);

}
catch (ex) {
    console.log(ex);
}

setLocation


This method is used to publish the location information of a client to IMIconnect platform.

Syntax: setLocation (lat, lang)

ParameterTypeDescription
latIntegerA geographic coordinate that specifies the north-south position of a point on Earth's surface.
longIntegerA geographic coordinate that specifies the east-west position of a point on Earth's surface.

Example:

try {
    client.setLocation(17.43, 78.2656);

} catch (ex) {
    console.log(ex);
}

subscribe


This method allows a user to subscribe to a topic to receive messages.

📘

Message producers are called publishers and message consumers are called subscribers.

Syntax: subscribe (topic, Callback)

Parameters:

ParameterTypeDescription
topicStringThe topic to which the application subscribes to receive messages.
CallbackCallbackOptional. Refer to Callback object.

Example:

try {
    var callback = {
        onSuccess: function(data) {
            //after succesfully subscription
        },
        onFailure: function(data) {
            //if subscription fails
            console.log(data);
        }

    };
    client.subscribe("news", callback);
}

} catch (ex) {
    console.log(ex);
}

unSubscribe


This method is used to stop receiving the messages from the subscribed topic.

Syntax: unSubscribe (topic, callback)

Parameters:

ParameterTypeDescription
topicStringSpecifies the topic name to unsubscribe.
callbackCallbackOptional. Refer to Callback object.

Example:

try {
    var callback = new IMI.Callback();
    callback.onSuccess = function(data) {

    };
    callback.onFailure = function(data) {
        console.log(data);
    };
    client.unSubscribe("news", callback);
}

} catch (ex) {
    console.log(ex);
}

IMI.ConnectReceiver


Connectreceiver is an abstract class that contains the methods to override the default methods.

Following are the methods available for Push and Real Time Messaging:

Method NamePUSH MessagingReal Time Messaging
onConnectionChange
onMessageArrived

onConnectionChange


This method is invoked whenever there is a change in the connection status.

Syntax: onConnectionChange (status_code)

Parameters:

Parameter

Type

Description

state

Number

The available connection states are:

  • 0: connection success
  • 1: connection failed
  • 2: retry connection
  • 3: connection lost

Example:

var options = {
       onConnectionChange: function(status) {
           if (status == 0) {
               //we can write code here subscribe to topic
               client.subscribe("news");
               console.log("connection success");
           } else if (status == 1) {
               console.log("connectfailed");
           } else if (status == 2) {
               console.log("retryconnect");
           } else if (status == 3) {
               console.log("connectionlost");
           }

       },
       onMessageArrived: function(message) {
           try {
               var self = this;
               console.log("onMeassageArrived 108");
               console.log(message);
               if (message.getProperty("senderId") != null) {
                   //some operation based on requirement
               } else {
                   //based on the message, write your logic.
               }

           } catch (err) {
               alert(err);
           }
       };
   }
   var client = new IMI.Client(appId, appSecret, options);
   client.connect("abc", "sds");

onMessageArrived


This method is invoked when a message is received from the IMIconnect Platform.

Syntax: onMessageArrived (message)

Parameters:

ParameterTypeDescription
messageMessageSpecifies the Message object.

Example:

var options = {
       onConnectionChange: function(status) {
           if (status == 0) {
               //we can write code here subscribe to topic
               client.subscribe("news");
               console.log("connection success");
           } else if (status == 1) {
               console.log("connectfailed");
           } else if (status == 2) {
               console.log("retryconnect");
           } else if (status == 3) {
               console.log("connectionlost");
           }

       },
       onMessageArrived: function(message) {
           try {
               var self = this;
               console.log("onMeassageArrived 108");
               console.log(message);
               if (message.getProperty("senderId") != null) {
                   //some operation based on requirement
               } else {
                   //based on the message, write your logic.
               }

           } catch (err) {
               alert(err);
           }
       };
   }
   var client = new IMI.Client(appId, appSecret, options);
   client.connect("abc", "sds");

Contents of Message Object

//RT Message:

{
  "topic": "Topic Name",
  "senderId": "SenderId",
  "type": "inbox",
  "message": "Message Text",
  "userId": "UserId",
  "tid": "56aabfd0-c3da-4609-a418-c5fe43cedfc7",
  "channel": "rt",
  "extras": {
    "customtags": {
      "key1": 1,
      "key2": {
        "subkey": "val"
      },
      "key3": [
        "object3",
        "object4"
      ]
    },
}

IMI.Callback


This class is used by the methods in IMIconnect that returns the response asynchronously.

Following are the methods:

  • onSuccess
  • onFailure

onSuccess


This method is invoked explicitly on receiving the response successfully.

Syntax: onSuccess(result)

Example:

try {

    var callback = new IMI.Callback();
    callback.onSuccess = function(data) {
            //after succesfully subscription
        },
        callback.onFailure = function(data) {
            //if subscription fails
            console.log(data);
        }
    client.subscribe("news", callback);
}

} catch (ex) {
    console.log(ex);
}

onFailure


This method is invoked when IMIconnect platform is unable to receive the response.

Syntax: onFailue(result)

Example:

try {

    var callback = new IMI.Callback();
    callback.onSuccess = function(data) {
            //after succesfully subscription
        },
        callback.onFailure = function(data) {
            //if subscription fails
            console.log(data);
        }
    client.subscribe("news", callback);
}

} catch (ex) {
    console.log(ex);
}

IMI.Message


This class represents message sent or received through RTM channel. It has two class variables.

  • message (Unicode text of the message send or receive)
  • messageid (Unicode id of the message)

Following are the methods:

setProperty


This method allows you to set property to a message object as key value pairs, value can be of any type.

Syntax: setProperty(key, value)

Parameters:

ParameterTypeDescription
keyStringSpecifies the key to identify a particular value.
valueStringSpecifies the value to add to a particular key.

Example:

try {
    var dr = new IMI.Message();
    dr.setProperty("message", "Hii");
    dr.setProperty("channel", "rt");
    dr.setProperty("senderId", "NEWS");

    client.publish("news", msg);

} catch (ex) {
    console.log(ex);
}

getProperty


This method returns the value associated with the key.

Syntax: getProperty(key)

Parameters:

ParameterTypeDescription
keyStringSpecifies the key to identify a particular value.

Error Messages

When an error occurs while using the JavaScript SDK, the following error messages are thrown:

Error MessageDescription
NotRegisteredReturned when the app is not registered with IMIconnect.
NotConnectedReturned when the app is not connected to IMIconnect
FeatureNotSupportedReturned when the feature is not supported in IMIconnect.