PubNub Notifications JavaScript Quick Start

Last updated: 2021-12-05 Contributors Byrne ReeseJohn WangPaco Vu
Edit this page

Welcome to the RingCentral Platform. RingCentral is the leading unified communications platform. From one system developers can integrate with, or build products around all the ways people communicate today: SMS, voice, fax, chat and meetings.

In this Quick Start, we are going to help you subscribe for PubNub push notifications using our Push Notifications API, which allows your application receiving notifications on a selected events. Let's get started.

Create an App

The first thing we need to do is create an app in the RingCentral Developer Portal. This can be done quickly by clicking the "Create Notifications App" button below. Just click the button, enter a name and description if you choose, and click the "Create" button. If you do not yet have a RingCentral account, you will be prompted to create one.

Create Notifications App

  1. Login or create an account if you have not done so already.
  2. Go to Console/Apps and click 'Create App' button.
  3. Select "REST API App" under "What type of app are you creating?" Click "Next."
  4. Under "Authentication" select "Password-based auth flow."
  5. Under "Security" add the following permissions:
    • SMS
  6. Under "Security" select "This app is private and will only be callable using credentials from the same RingCentral account."

When you are done, you will be taken to the app's dashboard. Make note of the Client ID and Client Secret. We will be using those momentarily.

Download and edit a .env file

Follow the instructions found in our guide to running Developer Guide code samples. Or:

  1. Download our env-template and save it as a file named .env.
  2. Edit your newly downloaded .env file, setting its variables with the proper values for the app you created above.

Subscribe to a push notification

Install RingCentral JavaScript SDK

$ npm install @ringcentral/sdk --save
$ npm install @ringcentral/subscriptions --save
$ npm install dotenv --save

Create and edit pubnub-notification.js

Create a file called pubnub-notification.js. Be sure to edit the variables in ALL CAPS with your app and user credentials.

const RC   = require('@ringcentral/sdk').SDK
const Subs = require('@ringcentral/subscriptions').Subscriptions
require('dotenv').config();

var rcsdk = new RC({
    'server':       process.env.RC_SERVER_URL,
    'clientId':     process.env.RC_CLIENT_ID,
    'clientSecret': process.env.RC_CLIENT_SECRET
});
var platform = rcsdk.platform();
platform.login({
    'username':  process.env.RC_USERNAME,
    'password':  process.env.RC_PASSWORD,
    'extension': process.env.RC_EXTENSION
})

var subscriptions = new Subs({ sdk: rcsdk });
var subscription = subscriptions.createSubscription({
    pollInterval: 10 * 1000, renewHandicapMs: 2 * 60 * 1000
});

platform.on(platform.events.loginSuccess, () => {
  subscribe_for_SMS_notification()
});

function subscribe_for_SMS_notification() {
  subscription.setEventFilters(['/restapi/v1.0/account/~/extension/~/message-store/instant?type=SMS'])
    .register()
    .then(function(subscriptionResponse) {
      console.log("Ready to receive incoming SMS via PubNub.")
    })
    .catch(function(e) {
      console.error(e);
      throw e;
    });
}

subscription.on(subscription.events.notification, function(msg) {
  console.log(msg.body);
});

Run your code

You are almost done. Now run your script.

$ node pubnub-notification.js

Install RingCentral Python SDK

$ pip install ringcentral python-dotenv

Create and Edit pubnub_notification.py

Create a file called pubnub_notification.py using the contents below.

#!/usr/bin/env python
from ringcentral import SDK
from multiprocessing import Process
from time import sleep
from ringcentral.subscription import Events
import os,sys

rcsdk = SDK( os.environ.get('RC_CLIENT_ID'),
             os.environ.get('RC_CLIENT_SECRET'),
             os.environ.get('RC_SERVER_URL') )
platform = rcsdk.platform()

try:
  platform.login(os.environ.get('RC_USERNAME'),
                 os.environ.get('RC_EXTENSION'),
                 os.environ.get('RC_PASSWORD') )
