question

Muhammad Shoaib avatar image
Muhammad Shoaib asked Phong Vu commented

cannot receive call notification in NodeJS

I am facing issues with call notification.

I am able to receive calls in the call log from dashboard but in NodeJS code using this function "handleSubscriptionNotification" i cannot get response after making call and cannot handle subscriptions here in this function.

I am able to get extensions and event filters and can get messages: LOGIN SUCCESS DATA, RENEW SUBSCRIPTION SUCCESS DATA, SUBSCRIPTION CREATED SUCCESSFULLY but cannot get this message SUBSCRIPTION NOTIFICATION..... from handleSubscriptionNotification.

Help me with this issue.



rest api
2 comments
1 |3000

Up to 8 attachments (including images) can be used with a maximum of 1.0 MiB each and 10.0 MiB total.

Phong Vu avatar image Phong Vu ♦♦ commented ·

Can you post the code where you register for notification and the function where you expect to handle the notification.

Remember to remove sensitive information such as client id, client secret, username and password etc.

0 Likes 0 ·
Muhammad Shoaib avatar image Muhammad Shoaib Phong Vu ♦♦ commented ·

I have shared the code in answer

0 Likes 0 ·
Muhammad Shoaib avatar image
Muhammad Shoaib answered Phong Vu edited
function createEventFilter(extensions) {
  var _eventFilters = [];
  for(var i = 0; i < extensions.length; i++) {
  var extension = extensions[i];
  console.log('EXTENSION: ', extension.id);
  if(true) 
    _eventFilters.push('/account/~/extension/' + extension.id + '/presence?detailedTelephonyState=true&aggregated=true')
  }
  console.log('EVENT FILTERS: ', _eventFilters);
  return _eventFilters;
}

function startSubscription(eventFilters) {
  return subscription
  .setEventFilters(eventFilters)
  .register()
}

platform.on(platform.events.loginSuccess, handleLoginSuccess)
platform.on(platform.events.refreshSuccess, handleRefreshSuccess);

subscription.on(subscription.events.notification, handleSubscriptionNotification);
subscription.on(subscription.events.subscribeSuccess, handleSubscribeSuccess)

function handleSubscriptionNotification(msg) {
  console.log('SUBSCRIPTION NOTIFICATION.....');
  console.log(util.inspect(msg, {showHidden: true, depth: null}));
}


1 |3000

Up to 8 attachments (including images) can be used with a maximum of 1.0 MiB each and 10.0 MiB total.

Muhammad Shoaib avatar image
Muhammad Shoaib answered

This is where i am handling notification and due to character limits i had to remove extra events like

platform.on(platform.events.loginSuccess, handleLoginSuccess);

platform.on(platform.events.loginError, handleLoginError);

platform.on(platform.events.logoutSuccess, handleLogoutSuccess);

platform.on(platform.events.logoutError, handleLogoutError);

platform.on(platform.events.refreshSuccess, handleRefreshSuccess);


but i am using these events in my code

1 |3000

Up to 8 attachments (including images) can be used with a maximum of 1.0 MiB each and 10.0 MiB total.

Phong Vu avatar image
Phong Vu answered

You codes look ok except there are a few things you need to double check.

1. I have not seen the "aggregated" parameter for presence notification from documentation.

2. Maybe you removed the log, but I don't see where you log your subscription successfully. Can you add some extra lines to the startSubscription function as shown below if you haven't had that in your code.

function startSubscription(eventFilters) {
   subscription.setEventFilters(eventFilters)
      .register()
      .then(function(subscriptionResponse) {
          console.log("Ready to receive notification via PubNub.")
      })
      .catch(function(e) {
          console.error(e);
      });
}

3. I assumed that you declare the var subscription = rcsdk.createSubscription(); as a global variable. So you don't really need to return subscription. inside the startSubscription() function.

