PubNub notifications Quick Start

Last updated: 2024-07-22Contributors
Edit this page

PubNub support is deprecated. Please migrate to WebSockets.

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 and obtain credentials

The first thing we need to do is create an app in the RingCentral Developer Console. 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 "Auth" select "JWT auth flow."
  5. Under "Security" add the following permissions:
    • WebhookSubscriptions
    • 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.
    • RC_APP_CLIENT_ID - set to the Client ID of the app you created above
    • RC_APP_CLIENT_SECRET - set to the Client Secret of the app you created above
    • RC_USER_JWT - set to the JWT credential you created for yourself

Subscribe to a push notification

Install RingCentral JavaScript SDK

$ npm install @ringcentral/sdk --save
$ npm install @ringcentral/subscriptions-deprecated --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 Subscriptions = require('@ringcentral/subscriptions-deprecated').Subscriptions
require('dotenv').config();

var rcsdk = new RC({
    'server':       process.env.RC_SERVER_URL,
    'clientId':     process.env.RC_APP_CLIENT_ID,
    'clientSecret': process.env.RC__APP_CLIENT_SECRET
});
var platform = rcsdk.platform();
platform.login({ 'jwt':  process.env.RC_USER_JWT })

var subscriptions = new Subscriptions({ 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/python

# You get the environment parameters from your
# application dashbord in your developer account
# https://developers.ringcentral.com

import os
import sys

from dotenv import load_dotenv
from ringcentral import SDK
from multiprocessing import Process
from time import sleep
from ringcentral.subscription import Events
load_dotenv()

rcsdk = SDK( os.environ.get('RC_APP_CLIENT_ID'),
             os.environ.get('RC__APP_CLIENT_SECRET'),
             os.environ.get('RC_SERVER_URL') )
platform = rcsdk.platform()
try:
  platform.login( jwt=os.environ.get('RC_USER_JWT') )
except Exception as e:
  sys.exit("Unable to authenticate to platform: " + str(e))

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
/// Remember to modify the path ./../ pointing to the location where the RingCentral SDK was installed and the .env file was saved!
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_APP_CLIENT_ID'],
                                  $_ENV['RC_APP_CLIENT_SECRET'],
                                  $_ENV['RC_SERVER_URL'] );
$platform = $rcsdk->platform();
$platform->login( [ "jwt" => $_ENV['RC_USER_JWT'] ] );

$subscription = $rcsdk->createSubscription('Pubnub');
$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.

using System;
using System.Threading.Tasks;
using RingCentral;
using dotenv.net;

DotEnv.Load();

namespace PubNub_Notifications
{
class Program
{
    static RestClient restClient;
    static void Main(string[] args)
    {
    restClient = new RestClient(
        Environment.GetEnvironmentVariable("RC_APP_CLIENT_ID"),
        Environment.GetEnvironmentVariable("RC__APP_CLIENT_SECRET"),
        Environment.GetEnvironmentVariable("RC_SERVER_URL"));
    restClient.Authorize(
        Environment.GetEnvironmentVariable("RC_USER_JWT")).Wait();
        pubnub_notification().Wait();
    }
    static private async Task pubnub_notification()
    {
        try
        {
        var pubNubExtension = new PubNubExtension();
        await rc.InstallExtension(pubNubExtension);
            var eventFilters = new[]
            {
                "/restapi/v1.0/account/~/extension/~/message-store/instant?type=SMS"
            };
        var subscription = await pubNubExtension.Subscribe(eventFilters, message =>
        {
        Console.WriteLine("I got a notification:");
        Console.WriteLine(message);
        });
        // Wait for 60 seconds before the app exits
        // In the mean time, send SMS to trigger a notification for testing purpose
        await Task.Delay(60000);
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex);
        }
    }
}
}

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_APP_CLIENT_ID"),
                 System.getenv("RC_APP_CLIENT_SECRET"),
                 System.getenv("RC_SERVER_URL") );
    try {
        rc.authorize( System.getenv("RC_USER_JWT") );
        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.

#!usr/bin/ruby

# You get the environment parameters from your
# application dashbord in your developer account
# https://developers.ringcentral.com

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

$rc = RingCentral.new(ENV['RC_APP_CLIENT_ID'],
                      ENV['RC__APP_CLIENT_SECRET'],
                      ENV['RC_SERVER_URL'])

$rc.authorize(jwt: ENV['RC_USER_JWT'])

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