except:
  sys.exit("Unable to authenticate to platform. Check credentials.")

def on_message(msg):
    print (msg)

def pubnub():
    try:
        s = rcsdk.create_subscription()
        s.add_events(['/account/~/extension/~/message-store/instant?type=SMS'])
        s.on(Events.notification, on_message)
        res = s.register()
        try:
            print("Wait for notification...")
        except Exception as e:
            print (e)
            sys.exit(1)
        while True:
            sleep(0.1)

    except KeyboardInterrupt:
        print("Pubnub listener stopped...")

p = Process(target=pubnub)
try:
    p.start()
except KeyboardInterrupt:
    p.terminate()
    print("Stopped by User")
    sys.exit(1)

Run your code

You are almost done. Now run your script.

$ python pubnub_notification.py

Install RingCentral PHP SDK

$ curl -sS https://getcomposer.org/installer | php
$ php composer.phar require ringcentral/ringcentral-php vlucas/phpdotenv

Create and edit pubnub-notification.php

Create a file called pubnub-notification.php using the contents below.

<?php
require('vendor/autoload.php');
$dotenv = Dotenv\Dotenv::createImmutable(__DIR__ . '/../');
$dotenv->load();
use RingCentral\SDK\Subscription\Events\NotificationEvent;
use RingCentral\SDK\Subscription\Subscription;

$rcsdk = new RingCentral\SDK\SDK( $_ENV['RC_CLIENT_ID'],
                                  $_ENV['RC_CLIENT_SECRET'],
                                  $_ENV['RC_SERVER_URL'] );
$platform = $rcsdk->platform();
$platform->login( $_ENV['RC_USERNAME'],
                  $_ENV['RC_EXTENSION'],
                  $_ENV['RC_PASSWORD'] );

$subscription = $rcsdk->createSubscription();
$subscription->addEvents(array('/restapi/v1.0/account/~/extension/~/message-store/instant?type=SMS'));
$subscription->addListener(Subscription::EVENT_NOTIFICATION, function (NotificationEvent $e) {
    print_r($e->payload()['body']);
});
$subscription->setKeepPolling(true);
$subscription->register();
?>

Run your code

You are almost done. Now run your script.

$ php pubnub-notification.php

Create a Visual Studio project

  • Choose Console Application .Net Core -> App
  • Select Target Framework .NET Core 2.1
  • Enter project name "PubNub_Notifications"
  • Add NuGet package RingCentral.Net (4.1.0) SDK
  • Add NuGet package RingCentral.Net.PubNubPCL (1.3.1) SDK

Edit the file Program.cs

Be sure to edit the variables in ALL CAPS with your app and user credentials.

package PubNub_Notifications;

import java.io.IOException;

import com.ringcentral.*;
import com.ringcentral.definitions.*;
import com.ringcentral.pubnub.Subscription;

public class PubNub_Notifications {
    static RestClient restClient;

    public static void main(String[] args) {
        try {
            PubNubNotifications();
        } catch (RestException | IOException e) {
            e.printStackTrace();
        }
    }