4. If everything is correct and it still does not work. Can you simplify the event filter to just 1 extension and make sure you make a call to that extension's phone number. Or just change that extension's presence status.


Next time please post your code within the code </> block so it is easier to read (as I edited your code above)

1 |3000

Up to 8 attachments (including images) can be used with a maximum of 1.0 MiB each and 10.0 MiB total.

Muhammad Shoaib avatar image
Muhammad Shoaib answered Phong Vu commented
var RC = require('ringcentral');
var http = require('http');
var util = require('util');

// Set the RingCentral API Base URL based upon environment
var rcServer = "https://platform.devtest.ringcentral.com"

// Initialize the RC SDK
var sdk = new RC({
    server: rcServer,
    appKey: '',
    appSecret: ''
});

// APP VARS
var server = http.createServer();
var platform = sdk.platform();
var subscription = sdk.createSubscription();

// Login to the RingCentral Platform
function login() {
    return platform.login({
            username: "",
            password: "",
            extension: 101
        })
        .then(function (response) {
            console.log("Succesfully logged into the RC Account");
            init();
            platform.get('/account/~/presence', {
                detailedTelephonyState: true
            })
            .then(function (resp) {
                console.log('resp', resp.json().records)

                var jsonObj = resp.json()
                for (var record of jsonObj.records){
                  console.log('\n***',record)
                }
            })
        })
        .catch(function (e) {
            console.error("ERROR: ", e);
            throw e;
        });
}

login();

function init() {
    var extensions = [];
    var page = 1;

    function getExtensionsPage() {

        return platform
            .get('/account/~/extension/', {
                type: 'User',
                status: 'Enabled',
                page: page,
                perPage: 500 //REDUCE NUMBER TO SPEED BOOTSTRAPPING
            })
            .then(function (response) {
                //console.log("The extension response contained:", JSON.stringify(response.json(), null, 2));
                var data = response.json();
                //console.log("************** THE NUMBER OF EXTENSIONS ARE : ***************", data.records.length);
                extensions = extensions.concat(data.records);
                console.log("records")
                // console.log(extensions)
                if (data.navigation.nextPage) {
                    page++;
                    return getExtensionsPage(); // this will be chained
                } else {
                    console.log('\none ext: ',extensions[0], '\n')
                    return extensions; // this is the finally resolved thing
                }
            });

    }

    /*
     Loop until you capture all extensions
     */
    return getExtensionsPage()
        .then(createEventFilter)
        .then(startSubscription)
        .catch(function (e) {
            console.error(e);
            throw e;
        });

}

function createEventFilter(extensions) {
    //console.log("********* CREATING EVENT FILTERS ***************");
    var _eventFilters = [];
    // var messageType = messageType || 'SMS'; // SMS is the default message type in RC-API as of 2016-09-16
    for(var i = 0; i < extensions.length; i++) {
        var extension = extensions[i];
        console.log('\n\n\n',extension)
        if(true) _eventFilters.push('/account/~/extension/' + extension.id);
        if(true) _eventFilters.push('/account/~/extension/' + extension.id + '/presence?detailedTelephonyState=true&aggregated=true');
    }
    // console.log('EVENT FILTERS: ', _eventFilters);
    return _eventFilters;
}

function startSubscription(eventFilters) { //FIXME MAJOR Use devices list somehow
    //console.log("********* STARTING TO CREATE SUBSCRIPTION ON ALL FILTERED DEVICES ***************");
    console.log('\n\nevts',eventFilters)
    subscription
        .setEventFilters(eventFilters)
        .register()
        .then((data) => console.log("Ready to receive notification via PubNub\n\n\n",data))
        .catch((err) => console.log("ERRORSERRORS: ",err))
}

// Register Platform Event Listeners
platform.on(platform.events.loginSuccess, handleLoginSuccess);
platform.on(platform.events.loginError, handleLoginError);
platform.on(platform.events.logoutSuccess, handleLogoutSuccess);
platform.on(platform.events.logoutError, handleLogoutError);
platform.on(platform.events.refreshSuccess, handleRefreshSuccess);
platform.on(platform.events.refreshError, handleRefreshError);

