CometChat Pro Documentation

You'll find comprehensive guides and documentation to help you start working with CometChat as quickly as possible. Let's jump right in!

Cordova/Ionic

Learn how to send push notifications for messages.

The Push Notification extension allows you to send push notifications to mobile apps and desktop browsers.

Add Push Notification

For Cordova & Ionic, there are numerous plugins available via NPM which can be used to set up push notifications for your apps like FCM Plugin and Push Plugin.

To setup Push Notification, you need to follow the steps mentioned in the Plugin's Documentation. You need to make different apps on the firebase console for each platform respectively (Android, iOS).

  • To configure Firebase Push Notifications for your apps create a Firebase project at
    Firebase Console

Step 1: Add Firebase to your app

Create Firebase App

If you have previously not created a Firebase project for your app Click Add project. If you already have created a project for your app in which you wish to integrate CometChat, select the same project, and download the config file:

  1. For Android, you need to download the google-services.json file.

  2. For iOS, you need to download the GoogleService-Info.plist file.

  3. For web, you will need to have the Firebase config object which will look something like:

var firebaseConfig = {
  apiKey: "api-key",
  authDomain: "project-id.firebaseapp.com",
  databaseURL: "https://project-id.firebaseio.com",
  projectId: "project-id",
  storageBucket: "project-id.appspot.com",
  messagingSenderId: "sender-id"
};

Step 2: Add FCM Server Key

Login to CometChatPro Dashboard and move to Extension tab as follows:

FCM

In extension, section select Push Notification Service and click add Extension, this will add push notification service to your app

Move to Your extension tab, Enable push notification service

then ACTION > SETTINGS > ADD FCM SERVER KEY > SAVE

FCM SERVER KEY

Always get your Firebase Cloud Messaging Server Key from firebase console as shown below:

Subscribe To Topic/s

To subscribe to topics instead of using the subscribe to a topic method provided by the plugin you are using, we recommend you use our APIs to subscribe to a topic.

You can subscribe to topic/s in two ways:
a. Subscribe to all topics(all the joined groups and one-to-one conversations)
b. Subscribe to one topic.

a. Subscribe to all topics
If you wish to subscribe to all the groups you have previously joined, you can use the below code snippet.

📘

Note

You will still have to subscribe to groups individually whenever you join any group using the joinGroup() method provided by the SDK.

❗️

Please make sure you are subscribing to topics in the success of CometChat.login().

var appID = "APP_ID";
var token = "GENERATED_FCM_TOKEN";
var userUID = "UID_OF_LOGGED_IN_USER";
var appToken;
CometChat.getJoinedGroups().then(groups => {
  CometChat.getAppSettings().then(settings: any => {
    if(settings.extensions){
        settings.extensions.forEach(ext => {
            if (ext.id == "push-notification"){
            appToken = ext.appToken;
        }
        });
        }
    var url =
      "https://push-notification-us.cometchat.io/v1/subscribetomany?appToken=" +
      appToken;
    fetch(url, {
      method: "POST",
      headers: new Headers({
        "Content-Type": "application/json"
      }),
      body: JSON.stringify({
        appId: appID,
        fcmToken: token,
        uid: userUID,
        groups: groups,
        platform: "ionic"
      })
    })
      .then(response => {
        if (response.status < 200 || response.status >= 400) {
          console.log("Error subscribing to topics: " +response.status +" - " +response.text());
        } else {
          console.log("Subscribed to all topics");
        }
      })
      .catch(error => {
        console.error(error);
      });
  });
});

b. Subscribe to one topic:

To receive push notifications, the logged-in user must subscribe to two types of topics:

  1. Their own topic - All the messages for one-on-one conversations that are sent to the logged-in user are received using this topic. The topic you must subscribe to is AppID_user_UID where AppID is your CometChat App ID and UID is the logged-in user's ID.

  2. Topics for all the groups the logged in user is a part of - All the messages for a group conversation are received using these topics. For every group joined, the logged-in user will have to subscribe to the topic for that group. For every group, you must subscribe to AppID_group_GUID where AppID is your CometChat App ID and GUID is the group's ID.

FCM topic messaging allows your app server to send a message to multiple devices that have opted into a particular topic. Based on the publish/subscribe model, topic messaging supports unlimited subscriptions per app.

