This module handles the SDK initialization and registration. This module has the following classes:
This class contains the methods to initialize the SDK and register a user. When integrating the SDK into your app it is mandatory to use this class to initialize the SDK before any other features are used. With the exception of the Authentication module, it is also necessary to register a user before other features are used.
startup
This method is used to initialize the SDK with configuration as per ‘default’ configuration in the imi-environments.js file.
Syntax: startup()
IMI.IMIconnect.startup();
shutdown
This method is used to clean up the SDK, freeing all internal object instances. Invoking this method will stop the SDK features from functioning and as such RTM will no longer be received.
Syntax: shutdown()
// Provides a means to shutdown the SDK and perform cleanup, after this method is called none of the SDK features will work
try {
IMI.IMIconnect.shutdown();
} catch (error) {
console.log(error)
}
register
This method is used to register the userId with imiconnect. This method reads the device details and sent to the imiconnect platform. Once a user is registered all further SDK calls take place in the context of that user.
Syntax: register(deviceProfile, regcallback)
Parameters:
deviceProfile
[ICDeviceProfile]
Specifies the device profile registered with imiconnect.
regcallback
Object
Refer to example below.
**
//Verify whether the user is registered or not, if not registered, register the user.
if (!IMI.IMIconnect.isRegistered()) {
var callback = {
onSuccess: function(data) {
console.log("reg success",datauserId);
//Write you code to connect to imiconnect.
},
onFailure: function(errormsg) {
console.log("reg failed");
}
};
var deviceProfile=new IMI.ICDeviceProfile(deviceId, userId);
//here user id is optional (If user id not there user can call deviceID,
userId will be generated by imiconnect and passed to callback function)
//var deviceProfile = new IMI.ICDeviceProfile(deviceId);
IMI.IMIconnect.register(deviceProfile, callback);
}
else{
//Write you code to connect to imiconnect.
}
unregister
This method is used to unregister the current user. The features that rely on a registered user will no longer function after this method has been called.
Syntax: IMI.IMIconnect.unregister(unregisterCallback);
unregisterCallback
Callback
var unregisterCallback = {
onSuccess: function (msg) {
console.log("de register...");
},
onFailure: function (err) {
console.log("failed to un register");
}
};
IMI.IMIconnect.unregister(unregisterCallback );
isRegistered
This method is used to check whether the user is currently registered with imiconnect.
Syntax: boolean isRegistered()
Returns:
Returns true if the user is registered, else false is returned.
**
var isRegistered = IMI.IMIconnect.isRegistered();
updateProfileData
This method is used to update userID and customerID parameters of current device profile registered with imiconnect.
To update UserID
Syntax: IMI.IMIconnect.updateProfileData(IMI.ICDeviceProfileParam.UserId, newuserid, userIdcallbck);
Parameters:
DeviceProfileParam
IMI.ICDeviceProfileParam.UserId
Specifies the user ID to register with imiconnect.
newUserId
String
Specifies the new user ID to register with imiconnect.
userIdcallback
Object
Refer to example below.
To update CustomerID
Syntax: IMI.IMIconnect.updateProfileData(IMI.ICDeviceProfileParam.CustomerId, newcustomerid, customerCallback);
Parameters:
DeviceProfileParam
IMI.ICDeviceProfileParam.CustomerId
Specifies the customer ID to register with imiconnect.
newcustomerId
String
Specifies the new customer ID to register with imiconnect.
customerCallback
Object
Refer to example below.
var userIdcallbck = {
onSuccess: function (msg) {
console.log("usermodified...");
},
onFailure: function (err) {
console.log("failed to add user");
}
};
IMI.IMIconnect.updateProfileData(IMI.ICDeviceProfileParam.UserId, "2130", userIdcallbck);
var customerCallback = {
onSuccess: function (msg) {
console.log("customer...");
$("#setCustomerModel").modal('hide');
},
onFailure: function (err) {
console.log("failed to add customer");
alert(err)
}
};
IMI.IMIconnect.updateProfileData(IMI.ICDeviceProfileParam.CustomerId, "2130", customerCallback);
removeProfileData
This method is used to remove the profile data (user ID or customer ID).
To Remove UserID
This method is used to remove the userID.
Syntax: IMI.IMIconnect.removeProfileData(IMI.ICDeviceProfileParam.UserId, removeUserCallback);
Parameters:
DeviceProfileParam
IMI.ICDeviceProfileParam.UserId
Specifies the user ID to register with imiconnect.
removeUserCallback
Object
Refer to example below.
To Remove customerID
This method is used to remove the userID.
Syntax: IMI.IMIconnect.removeProfileData(IMI.ICDeviceProfileParam.CustomerId, CustomerIdcallbck);
Returns:
Returns customerId.
Parameters:
DeviceProfileParam
IMI.ICDeviceProfileParam.CustomerId
Specifies the customer ID to register with imiconnect.
customerIdcallback
Callback
Refer to example below.
var removeUserCallback = {
onSuccess: function (resrmsg) {
console.log("remove userId...");
},
onFailure: function (err) {
console.log("failed to remove customerid..");
}
};
IMI.IMIconnect.removeProfileData(IMI.ICDeviceProfileParam.UserId, userIdcallbck);
var CustomerIdcallbck = {
onSuccess: function (msg) {
console.log("usermodified...");
},
onFailure: function (err) {
console.log("failed to add user");
}
};
IMI.IMIconnect.removeProfileData(IMI.ICDeviceProfileParam.CustomerId, customerCallback);
setSecurityToken
This method allows to specify the security token that the SDK will pass to the imiconnect platform.
Syntax: setSecurityToken(token)
//generate token and call the below method using the token
IMI.IMIconnect.setSecurityToken(token);
registerListener
This method has been deprecated. Please use registerSecurityTokenListener
This method allows registering an object which implements the onFailure
method to listen for security token related exceptions which occur from internal (indirect) connect platform API calls.
Syntax: registerListener(callbackListener)
Parameters:
callbackListener
Security Token Exception listener object.
var callback= {
onFailure: function () {
console.log("token got expired...");
alert("token got expired...");
//need to generate token your (for more information, refer to docs) }
};
//this method should be called after startup()
IMI.IMIconnect.registerListener(callback);
registerSecurityTokenListener
This method allows registering an object which implements the onFailure
method to listen for security token related exceptions which occur from internal (indirect) connect platform API calls.
Syntax: registerSecurityTokenListener(callbackListener)
Parameters:
callbackListener
Security Token Exception listener object.
var callback= {
onFailure: function () {
console.log("token got expired...");
alert("token got expired...");
//need to generate token your (for more information, refer to docs) }
};
//this method should be called after startup()
IMI.IMIconnect.registerSecurityTokenListener(callback);
unregisterListener
This method has been deprecated. Please use unRegisterSecurityTokenListener
This method allows unregistering a previously registered object in order to stop listening for security token exceptions.
Syntax: unregisterListener(callbackListener)
Parameters:
callbackListener
Security Token Exception listener object.
var callbackListener={
onFailure:function(error){
//This method will be called when security token issues comes
}
}
IMI.IMIconnect.unregisterListener(callback);
unRegisterSecurityTokenListener
This method allows unregistering a previously registered object in order to stop listening for security token exceptions.
Syntax: unRegisterSecurityTokenListener(callbackListener)
Parameters:
callbackListener
Security Token Exception listener object.
var callbackListener={
onFailure:function(error){
//This method will be called when security token issues comes
}
}
IMI.IMIconnect.unRegisterSecurityTokenListener(callback);
An ICDeviceProfile instance should be instantiated to register a device profile.
The developer can choose to register the device profile with a deviceId
only or with a deviceId
and an appUserId
. Users' can generate their own device ID or can choose the default deviceId
provided by the SDK.
If the user chooses to register a device profile with the deviceId
only, then the backend will automatically generate an appUserId
.
The current device profile is accessible via the imiconnect class.
Public Methods | |
---|---|
String | getDefaultDeviceId() |
String | isAppUserSystemGenerated() |
String | getUserId() |
String | getDeviceId() |
ICDeviceProfile()
The current device profile, which is accessible via the IMIconnect class.
Syntax: ICDeviceProfile(deviceId, userId)
Syntax: ICDeviceProfile(deviceId, userId, customerId, isSystemGenerated)
Parameters:
deviceId
Property
Specifies the device ID that is created in imiconnect.
userId
Property
Specifies the user ID that is created in imiconnect.
customerId
Property
Specifies the customer ID that is created in imiconnect.
isSystemGenerated
Property
Indicates if the device ID is system generated.
var deviceId=IMI.ICDeviceProfile.getDefaultDeviceId();
var deviceProfile =new IMI.ICDeviceProfile(deviceId, userId);
var deviceProfile =new IMI.ICDeviceProfile(deviceId, userId, customerId, isSystemGenerated);
isAppUserSystemGenerated()
This method is used to know whether the appuserId is generated by the end-system or the user.
Syntax: String isAppUserSystemGenerated()
Return Value:
Returns the appuserid.
**
var deviceProfile =new IMI.ICDeviceProfile(deviceId, userId);
var isAppUserSystemGenerated=deviceProfile.isAppUserSystemGenerated(); if(isAppUserSystemGenerated)
{
console.log("system generated appuser");
}
getUserId()
This method is used to get the user ID.
Syntax: String getUserId()
Return Value:
Returns the userId.
getDeviceId()
This method is used to get the user ID.
Syntax: String getDeviceId()
Return Value:
Returns the deviceId.
uploadFile
This method is used to check the status of the file upload.
Syntax: uploadFile(file, file.type, callback)
Return Value: Returns the file upload status.
onFileUploadComplete
This method is used to execute the callback method after the file upload is complete.
Syntax: onFileUploadComplete: function(file, mediaId, error, resp)
onFileUploadComplete: function(file, mediaId, error, resp){
if(error){
console.log(error);
} else{
$("#mediaid").val(mediaId);
$('#imgPreviewThumb').src("data:image/png;base64," + resp.preview);
}
}
function pubMessage(threadtitle, threadid, msg, mediaId, callback){
----------------
----------------
if(mediaId && mediaId !==""){
var mediaArr = [];
var icAttach = new IMI.ICAttachment();
icAttach.setMediaId(mediaId);
mediaArray.push(icAttach);
message.setAttachment(mediaArray);
}
This module enables publication and receipt of In-app Messages and Push notifications. The usage of this module is optional.
This module has the following classes:
The ICMessaging singleton class facilitates you to send and receive RTM messages and update the read status for RTM and Push.
deleteMessage
Use this method to delete the given message transaction id from the imiconnect platform
messageTransactionId
Tid of the message to be deleted
Syntax: deleteMessage(messageTransactionId, callback);
var callback = {
onSuccess: function (tid) {
debug("message deleted", tid);
},
onFailure: function (error) {
debug("failed", error);
},
};
var messaging = IMI.ICMessaging.getInstance();
messaging.deleteMessage(tid, callback);
connect
This method is used to establish a connection to receive Real-Time Messages from the imiconnect platform.
When the connection is successful, the status events are notified through ICMessagingReceiver.onConnectionStatusChanged
.
It throws an Exception
if a user is not registered with imiconnect or if the RTM feature is not enabled in the policy.
Syntax: connect()
var messaging = IMI.ICMessaging.getInstance();
try {
messaging.connect();
} catch (error) {
console.log(error)
}
disconnect
This method is used to disconnect the connection between the app and the imiconnect platform. If there is no active connection, then this method fails silently.
When the disconnection is successful, the status events are notified through ICMessagingReceiver.onConnectionStatusChanged
.
The disconnect method throws an Exception
if a user is not registered with imiconnect or RTM feature is not enabled in the policy.
Syntax: disconnect()
**
var messaging = IMI.ICMessaging.getInstance();
try {
messaging.disconnect();
} catch (error) {
console.log(error)
}
fetchTopics
This method is used to get a list of topics that are configured with the imiconnect app. Use the filter parameter to control the type of topics that are returned.
Results are reported through a callback.
Syntax: fetchTopics(filter, callback)
Parameters:
callback
JSObject
Specifies the callback object.
**
var messaging = IMI.ICMessaging.getInstance();
var callback = {
onSuccess: function(ictopicslist) {
console.log("success");
//Write your logic to read topics and subscribe/unsubscribe/publish on those topics.
if (ictopicslist) {
for (var i = 0; i < ictopicslist.length; i++) {
var icTopic = ictopicslist[i];
console.log(icTopic.getName());
}
}
},
onFailure: function(errormsg) {
console.log("failed to get topics");
}
};
messaging.fetchTopics(IMI.ICAccessLevelFilter.All, callback);
getConnectionStatus
This method is used to get the current connection status between the SDK and imiconnect platform.
Syntax: ICConnectionStatus getConnectionStatus()
Return Value:
Returns the current connection status between the SDK and the imiconnect platform.
**
var messaging = IMI.ICMessaging.getInstance();
try {
var connectionStatus = messaging.getConnectionStatus();
if (connectionStatus == IMI.ICConnectionStatus.Connected) {
//write your logic here
}
} catch (error) {
console.log(error)
}
getInstance
This method is used to get the ICMessaging
singleton instance. The instance is created internally on demand.
Syntax: ICMessaging getInstance()
Return Value:
Returns the ICMessaging
singleton instance.
**
var messaging = IMI.ICMessaging.getInstance();
isConnected
This method is used to verify whether the RTM connection is established between SDK and imiconnect. This is a convenience method for getConnectionStatus() == ICConnectionStatus.Connected
.
Syntax: boolean isConnected()
Return Value:
Returns true if the RTM connection is established between SDK and imiconnect.
**
var messaging = IMI.ICMessaging.getInstance();
try {
var isConnected = messaging.isConnected();
if (isConnected) {
//write your logic
}
} catch (error) {
console.log(error)
}
publishMessage
This method is used to publish the passed ICMessage
instance through RTM connection.
The results of the operation are reported through a callback.
Syntax: publishMessage(message, callback)
Parameters:
callback
JSObject
Specifies the callback object.
**
var callback = {
onSuccess: function() {
console.log("message sent");
},
onFailure: function(errormsg) {
console.log("failed to send message");
}
};
var messaging = IMI.ICMessaging.getInstance();
var message = new IMI.ICMessage();
message.setMessage("Test message");
var thread = new IMI.ICThread();
thread.setId("threadid <which is created using createThread()/came in Message>");
thread.setTitle("cricket");
thread.setStreamName("sports");
message.setThread(thread);
messaging.publishMessage(message, callback);
setMessageAsRead
This method is used to update the status of the message identified by transactionId as Read.
The results of the operation are reported through a callback.
Syntax: setMessageAsRead(transactionId, callback)
Parameters:
transactionId
String
Specifies a single transaction id.
callback
JSObject
Specifies the callback.
**
//To send single message read status back to imiConnect
var messageTransactionId = "<your message transaction id>";
var messaging = IMI.ICMessaging.getInstance();
var callback = {
onSuccess: function() {
console.log("success");
},
onFailure: function(errormsg) {
console.log("failed ");
}
};
messaging.setMessageAsRead(messageTransactionId, callback);
setMessagesAsRead
This method is used to update the status of the message identified by transactionIds as Read.
The results of the operation are reported through a callback.
Syntax: setMessagesAsRead(transactionIds, callback)
Parameters:
transactionIds
String []
Specifies an array of transaction ids.
callback
JSObject
Specifies the callback object.
**
//To send mutliple messages read status back to imiConnect
var msgTransIds = ["transid1", "transid2", "transid3"];
var messaging = IMI.ICMessaging.getInstance();
var callback = {
onSuccess: function() {
console.log("success");
},
onFailure: function(errormsg) {
console.log("failed ");
}
};
messaging.setMessagesAsRead(msgTransIds, callback);
setICMessagingReceiver
This method is used to set ICMessagingReceiver callback. It contains two methods. When a message is received, ICMessagingReceiver.onMessageReceived
method is called. When a connection status is changed ICMessagingReceiver.onConnectionStatusChanged
method is called.
The results of the operation are reported through a callback.
Syntax: setICMessagingReceiver(callback)
Parameters:
callback
ICMessagingReceiver
Refer to ICMessagingReceiver.
**
//To receive connect status changes and published messages
var icMsgRecrCallback = new IMI.ICMessagingReceiver();
icMsgRecrCallback.onConnectionStatusChanged = function(statuscode) {
console.log("read the statuscode, based on the status do the operations");
if (statuscode == IMI.ICConnectionStatus.Connected) {
//Connected
} else if (statuscode == IMI.ICConnectionStatus.Error) {
//Error while connecting
}else if (statuscode == IMI.ICConnectionStatus.Refused) {
//Connection lost
} else {
//unknow error
}
};
icMsgRecrCallback.onMessageReceived = function(icMessage) {
//icMessage is IMI.ICMessage object
if (icMessage.getType() === IMI.ICMessageType.Message) {
//here direct message came from server(message sent from api)
} else if (icMessage.getType() === IMI.ICMessageType.ReadReceipt) {
//here read receipt came from another application for device syncing(read sent from another device)
} else if (icMessage.getType() === IMI.ICMessageType.Republish) {
//here repulished message came from another application for device syncing (message send from another device)
}
}
var messaging = IMI.ICMessaging.getInstance();
messaging.setICMessagingReceiver(icMsgRecrCallback);
subscribeTopic
This method is used to subscribe to the topic that has Read access level, allowing the SDK to receive messages on that topic.
The results of the operation are reported through a callback.
Incoming messages are received through ICMessagingReceiver.onMessageReceived
.
Syntax: subscribeTopic(topic, callback)
Parameters:
topic
String
Specifies the topic name to subscribe.
callback
JSObject
Specifies the callback.
**
//To subscribe to a topic
try {
var messaging = IMI.ICMessaging.getInstance();
var callback = {
onSuccess: function() {
console.log("success");
},
onFailure: function(errormsg) {
console.log("failed ");
}
};
var topic = "<Topic Name>";
messaging.subscribeTopic(topic, callback);
} catch (error) {
console.log(error)
}
unsubscribeTopic
This method is used to unsubscribe to the topic that has Read access level, preventing the SDK to receive messages on that topic. The messages may still be received until the callback has reported success.
The results of the operation are reported through a callback.
Syntax: unsubscribeTopic(topic, callback)
Parameters:
topic
String
Specifies the topic name to unsubscribe.
callback
JSObject
Specifies the callback.
callback = {
onSuccess: function(){
},
onFailure: function(){
}
};
**
//To unsubscribe to a topic
try {
var messaging = IMI.ICMessaging.getInstance();
var callback = {
onSuccess: function() {
console.log("success");
},
onFailure: function(errormsg) {
console.log("failed ");
}
};
var topic = "<Topic Name>";
messaging.unsubscribeTopic(topic, callback);
} catch (error) {
console.log(error)
}
createThread
This method is used to create a thread based on streamId
and threadTitle
and send the result in a callback.
Syntax: createThread(streamId, threadtitle, createThreadCallBack)
Parameters:
streamId
String
Identity of the stream.
threadTitle
String
Title of the thread.
callback
Invokes to report operation success or failure.
var createThreadCallBack = {
onSuccess: function (thread)
{
console.log(thread);
},
onFailure: function ()
{
console.log("failed to create thread")
}
};
messaging.createThread(steamid, threadtitle, createThreadCallBack);
fetchThreads
This method is used to get a list of threads that are created and at least one message transaction completed. Results are reported through the callback.
Syntax: fetchThreads(offset, limit, callback)
Parameters:
offset
String (mandatory parameter)
Pass offset value to fetch threads from that offset value.
Default value is 0.
limit
Integrer (mandatory parameter)
Specifies the maximum number of items that can be returned in threads array.
Default value is 100.
callback
Callback
Invokes to report if operation is a success or failure.
Success callback returns an additional value, a positive value indicating more threads on the server.
unread_msg_count
: Each thread object returns this based upon “server_inbox_version” in policy.
onFetchThreadsSuccess(threads, hasMoreThreads)
var messaging = IMI.ICMessaging.getInstance();
messaging.fetchThreads(offset, limit, callback);
fetchMessages
This method is used to get a list of messages from the imiconnect platform. All results are reported through the callback.
Syntax: fetchMessages(threadId, beforeDate, limit, callback)
Parameters:
threadId
String
Specifies the ThreadId value.
beforeDate
Date
Specifies the date since the messages must be returned. This value is optional; if nothing is passed then it is considered as current Date Time.
limit
Integer
Specifies the maximum number of items that can be returned in messages array.
Default value is 100
calback
Callback
Invokes to report if operation is a success or failure.
totalCount: fetchMessagesCallback
returns total number of messages for the userid/thread.
fetchMessagesSuccess(messages: any[], totalCount)
isOutgoing
Boolean
Indicates if the message is mobile originated if the value is true.
var messaging = IMI.ICMessaging.getInstance();
var messagesCallBack = {
onSuccess: function (messages) {
},
onFailure: function () {
console.log("failed to get messages");
}
};
messaging.fetchMessages(threadId, beforeDate, limit, callback);
fetchUnreadThreadCount
This method is used to get the count of threads that have unread messages.
Syntax: fetchUnreadThreadCount(callback)
Parameters:
callback
Callback
Invokes to report if operation is a success or failure.
Count: returns the unread thread count for user
fetchUnreadThreadCountSuccess(count)
var messaging = IMI.ICMessaging.getInstance();
messaging.fetchUnreadThreadCount(callback);
getSDKVersion
This method gets the SDK version being used.
Syntax: getSDKVesrion()
Returns: string version of SDK
this.sdkVersion = "v" + IMIconnectPlugin.getSDKVersion();
getOutgoing
This method is used to get the list of outgoing messages.
Syntax: getOutgoing()
setOutgoing
This method is used to set the outgoing flag as true to indicate that the message is mobile originated.
Syntax: setOutgoing(true)
fetchStreams
This method is used to get a list of streams. All results are reported through the callback.
Syntax: fetchStreams(callback)
Parameters:
callback
Callback
Invokes to report if operation is a success or failure.
var messaging = IMI.ICMessaging.getInstance();
var streamsCallBack = {
onSuccess: function (streams) {
//render streams
},
onFailure: function (error) {
alert("failed to get streams:");
}
};
messaging.fetchStreams(streamsCallBack);
This class allows the interception of incoming messages and RTM connection status changes. The default class provides standard message handling. You must invoke setICMessagingReceiver
to set ICMessagingReceiver
callback.
Public Methods | |
---|---|
onConnectionStatusChanged(status) | |
onMessageReceived(message) |
onConnectionStatusChanged
This method is invoked whenever there is a change to the RTM connection status.
Syntax: onConnectionStatusChanged(status)
Parameters:
onMessageReceived
This method is invoked whenever a new RTM message is received.
Syntax: onMessageReceived(message)
Parameters:
This class exposes message data from RTM and Push channels in a generalized form and is also used to send Real-Time Messages from an app to the imiconnect platform.
Public Methods | |
---|---|
String | getCategory() |
String | getChannel() |
JSObject | getCustomTags() |
JSObject | getExtras() |
IMI.ICMediaFile[] | getMedia() |
String | getMessage() |
String | getReplyTo() |
String | getSenderId() |
String | getTopic() |
String | getTransactionId() |
String | getUserId() |
setCustomTags(tags) | |
setMedia(files) | |
setMessage(message) | |
setSenderId(senderId) | |
String | setTopic(topic) |
getAttachments | |
getThread | |
getSubmittedAt | |
getDeliveredAt | |
boolean | getReadAt |
boolean | getType |
setAttachments | |
setThread |
getCategory
This method is used to get the category of the interactive message.
Syntax: String getCategory()
Return Value:
Returns the category of the message.
getChannel
This method is used to get the channel on which the message was received.
Syntax: String getChannel()
Return Value:
Returns the channel.
getCustomTags
This method is used to get the custom or developer specified data that was sent as part of the message payload.
Syntax: JSObject getCustomTags()
Return Value:
Returns the custom tags sent along with the message payload.
getExtras
This method is used to get the supplementary data that was sent as part of the message payload. The format of this data is controlled by the imiconnect platform.
Syntax: JSObject getExtras()
Return Value:
Returns the supplementary data that was sent along with the message payload.
getMedia
This method is used to get the media files that are attached to the message.
Syntax: IMI.ICMediaFile[] getMedia()
Return Value:
Returns the media files that ware attached to the message.
getMessage
This method is used to get the content of the message that is displayed to the end-users.
Syntax: String getMessage()
Return Value:
Returns the text message that is displayed to the end-users.
getReplyTo
This method is used to get the topic to which the reply should be sent. This method is not applicable to Push messaging.
Syntax: String getReplyTo()
Return Value:
Returns the topic to which reply should be sent.
getSenderId
This method is used to get the senderId an arbitrary identifier that is set by the sender of the message. This method is not applicable to Push messaging.
Syntax: String getSenderId()
Return Value:
Returns the senderid of the message.
getTopic
This method is used to get the topic on which the message was received. This method is not applicable to Push messaging.
Syntax: String getTopic()
Return Value:
Returns the topic on which the message was received.
getTransactionId
This method is used to get the transaction id that uniquely identifies the message transaction within the imiconnect platform.
Syntax: String getTransactionId()
Return Value:
Returns the transaction id that identifies the message transaction.
getUserId
This method is used to get the user id from which the message is originated. This method is not applicable to Push messaging.
Syntax: String getUserId()
Return Value:
Returns the user id from which the message is originated.
setCustomTags
This method is used to set the custom tags object to be sent with an outgoing RTM. This method is not applicable to Push messaging.
Syntax: setCustomTags(tags)
Parameters:
tags
JSObject
Specifies the JSObject.
setMedia
This method is used to set the media file attachments to be sent with an outgoing RTM. This method is not applicable to Push messaging.
Syntax: setMedia(files)
Parameters:
setMessage
This method is used to set the content of the text message to be sent with an outgoing RTM. This method is not applicable to Push messaging.
Syntax: setMessage(message)
Parameters:
message
String
Specifies the content of the text message.
setSenderId
This method is used to set the senderid to be sent with an outgoing RTM. This is arbitrary information such as a simple tag. This method is not applicable to Push messaging.
Syntax: setSenderId(senderId)
Parameters:
senderId
String
Specifies the sender id.
setTopic
This method is used to set the topic on which the message should be published. This method is not applicable to Push messaging.
Syntax: String setTopic(topic)
Parameters:
topic
String
Specifies the topic.
getAttachments
This method is used to get the attachment files that are attached to the message.
Syntax: ICAttachment[] getAttachments()
Return Type: Returns the attachment files attached to the message.
getThread
This method is used to get the thread details specified in the message.
Syntax: ICThread getThread()
Return Type: Returns the thread details that were specified in the message.
getSubmitted
This method is used to get the message submitted date to the imiconnect platform.
Syntax: Date getSubmittedAt()
Return Type: Returns the message submitted date to the imiconnect platform.
getDelivered
This method is used to get the message delivered date to the device.
Syntax: Date getDeliveredAt()
Return Type: Returns the message delivered date to the device.
getReadAt
This method is used to get the message read date at the device.
Syntax: Date getReadAt()
Return Type: Returns the message read date at the device.
getType
This method is used to get the message type.
Syntax: ICMessageType getType()
Return Type: Returns the message type.
setAttachments
This method is used to set the media file attachments to be sent with an outgoing RTM. This method is not applicable to Push messaging.
Syntax: setAttachments(final ICAttachment[] attachments)
Parameters:
attachments
Refer to ICAttachment class.
setThread
This method is used to set the thread details that need to be specified in the message.
Syntax: setThread(final ICThread thread)
Parameters:
thread
Refer to ICThread class.
setRelatedTransactionId
Use the property to set related transaction ID while submitting a form response.
Syntax: ICMessage.setRelatedTransactionId(relatedTransactioId)
message.setThread(this.thread);
message.setRelatedTransactionId(formMT.getTransactionId());
getRelatedTransactionId
This method returns a relatedTransactionID which can be used to identify original Form MO.
Syntax: ICMessage. getRelatedTransactionId()
Returns: String
getInteractiveData()
This method returns details about the form-response.
Note
This does not return the actual form response details.
Syntax: ICMessage.getInteractiveData()
Returns: ICInteractiveData object
This class is deprecated.
This class exposes data relating to media file attachments that are received through RTM and used to attach media files to outgoing messages.
Public Methods | |
---|---|
String | getContentType() |
long | getDuration() |
double | getLatitude() |
double | getLongitude() |
String | getPreview() |
long | getSize() |
String | getURL() |
setContentType(contentType) | |
setDuration(duration) | |
setLatitude(latitude) | |
setLongitude(longitude) | |
setPreview(preview) | |
setSize(size) | |
setURL(url) |
getContentType
This method is used to get the content type such as image/jpeg.
Syntax: String getContentType()
Return Value:
Returns the content type such as image or jpg.
getDuration
This method is used to get the duration of the applicable audio and video files.
Syntax: long getDuration()
Return Value:
Returns the duration of the audio and video files.
getLatitude
This method is used to get the latitude of the location passed in a message.
Syntax: double getLatitude()
Return Value:
Returns the latitude of the location.
getLongitude
This method is used to get the longitude of the location passed in a message.
Syntax: double getLongitude()
Return Value:
Returns the longitude of the location.
getPreview
This method is used to get the preview thumbnail as a string.
Syntax: String getPreview()
Return Value:
Returns the preview thumbnail as a string.
getSize
This method is used to get the file size in bytes.
Syntax: long getSize()
Return Value:
Returns the file size in bytes.
getURL
This method is used to get the URL of the media file.
Syntax: String getURL()
Return Value:
This method returns the URL.
setContentType
This method is used to set the content type such as image/jpeg.
Syntax: setContentType(contentType)
Parameters:
contentType
String
Specifies the content type.
setDuration
This method is used to set the duration of the audio and video files.
Syntax: setDuration(duration)
Parameters:
duration
long
Specifies the duration in milliseconds.
setLatitude
This method is used to set the latitude of the location passed in a message.
Syntax: setLatitude(latitude)
Parameters:
latitude
double
Specifies the latitude of the location.
setLongitude
This method is used to set the longitude of the location passed in a message.
Syntax: setLongitude(longitude)
Parameters:
longitude
double
Specifies the longitude of the location.
setPreview
This method is used to set the preview of the media file.
Syntax: setPreview(preview)
Parameters:
preview
String
Specifies the preview of the media file.
size
long
Specifies the size of the file in bytes.
url
String
Specifies the URL for the media.
This class exposes data relating to media file attachments that are received through RTM and used to attach media files to outgoing messages.
Public Methods | |
---|---|
String | getContentType() |
long | getDuration() |
double | getLatitude() |
double | getLongitude() |
String | getPreview() |
long | getSize() |
String | getURL() |
setContentType(contentType) | |
setDuration(duration) | |
setLatitude(latitude) | |
setLongitude(longitude) | |
setPreview(preview) | |
setSize(size) | |
setURL(url) |
getContentType
This method is used to get the content type such as image/jpeg.
Syntax: String getContentType()
Return Value:
Returns the content type such as image or jpg.
getDuration
This method is used to get the duration of the applicable audio and video files.
Syntax: long getDuration()
Return Value:
Returns the duration of the audio and video files.
getLatitude
This method is used to get the latitude of the location passed in a message.
Syntax: double getLatitude()
Return Value:
Returns the latitude of the location.
getLongitude
This method is used to get the longitude of the location passed in a message.
Syntax: double getLongitude()
Return Value:
Returns the longitude of the location.
getPreview
This method is used to get the preview thumbnail as a string.
Syntax: String getPreview()
Return Value:
Returns the preview thumbnail as a string.
getSize
This method is used to get the file size in bytes.
Syntax: long getSize()
Return Value:
Returns the file size in bytes.
getURL
This method is used to get the URL of the media file.
Syntax: String getURL()
Return Value:
This method returns the URL.
setContentType
This method is used to set the content type such as image/jpeg.
Syntax: setContentType(contentType)
Parameters:
contentType
String
Specifies the content type.
setDuration
This method is used to set the duration of the audio and video files.
Syntax: setDuration(duration)
Parameters:
duration
long
Specifies the duration in milliseconds.
setLatitude
This method is used to set the latitude of the location passed in a message.
Syntax: setLatitude(latitude)
Parameters:
latitude
double
Specifies the latitude of the location.
setLongitude
This method is used to set the longitude of the location passed in a message.
Syntax: setLongitude(longitude)
Parameters:
longitude
double
Specifies the longitude of the location.
setPreview
This method is used to set the preview of the media file.
Syntax: setPreview(preview)
Parameters:
preview
String
Specifies the preview of the media file.
size
long
Specifies the size of the file in bytes.
url
String
Specifies the URL for the media.
This class exposes Real Time Messaging topic data that is used to publish outgoing messages or subscribe to receive incoming messages.
Public Methods | |
---|---|
ICAccessLevel | getAccessLevel() |
String | getCreatedBy() |
Date | getCreatedDate() |
String | getName() |
Date | getUpdatedDate() |
Boolean | isSubscribed() |
getAccessLevel
This method is used to get the access level assigned to the topic.
Syntax: IMI.ICAccessLevel getAccessLevel(level)
Return Value:
Returns the access level assigned to the topic.
getCreatedBy
This method is used to get name who created the topic.
Syntax: String getCreatedBy()
Return Value:
Returns the name who created the topic.
getCreatedDate
This method is used to get the date on which the topic is created.
Syntax: Date getCreatedDate()
Return Value:
Returns the date on which the topic is created.
getName
This method is used to get the topic name.
Syntax: String getName()
Return Value:
Returns the topic name.
getUpdatedDate
This method is used to get the date on which the topic was last updated.
Syntax: Date getUpdatedDate()
Return Value:
Returns the date on which the topic was last updated.
isSubscribed
This method is used to verify whether the current user is subscribed to the topic.
Syntax: Boolean isSubscribed()
Return Value:
Returns true if the current user is subscribed to the topic.
This class exposes the thread data from the In-app channel in a generalized form. It is also used to send In-app from an app to the imiconnect platform.
Public Methods | |
---|---|
String | getId |
String | getTitle |
boolean | isWritable |
String | getStreamName |
Date | getCreatedAt |
Date | getUpdatedAt |
JSON | setExtras |
JSON | getExtras |
Number | getUnreadMessageCount |
getId
This method is used to get thread ID information.
Syntax: String getId()
Return Value: Returns the thread ID information.
getTitle
This method is used to get the thread title.
Syntax: String getTitle()
Return Value: Returns the thread title.
isWritable
This method is used to validate if a thread is writable or not. A thread is writable for Conversation thread, else (for announcement) thread it is not writable.
Syntax: boolean isWritable()
Return Value: Returns whether the thread is writable or not.
getStreamName
This method is used to get the stream name to communicate to the imiconnect platform.
Syntax: String getStreamName()
Return Value: Returns the stream name.
getCreatedAt
This method is used to get the thread created date on the imiconnect platform.
Syntax: Date getCreatedAt()
Return Value: Returns the thread created date on the imiconnect platform.
getUpdatedAt
This method is used to get the thread updated date on the imiconnect platform.
Syntax: Date getUpdatedAt()
Return Value: Returns the thread updated date on the imiconnect platform.
setExtras
This method is used to set extra data to be associated with the thread.
Syntax: JSON setExtras(extras)
//accepts any JSON object
getExtras
This method is used to get the thread updated date on the imiconnect platform.
Syntax: JSON getExtras()
Return Value: Returns the extra data associated with the thread.
getUnreadMessageCount
This method returns the count of unread messages.
Syntax: getUnreadMessageCount()
Return Value: Returns the count of unread messages.
setReasonForStatusChange
Provide reason for changing status.
Syntax: ICThread.setReasonForStatusChange(reason);
reason
string
getReasonForStatusChange()
Returns reason if provided while changing status of the ICThread object.
Syntax: ICThread.getReasonForStatusChange()
thread.setReasonForStatusChange(reason);
messaging.closeThread(thread, closeThreadCallBack);
This enumeration describes different access levels a topic can have. Write access is required to publish to a topic. Read access is required to subscribe to a topic.
Read
Users are only permitted to receive a message on the topic.
Write
Users are allowed to publish a message on the topic.
ReadWrite
Users can receive and publish messages on the topic.
This enumeration describes different filters used to fetch topics.
All
Used to fetch all the topics regardless of access level.
Read
Used to fetch the topics with Read access.
Write
Used to fetch the topics with Write access.
ReadWrite
Used to fetch the topics with ReadWrite access.
This enumeration describes different connection statuses between the SDK and the Real-Time Messaging server.
None
No connection attempt has been made.
Connecting
The SDK is attempting to establish a connection to the Real-Time Messaging server.
Connected
The SDK is connected and allows you to publish and receive messages.
Refused
The connection is refused by the server.
Note: Currently this value is not used.
Closed
The SDK is disconnected from the Real-Time Messaging server.
Error
A connection error has occurred.
This enumeration describes different error codes of the SDK.
Not Initialized
Returned when trying to access a feature without initializing the SDK.
AlreadyInitialized
Returned when trying to initialize the SDK when it is already initialized.
ConnectionAlreadyExists
Returned when the connection is already established.
NotRegistered
Returned when trying to access a feature without registering a user.
FeatureNotSupported
Returned when trying to access a feature that is not supported by the app.
InvalidParameterValue
Returned when a required parameter is not passed or an invalid value has been passed to a method.
PermissionNotGranted
Returned when access is not granted to a permission that is required for operation.
NotConnected
Returned when trying to communicate with the RTM server without establishing a connection.
ConnectionFailure
Returned when a connection is failed between the SDK and RTM server.
PublishFailed
Returned when a publication of an RTM message has failed.
SubscribeFailed
Returned when a subscription to an RTM topic has failed.
UnsubscribeFailed
Returned when trying to unsubscribe from an RTM topic has failed.
Unknown
Returned when an unknown error occurs.
DeviceIdCurrentlyNotRegistered (code 6006)
Returned when the device ID is currently not registered.
DuplicateRegisterListener (code 6026)
Duplicate register listener.
InvalidToken (code 6027)
Invalid token.
InvalidAuthorizationRequest (code 6028)
Invalid authorization request.
TokenExpired (code 6029)
Token has expired.
TokenRequired (code 6030)
Token is required.
This enumeration describes different connection statuses and their respective error codes.
UserId
Specifies the value passed in the UserId parameter in DeviceProfileParam.
CustomerId
Specifies the value passed in the CustomerId parameter in DeviceProfileParam.
Message
The message is a standard RTM.
ReadReceipt
The message data is ReadReceipt. Only TransactionId is available and can be used to match receipt to the original message.
MessageNotification
The message is a notification.
Republish
The message is a republish of a MO, all data available in the original message is available.
Push Messaging
The push notification service allows you to send messages to web applications from imiconnect. The notifications are sent to the 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.
In-app (Real-Time) Messaging
The 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, on a banking website, if a customer wishes to interact with a customer service team, you can integrate a chat or customer service feedback functionality using In-app Messaging on your website.
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 In-app Messaging:
connect
This method is used to initiate a connection between the web app and IMIconnect Message Broker to send (publish) or receive in-app 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 in-app 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:
userName
String
Specifies the username to authenticate the user.
password
String
Specifies the app secret key to authenticate the user.
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
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:
callbackfunction
function
Specifies 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
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 subscription details of the given topic.
Syntax: getSubscriptions (topic, Callback)
Parameters:
topic
String
Retrieves the subscriptions of a topic.
Returns:
None
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 the imiconnect platform under channel configuration by an imiconnect admin.
Syntax: getTopics (icallback, pageNo)
Parameters:
pageNo
Number (greater than 0)
Specifies the page number from which to get the topics
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)
Parameters:
topic
String
The topic to which the message has to be published.
message
Specifies the text message and properties related to the message. Refer to the Message object.
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 the imiconnect platform.
Syntax: register (userId, callback)
Before registering customers through web app, a master profile has to be created using
Create Profile API.
Parameters:
userId
String
Specifies the user name for authentication.
Returns:
The response of registered method is returned using Callback
.
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 the imiconnect platform with the transaction id.
Syntax: sendDRMessage(tid, callback)
Parameters:
tid
String
Specifies the transaction id of the delivery report.
try {
client.sendDRMessage("12dsd32sdsds343esddsdsdsdds");
} catch (ex) {
console.log(ex);
}
sendReadReceipt
This method is used to send read receipt details to the imiconnect platform with transaction id.
Syntax: sendReadReceipt (tid)
Parameters:
tid
String
Specifies the transaction id of the delivery report.
try {
client.sendReadReceipt("12dsd32sdsds343esddsdsdsdds");
} catch (ex) {
console.log(ex);
}
setConnectReceiver
This method is used to register the callback to listen to different types of events provided in the callback.
Syntax: setConnectReceiver(ConnectReceiver)
Parameters:
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 the imiconnect platform.
Syntax: setLocation (lat, long)
lat
Integer
A geographic coordinate that specifies the north-south position of a point on Earth's surface.
long
Integer
A geographic coordinate that specifies the east-west position of a point on Earth's surface.
try {
client.setLocation(17.43, 78.2656);
} catch (ex) {
console.log(ex);
}
Message producers are called publishers and message consumers are called subscribers.
Syntax: subscribe (topic, Callback)
Parameters:
topic
String
The topic to which the application subscribes to receive messages.
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 messages from the subscribed topic.
Syntax: unSubscribe (topic, callback)
Parameters:
topic
String
Specifies the topic name to unsubscribe.
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 In-app Messaging:
onConnectionChange
This method is invoked whenever there is a change in the connection status.
Syntax: onConnectionChange (status_code)
Parameters:
state
Number
The available connection states are:
- 0: connection success
- 1: connection failed
- 2: retry connection
- 3: connection lost
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:
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)
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 the imiconnect platform is unable to receive the response.
Syntax: onFailue(result)
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 the message sent or received through the In-app Messaging channel. It has two class variables.
- Message (Unicode text of the message send or receive)
- message-id (Unicode id of the message)
Following are the methods:
setProperty
This method allows you to set the property to a message object as key-value pairs, the value can be of any type.
Syntax: setProperty(key, value)
Parameters:
key
String
Specifies the key to identify a particular value.
value
String
Specifies the value to add to a particular key.
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:
key
String
Specifies the key to identify a particular value.
When an error occurs while using the JavaScript SDK, the following error messages are thrown:
NotRegistered
Returned when the app is not registered with imiconnect
NotConnected
Returned when the app is not connected to imiconnect
FeatureNotSupported
Returned when the feature is not supported in imiconnect
ICFormField
This class represents formField data for form attachment
getType
This method is used to get the ICFormFieldType of the object
Syntax:getType()
Returns: ICFormFieldType object
setType
This method sets the type of the FormField.
Syntax:setType(ICFormFieldType type)
type
type of the formField
getName
This method is used to get the formField name
Syntax: getName()
Returns: formField name
setName
This method is used to set the formField name
Syntax: setName(name)
label
string
getLabel
This method is used to get the formField label. Label can be used as display text for the field.
Syntax: getLabel()
Returns: label: String
setLabel
This method is used to set the formField label.
Syntax: setLabel(label)
label
string
getValue
This method is used to get the formField Value
Syntax: getValue ()
Returns: Value as submitted by the user
setValue
This method is used to set the value of FormField
Syntax: setValue(value)
value
string
getDescription
This method is used to get the formField description
Syntax: getDescription ()
Returns: string
setDescription
This method is used to set the description of FormField
Syntax: setDescription(description)
description
string
getMandatory
This method returns whether it is mandatory for user to fill FormField value.
Syntax: getMandatory ()
Returns: Bool
setMandatory
This method sets whether it is mandatory to fill form field value or not.
Syntax: setMandatory(value)
value
bool true or false
options
options array for formField Type "dropdown"
getOptions
This method is used to get the options for FormField type "Dropdown"
Syntax: getOptions()
Returns: options array for formField Type "dropdown"
fromJSON
Instantiates a new ICFormField instance from the supplied JSONObject.
Syntax: fromJSON(jsonObj)
Returns:* A new ICFormField or null if jsonObj is null
jsonObject
A valid JSONObject instance containing form field data
IMI.ICInteractiveData
This class represents the data for user interaction on message
getSubmittedAt
Returns the date on which the interaction data was submitted to the imiconnect platform.
Syntax: getSubmittedAt()
Returns: Date() object
setSubmittedAt
Sets the date on which the interaction data was submitted to the imiconnect platform
Syntax: setSubmittedAt(submittedAt)
submittedAt
date
setType
This method sets the type of the Interactive Data
Syntax: setType(ICInteractiveDataType type)
type
type of the ICInteractiveDataType
getType
This method is used to get the ICInteractiveDataType for the message
Syntax: getType()
Returns: ICInteractiveDataType object
getTid
This method gets the transaction id that uniquely identifies the form response message.
Syntax: getTid()
Returns: String
setTid
This method sets the transaction id for form response message.
Syntax: setTid(tid)
tid
a string transaction id that uniquely identifies the form response message
getPayload
This method gets interactive payload data
Syntax: getPayload()
Returns: JSON Object
toJSON
This method returns a new JSONObject instance containing message interactive data.
Syntax: toJSON()
Returns: JSON Object
fromJSON
Instantiates a new ICInteractiveData instance from the supplied JSONObject.
Syntax: fromJSON(jsonObj)
Returns: A new ICInteractiveData object
IMI.ICFormTemplateAttachment
This class represents Form template attachment.
getTitle
This method returns the form template attachment title.
Syntax: getTitle()
Returns: the form template attachment title
setTitle
This method Sets the form template attachment title
Syntax: setTitle(title)
title
form template attachment title
getFields
This method returns list of form field data.
Syntax: getFields()
Returns: Array of IMI.ICFormField objects
setFields
This method sets array of form field data
Syntax: setFields(fields[])
fields
list of form field data
getContentType
This method gets content type of attachment
Syntax: getContentType ()
Returns: IMI.ICContentType value
setContentType
This method sets the contentType
Syntax: setContentType (type)
Type
IMI.ICContentType
getTemplateType
This method is used to get the template type
Syntax: getTemplateType()
Returns: ICTemplateType
setTemplateType
Syntax: setTemplateType(templateType)
templateType
ICTemplateType
getTemplateId
This method returns the template Id .
Syntax: getTemplateId()
Returns: Returns the Id for the template
setTemplateId
This method sets the template Id
Syntax: setTemplateId(templateId)
templateId
the Id for the template
toJSON
This method returns a new JSONObject instance containing form template attachment data.
Syntax: toJSON()
Returns: A JSONObject representation of the form template attachment data.
fromJSON
Instantiates a new ICFormTemplateAttachment instance from the supplied JSONObject.
Syntax: fromJSON(jsonObj)
Returns: A new ICFormTemplateAttachment or null if jsonObj is null.
jsonObject
A valid JSONObject instance containing form template attachment data.
Enumerations
IMI.ICInteractiveDataType
This enumeration describes the Interactive data type for message.
FormResponse
Form response is for message type ‘form’
Form
Indicates the form message which will accept a set of form fields
IMI.ICFormFieldType
This enumeration describes the type of form fields supported for message type “form”
Validation should be a part of UI as per application requirements
Text
Text This field is string input
Name
This field is string input
This field is string input
Integer
This field is integer input
Decimal
This field is decimal input
Date
This field is integer input
Dropdown
This field is a dropdown input
Audio
Media type is Audio
File
Media type is file
Video
Media type is Video
Image
Media type is Image
Url
Media type is a URL link
Template
Media type is a Form Template
None
Status not available
NotSent
Message has not been sent
Sent
Message has been sent
Delivered
Message has been delivered
Read
Message has been read
Updated 4 months ago