// Register Subscription Event Listeners
subscription.on(subscription.events.notification, handleSubscriptionNotification);
subscription.on(subscription.events.removeSuccess, handleRemoveSubscriptionSuccess);
subscription.on(subscription.events.removeError, handleRemoveSubscriptionError);
subscription.on(subscription.events.renewSuccess, handleSubscriptionRenewSuccess);
subscription.on(subscription.events.renewError, handleSubscriptionRenewError);
subscription.on(subscription.events.subscribeSuccess, handleSubscribeSuccess);
subscription.on(subscription.events.subscribeError, handleSubscribeError);

// Define Event Handlers
function handleSubscriptionNotification(msg) {
    console.log('SUBSCRIPTION NOTIFICATION.....');
    console.log(util.inspect(msg, {showHidden: true, depth: null}));
}

function handleRemoveSubscriptionSuccess(data) {
    console.log('REMOVE SUBSCRIPTION SUCCESS DATA: ', data);
}

function handleRemoveSubscriptionError(data) {
    console.log('REMOVE SUBSCRIPTION ERROR DATA: ', data);
}

function handleSubscriptionRenewSuccess(data) {
    console.log('RENEW SUBSCRIPTION SUCCESS DATA: ', data);
}

function handleSubscriptionRenewError(data) {
    console.log('RENEW SUBSCRIPTION ERROR DATA: ', data);
}

function handleSubscribeSuccess(data) {
    // console.log(data);
    console.log('SUBSCRIPTION CREATED SUCCESSFULLY');
}

function handleSubscribeError(data) {
    console.log('FAILED TO CREATE SUBSCRIPTION: ', data);
}

/**
 * Platform Event Handlers
 **/
function handleLoginSuccess(data) {
    // UNCOMMENT TO VIEW LOGIN DATA
    console.log('LOGIN SUCCESS DATA: ', data.json());
}

function handleLoginError(data) {
    console.log('LOGIN FAILURE DATA: ', data);
}

function handleLogoutSuccess(data) {
    console.log('LOGOUT SUCCESS DATA: ', data);
}

function handleLogoutError(data) {
    console.log('LOGOUT FAILURE DATA: ', data);
}

function handleRefreshSuccess(data) {
    console.log('REFRESH SUCCESS DATA: ', data);
}

function handleRefreshError(data) {
    console.log('REFRESH FAILURE DATA: ', data);
    console.log('Initialing Login again :');
    login();
}

server.listen(3001);
server.on('listening', function() {
    console.log('Server is listening on port: ', 3001);
});
server.on('close', function() {
    console.log('Server has closed and is no longer accepting connections');
});
server.on('error', function(err) {
    console.error(err);
});
server.on('request', inboundRequest);

function inboundRequest(req, res) {
    console.log('Inbound Request');
}

Hi @Phong Vu this is my complete code that i am using but still not able to receive notification

1 comment
1 |3000

Up to 8 attachments (including images) can be used with a maximum of 1.0 MiB each and 10.0 MiB total.

Phong Vu avatar image Phong Vu ♦♦ commented ·

I copy/paste your code and run it locally and it works well.

The only thing I needed to change was to quote the extension number "101" NOT as a number 101.

function login() {
    return platform.login({
            username: "",
            password: "",
            extension: "101"
        })


0 Likes 0 ·

Developer sandbox tools

Using the RingCentral Phone for Desktop, you can dial or receive test calls, send and receive test SMS or Fax messages in your sandbox environment.

Download RingCentral Phone for Desktop:

Tip: switch to the "sandbox mode" before logging in the app:

  • On MacOS: press "fn + command + f2" keys
  • On Windows: press "Ctrl + F2" keys