var token = "generated_FCM_token";
CometChat.getAppSettings().then(settings: any => {
    var appToken;
    if(settings.extensions){
    settings.extensions.forEach(ext => {
        if (ext.id == "push-notification"){
        appToken = ext.appToken;
      }
    });
    }
  var userType = "user";
  var UID = "UID";
  var appId = "APP_ID";
  var region = "REGION_OF_APP";
  var topic = appId + "_" + userType + "_" + UID;
  var url =
    "https://push-notification-"+ region +".cometchat.io/v1/subscribe?appToken=" +
    appToken +
    "";
  fetch(url, {
    method: "POST",
    headers: new Headers({
      "Content-Type": "application/json"
    }),
    body: JSON.stringify({ appId: appId, fcmToken: token, topic: topic })
  })
    .then(response => {
      if (response.status < 200 || response.status >= 400) {
        console.log(
          "Error subscribing to topic: " +
            response.status +
            " - " +
            response.text()
        );
      }
      console.log('Subscribed to "' + topic + '"');
    })
    .catch(error => {
      console.error(error);
    });
});
var token = "generated_FCM_token";
CometChat.getAppSettings().then(settings: any => {
  var appToken;
  if(settings.extensions){
    settings.extensions.forEach(ext => {
        if (ext.id == "push-notification"){
        appToken = ext.appToken;
      }
    });
    }
  var userType = "group";
  var GUID = "GUID";
  var appId = "APP_ID";
  var region = "REGION_OF_APP";
  var topic = appId + "_" + userType + "_" + GUID;
  var url =
    "https://push-notification-"+ region +".cometchat.io/v1/subscribe?appToken=" +
    appToken +
    "";
  fetch(url, {
    method: "POST",
    headers: new Headers({
      "Content-Type": "application/json"
    }),
    body: JSON.stringify({ appId: appId, fcmToken: token, topic: topic })
  })
    .then(response => {
      if (response.status < 200 || response.status >= 400) {
        console.log(
          "Error subscribing to topic: " +
            response.status +
            " - " +
            response.text()
        );
      }

      console.log('Subscribed to "' + topic + '"');
    })
    .catch(error => {
      console.error(error);
    });
});

Receive Message

Here you can use the callback provided by the plugin. For eg: If you are using the FCM Plugin you can receive the messages as follow:

this.fcm.onNotification().subscribe(data => {
    console.log("here you receive the message", data);
});

This should ideally be added in the app.component.ts file and should be called in the success of the platform.ready().

For other plugins, you can refer to the documentation provided by the plugin to check how messages can be received using that plugin. Once you have started receiving messages, you can act on the received messages accordingly as per your requirements.

Unsubscribe From Topic/s

You can unsubscribe from topic/s in two ways:
a. Unsubscribe from all topics(all the joined groups and one-to-one conversations)
b. Unsubscribe from one topic.

a. Unsubscribe from all topics:
If you subscribe to all topics you can unsubscribe from all the topics you have subscribed to in your logout method using the below code snippet.

var appID =  "APP_ID";
var token = "GENERATED_FCM_TOKEN";
var appToken;
CometChat.getAppSettings().then(settings: any => {
  if(settings.extensions){
    settings.extensions.forEach(ext => {
        if (ext.id == "push-notification"){
        appToken = ext.appToken;
      }
    });
    }
  var url = "https://push-notification-us.cometchat.io/v1/unsubscribealltopic?appToken=" + appToken;
  fetch(
    url, 
    {
      method: "DELETE",
      headers: new Headers({
        "Content-Type": "application/json"
      }),
      body: JSON.stringify({ appId: appID, fcmToken: token })
    }
  )
  .then(response => {
    if (response.status < 200 || response.status >= 400) {
      console.log("Error unsubscribing from topics: " +response.status +" - " +response.text());
    } else {
      console.log("Unsubscribed from all topics"); 
    }
  })
  .catch(error => {
    console.error(error);
  });
});

b. Unsubscribe from one topic:
If you subscribe to a single topic you can unsubscribe from the single topic in the following way:

var token = "generated_FCM_token";
CometChat.getAppSettings().then(settings: any => {
    var appToken;
    if(settings.extensions){
            settings.extensions.forEach(ext => {
            if (ext.id == "push-notification"){
            appToken = ext.appToken;
        }
        });
        }
    var userType = "user";
    var UID = "UID";
    var appId = "APP_ID";
    var region = "REGION_OF_APP";
    var topic = appId + "_" + userType + "_" + UID;
    var url =
    "https://push-notification-"+ region +".cometchat.io/v1/unsubscribe?appToken=" +
    appToken;
    fetch(url, 
        {
            method: "DELETE",
            headers: new Headers({
                "Content-Type": "application/json"
            }),
            body: JSON.stringify({ appId: appId, fcmToken: token, topic: topic })
        }
    )
        .then(response => {
            if (response.status < 200 || response.status >= 400) {
            console.log(
                "Error subscribing to topic: " +
                response.status +
                " - " +
                response.text()
            );
            } else {
            console.log('Unsubscribed from "' + topic + '"');
            }
        })
        .catch(error => {
            console.error(error);
        });
    });