    public static void PubNubNotifications() throws RestException, IOException {
    restClient = new RestClient(
        Environment.GetEnvironmentVariable("RC_CLIENT_ID"),
        Environment.GetEnvironmentVariable("RC_CLIENT_SECRET"),
        Environment.GetEnvironmentVariable("RC_SERVER_URL"));
    restClient.Authorize(
        Environment.GetEnvironmentVariable("RC_USERNAME"),
        Environment.GetEnvironmentVariable("RC_EXTENSION"),
        Environment.GetEnvironmentVariable("RC_PASSWORD")).Wait();

        var eventFilters = new String[] {
            "/restapi/v1.0/account/~/extension/~/message-store/instant?type=SMS"
        };
        Subscription subscription = new Subscription(restClient, eventFilters, (message)->{
            var gs = new Gson();
            if (message.contains("instant?type=SMS")) {
                InstantMessageEvent notification = gs.fromJson( message, InstantMessageEvent.class);
                InstantMessageEventBody body = notification.body;
                System.out.println(body.subject);
            }
        });

        subscription.subscribe();
        System.out.println("Ready to receive incoming SMS via PubNub.");

        try {
            while (true)
            {
                Thread.sleep(10000);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

Run your app

You are almost done. Now run your app from Visual Studio and send an SMS message to the phone number specified in the .

Create a Java project (using Eclipse IDE)

  • Create a new Java project
  • Select the Gradle Project wizard
  • Enter project name "PubNub_Notifications"
  • Open the build.gradle file and add the RingCentral Java SDK to the project as shown below:
dependencies {
    // ...
    compile 'com.ringcentral:ringcentral:1.4.0'
    compile 'com.ringcentral:ringcentral-pubnub:1.0.0'
}

Create a new Java Class

Select "File -> New -> Class" to create a new Java class named "PubNub_Notifications"

package PubNub_Notifications;

public class PubNub_Notifications {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

    }
}

Edit the file "PubNub_Notifications.java".

Be sure to edit the variables in ALL CAPS with your app and user credentials.

package com.ringcentral;

import com.ringcentral.*;
import com.ringcentral.definitions.*;
import com.ringcentral.pubnub.Subscription;
import java.io.IOException;
import com.google.gson.Gson;

public class PubNubQuickStart {
    static RestClient rc;

    public static void main(String[] args) {
        var obj = new PubNubQuickStart();
    rc = new RestClient( System.getenv("RC_CLIENT_ID"),
                 System.getenv("RC_CLIENT_SECRET"),
                 System.getenv("RC_SERVER_URL") );
    try {
        rc.authorize( System.getenv("RC_USERNAME"),
              System.getenv("RC_EXTENSION"),
              System.getenv("RC_PASSWORD") );
        obj.pubnub_notifications();
    } catch (RestException | IOException e) {
        e.printStackTrace();
    }
    }

    public void pubnub_notifications() throws RestException, IOException {
        var eventFilters = new String[] {
            "/restapi/v1.0/account/~/extension/~/message-store/instant?type=SMS"
        };
        Subscription subscription = new Subscription(rc, eventFilters, (message) -> {
        var gs = new Gson();
        if (message.contains("instant?type=SMS")) {
            InstantMessageEvent notification = gs.fromJson( message, InstantMessageEvent.class);
            InstantMessageEventBody body = notification.body;
            System.out.println(body.subject);
        }
        });

        subscription.subscribe();
        System.out.println("Ready to receive incoming SMS via PubNub.");

        try {
            while (true) {
        Thread.sleep(10000);
        }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

Run your app

You are almost done. Now run your app from Eclipse.

Install RingCentral Ruby SDK

$ gem install ringcentral-sdk dotenv

Create and edit pubnub_notification.rb

Create a file called pubnub_notification.rb using the contents below.

require 'ringcentral'
require 'subscription'
require 'dotenv/load'

$rc = RingCentral.new( ENV['RC_CLIENT_ID'],
                       ENV['RC_CLIENRT_SECRET'],
                       ENV['RC_SERVER_URL'] )

$rc.authorize( username: ENV['RC_USERNAME'],
               extension: ENV['RC_EXTENSION'],
               password: ENV['RC_PASSWORD'] )

def createSubscription(callback)
    events = [
        '/restapi/v1.0/account/~/extension/~/message-store/instant?type=SMS',
    ]
    subscription = PubNub.new($rc, events, lambda { |message|
        callback.call(message)
    })
    subscription.subscribe()
    puts "Waiting for incoming SMS message ..."
    while 1
        sleep(5)
    end
end

createSubscription(lambda { |msg|
    puts msg
})

Run your code

You are almost done. Now run your script.

$ ruby pubnub_notification.rb

Graduate Your App

Congratulations on creating your first RingCentral application. The last step is to graduate your application. We recommend going through this process for your first application so you can understand the steps to take in the future, but also to come to appreciate the care taken by RingCentral to ensure that only high-quality apps are allowed into our production environment.