WebSockets Quick Start

Last updated: 2024-02-28Contributors
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 WebSockets 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:
    • WebSocketsSubscriptions
  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_CLIENT_ID - set to the Client ID of the app you created above
    • RC_CLIENT_SECRET - set to the Client Secret of the app you created above
    • RC_JWT - set to the JWT credential you created for yourself

Subscribe to an event via WebSockets

Install RingCentral JavaScript SDK 5.0.0+

$ npm init # init npm project
$ npm install @ringcentral/sdk --save
$ npm install @ringcentral/subscriptions --save
$ npm install dotenv --save

Create and edit websockets.js

Create a file called websockets.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').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({ 'jwt':  process.env.RC_JWT })

var subscriptions = new Subscriptions({ sdk: rcsdk });
var subscription = subscriptions.createSubscription();

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

async function subscribe_for_SMS_notification() {
    subscription.on(subscription.events.notification, evt => {
        console.log(JSON.stringify(evt, null, 2));
    });
    await subscription
        .setEventFilters(['/restapi/v1.0/account/~/extension/~/message-store/instant?type=SMS'])
        .register()
        .then(function(subscriptionResponse) {
            console.log("Ready to receive incoming SMS via WebSocket.")
        })
        .catch(function(e) {
            console.error(e);
            throw e;
        });
}

Run your code

You are almost done. Now run your script.

$ node websockets.js

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.

// ref: https://github.com/tylerlong/RingCentral.WebSocket.Demo

using RingCentral;
using dotenv.net;
using RingCentral.Net.WebSocket;

var envVars = DotEnv.Read();

var rc = new RestClient(envVars["RINGCENTRAL_CLIENT_ID"], envVars["RINGCENTRAL_CLIENT_SECRET"], envVars["RINGCENTRAL_SERVER_URL"]);
await rc.Authorize(envVars["RINGCENTRAL_JWT_TOKEN"]);
Console.WriteLine(rc.token.access_token);

var wsExtension = new WebSocketExtension(new WebSocketOptions
{
    debugMode = true
});
await rc.InstallExtension(wsExtension);
await wsExtension.Subscribe(new string[] {"/restapi/v1.0/account/~/extension/~/message-store"}, message =>
{
    Console.WriteLine(message);
});

// Trigger some notifications for testing purpose
var timer = new PeriodicTimer(TimeSpan.FromMinutes(10));
while (await timer.WaitForNextTickAsync())
{
    await rc.Refresh();
    await rc.Restapi().Account().Extension().CompanyPager().Post(new CreateInternalTextMessageRequest
    {
        text = "Hello world",
        from = new PagerCallerInfoRequest
        {
            extensionId = rc.token.owner_id
        },
        to = new []{ new PagerCallerInfoRequest
        {
            extensionId = rc.token.owner_id
        }}
    });
    Console.WriteLine("Pager sent");
}

await rc.Revoke(); 

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 "WebSockets_Notifications"

package WebSockets_Notifications;

public class WebsSockets_Notifications {

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

    }
}

Edit the file "WebSockets_Notifications.java".

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

// Ref: https://github.com/ringcentral/ringcentral-websocket-java/blob/main/lib/src/test/java/com/ringcentral/websocket/LibraryTest.java
package com.ringcentral;

import com.ringcentral.RestClient;
import com.ringcentral.RestException;
import com.ringcentral.definitions.CreateInternalTextMessageRequest;
import com.ringcentral.definitions.PagerCallerInfoRequest;
import com.ringcentral.websocket.Subscription;
import java.io.IOException;
import com.google.gson.Gson;

public class WebSocketQuickStart {
    static RestClient rc;
    public static void main(String[] args) throws RestException, IOException, InterruptedException {
      RestClient rc = new RestClient(
            System.getenv("RINGCENTRAL_CLIENT_ID"),
            System.getenv("RINGCENTRAL_CLIENT_SECRET"),
            System.getenv("RINGCENTRAL_SERVER_URL")
        );

        rc.authorize(
            System.getenv("RINGCENTRAL_JWT_TOKEN")
        );
        final String[] message = {null};
        Subscription subscription = new Subscription(rc,
            new String[]{"/restapi/v1.0/account/~/extension/~/message-store"},
            (jsonString) -> {
                message[0] = jsonString;
            }
        );

        subscription.subscribe();

        // sleep and wait for notifications
        Thread.sleep(60000);
    }
}

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 websockets.rb