var token = "generated_FCM_token";
CometChat.getAppSettings().then(settings: any => {
    var appToken;
    if(settings.extensions){
        settings.extensions.forEach(ext => {
            if (ext.id == "push-notification"){
            appToken = ext.appToken;
        }
        });
        }
    var userType = "group";
    var GUID = "GUID";
    var appId = "APP_ID";
    var region = "REGION_OF_APP";
    var topic = appId + "_" + userType + "_" + GUID;
    var url =
    "https://push-notification-"+ region +".cometchat.io/v1/unsubscribe?appToken=" +
    appToken;
    fetch(url, 
        {
            method: "DELETE",
            headers: new Headers({
                "Content-Type": "application/json"
            }),
            body: JSON.stringify({ appId: appId, fcmToken: token, topic: topic })
        }
    )
        .then(response => {
            if (response.status < 200 || response.status >= 400) {
            console.log(
                "Error subscribing to topic: " +
                response.status +
                " - " +
                response.text()
            );
            } else {
            console.log('Unsubscribed from "' + topic + '"');
            }
        })
        .catch(error => {
            console.error(error);
        });
    });

Handle Custom Messages

To receive notification of CustomMessage, you need to set metadata while sending the CustomMessage.

var receiverID = "UID";
var customData = {
  latitude: "50.6192171633316",
  longitude: "-72.68182268750002"
};

var customType = "location";
var receiverType = CometChat.RECEIVER_TYPE.USER;
var metadata = {
  pushNotification: "Your Notification Message",
};

var customMessage = new CometChat.CustomMessage(
  receiverID,
  receiverType,
  customType,
  customData
);

customMessage.setMetadata(metadata);

CometChat.sendCustomMessage(customMessage).then(
  message => {
    // Message sent successfully.
    console.log("custom message sent successfully", message);
  },
  error => {
    console.log("custom message sending failed with error", error);
    // Handle exception.
  }
);

Converting push notification payload to message object

CometChat pro SDK provides a method CometChat.CometChatHelper.processMessage() to convert the message JSON to the corresponding object of TextMessage, MediaMessage,CustomMessage, Action or Call.

This code needs to be added to the onMessageReceived() method of the FirebaseMessagingService class.

var processedMessage = CometChat.CometChatHelper.processMessage(JSON_MESSAGE);

Messages

Simple text message

SenderName: text message

Attachment(s) with text

SenderName: text message

An attachment without text

SenderName: has sent you a/an Type

Attachments without text

SenderName: has sent you Types

📘

Type of Attachment can be of the following the type
1.CometChatConstants.MESSAGE_TYPE_IMAGE
2.CometChatConstants.MESSAGE_TYPE_VIDEO
3.CometChatConstants.MESSAGE_TYPE_AUDIO
4.CometChatConstants.MESSAGE_TYPE_FILE

Push Notification: Payload Sample for Text Message and Attachment/Media Message

{  
  "alert":"Spiderman: Text Message",
  "sound":"default",
  "title":"CometChat Pro",
  "message":{  
     "receiver":"superhero4",
     "data":{  
        "entities":{  
           "receiver":{  
              "entityType":"user",
              "entity":{  
                 "uid":"superhero4",
                 "role":"default",
                 "name":"Wolverine", 
                 "avatar":"http://data.cometchat.com/assets/images/avatars/wolverine.png",
                 "status":"offline"
              }
           },
           "sender":{  
              "entityType":"user",
              "entity":{  
                 "uid":"superhero3",
                 "role":"default",
                 "name":"Spiderman",
                 "avatar":"https://data.cometchat.com/assets/images/avatars/spiderman.png",
                 "status":"offline"
              }
           }
        },
        "text":"Text Message"
     },
     "sender":"superhero3",
     "receiverType":"user",
     "id":"142",
     "sentAt":1555668711,
     "category":"message",
     "type":"text"
  }
}
{
  "alert":"Spiderman: has sent an image",
  "sound":"default",
  "title":"CometChat Pro",
  "message":{
     "receiver":"superhero4",
     "data":{
        "attachments":[
           {
              "extension":"png",
              "size":14327,
              "name":"extension_leftpanel.png",
              "mimeType":"image/png",
              "url":"https://s3-eu-west-1.amazonaws.com/data.cometchat.com/1255466c41bd7f/media/1555671238_956450103_extension_leftpanel.png"
           }
        ],
        "entities":{
           "receiver":{
              "entityType":"user",
              "entity":{
                 "uid":"superhero4",
                 "role":"default",
                 "name":"Wolverine",
                 "avatar":"https://data.cometchat.com/assets/images/avatars/wolverine.png",
                 "status":"offline"
              }
           },
           "sender":{
              "entityType":"user",
              "entity":{
                 "uid":"superhero3",
                 "role":"default",
                 "name":"Spiderman",
                 "avatar":"https://data.cometchat.com/assets/images/avatars/spiderman.png",
                 "status":"offline"
              }
           }
        },
        "url":"https://s3-eu-west-1.amazonaws.com/data.cometchat.com/1255466c41bd7f/media/1555671238_956450103_extension_leftpanel.png"
     },
     "sender":"superhero3",
     "receiverType":"user",
     "id":"145",
     "sentAt":1555671238,
     "category":"message",
     "type":"image"
  }
}

Updated 3 months ago


Cordova/Ionic


Learn how to send push notifications for messages.

Suggested Edits are limited on API Reference Pages

You can only suggest edits to Markdown body content, but not to the API spec.