Create a file called websockets.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'

Dotenv.load

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

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

events = [
  '/restapi/v1.0/account/~/extension/~/message-store/instant?type=SMS',
]
subscription = WS.new($rc, events, lambda { |message|
  puts message
})
subscription.subscribe()

puts "Waiting for incoming SMS message ..."
while 1
    sleep(5)
end

Run your code

You are almost done. Now run your script.

$ ruby websockets.rb

Install RingCentral Python SDK

$ pip install ringcentral python-dotenv

Create and edit websocket_quick_start.py

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

# Need a .env file with following fields
# RC_SERVER_URL=
# RC_CLIENT_ID=
# RC_CLIENT_SECRET=
# RC_JWT=

from ringcentral import SDK
from dotenv import load_dotenv
import asyncio
import os
from ringcentral.websocket.events import WebSocketEvents

def on_notification(message):
    print("\n Subscription notification:\n")
    print(message)

def on_sub_created(sub):
    print("\n Subscription created:\n")
    print(sub.get_subscription_info())
    print("\n Please go and change your user status \n")

def on_ws_created(web_socket_client):
    print("\n New WebSocket connection created:")
    print(web_socket_client.get_connection_info())

async def main():
    load_dotenv(override=True)
    sdk = SDK(
        os.environ['RC_CLIENT_ID'],
        os.environ["RC_CLIENT_SECRET"],
        os.environ["RC_SERVER_URL"],
    )
    platform = sdk.platform()
    platform.login(jwt=os.environ["RC_JWT"])

    try:
        web_socket_client = sdk.create_web_socket_client()
        web_socket_client.on(WebSocketEvents.connectionCreated, on_ws_created)
        web_socket_client.on(WebSocketEvents.subscriptionCreated, on_sub_created)
        web_socket_client.on(WebSocketEvents.receiveSubscriptionNotification, on_notification)
        await asyncio.gather(
            web_socket_client.create_new_connection(), 
            web_socket_client.create_subscription(["/restapi/v1.0/account/~/extension/~/presence"])
        )
    except KeyboardInterrupt:
        print("Stopped by User")


if __name__ == "__main__":
    asyncio.get_event_loop().run_until_complete(main())

fill in .env file

You'll need RINGCENTRAL_SERVER_URL, RINGCENTRAL_CLIENT_ID, RINGCENTRAL_CLIENT_SECRET and RINGCENTRAL_JWT_TOKEN. All of them can be generated from developer portal.

Run your code

You are almost done. Now run your script.

$ python websocket_quick_start.py

Install RingCentral PHP SDK

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

Create and edit websockets.php

Create a file called websockets.php using the contents below.

<?php
/* You get the environment parameters from your 
   application dashbord in your developer account 
   https://developers.ringcentral.com */

require('vendor/autoload.php');
$dotenv = Dotenv\Dotenv::createImmutable(__DIR__);
$dotenv->load();

use RingCentral\SDK\WebSocket\WebSocket;
use RingCentral\SDK\WebSocket\Subscription;
use RingCentral\SDK\WebSocket\Events\NotificationEvent;

$rcsdk = new RingCentral\SDK\SDK( $_ENV['RC_CLIENT_ID'],
                                  $_ENV['RC_CLIENT_SECRET'],
                                  $_ENV['RC_SERVER_URL'] );
$platform = $rcsdk->platform();
$platform->login( [ "jwt" => $_ENV['RC_JWT'] ] );

$websocket = $rcsdk->initWebSocket();
$websocket->connect();

$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 'Notification ' . print_r($e->payload(), true) . PHP_EOL;
});
$subscription->register();
?>

Run your code

You are almost done. Now run your script.

$ php websockets.php

Test your WebSocket subscription

Now that your sample app is running, trigger a notification by sending yourself an SMS.