Social Messaging Quick Start

Last updated: 2024-04-10Contributors
Edit this page

Calling the RingCentral API for the first time? We recommend you try out getting started experience.

In this quick start, we are going to help you register an application and build your app to list all social messaging contents belong to the authenticated agent.

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 Social Messaging 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 Social Messaging 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:
    • Social Messaging
  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, paying close attention to the following:
    • 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

List agent's contents

const RC = require('@ringcentral/sdk').SDK
const path = require('path')
// Remember to modify the path of your .env file location!
require('dotenv').config({ path: path.resolve(__dirname, '../.env') })

// Initialize the RingCentral SDK and Platform
const rcsdk = new RC({
    'server':       "https://platform.ringcentral.com",
    'clientId':     process.env.RC_CLIENT_ID,
    'clientSecret': process.env.RC_CLIENT_SECRET
});
var platform = rcsdk.platform();

/* Authenticate a user using a personal JWT token */
platform.login({ 'jwt':  process.env.RC_JWT })

platform.on(platform.events.loginSuccess, function(e){
    list_contents("")
});

platform.on(platform.events.loginError, function(e){
    console.log("Unable to authenticate to platform. Check credentials.", e.message)
    process.exit(1)
});

/*
* List contents from all connected channels
*/
async function list_contents(pageToken) {
  try {
    var queryParams = {
      perPage: 50
    }
    if (pageToken != ""){
      queryParams['pageToken'] = pageToken
    }
    let endpoint = "/cx/social-messaging/v1/contents"
    let resp = await platform.get(endpoint, queryParams);
    let jsonObj = await resp.json();

    for (var record of jsonObj.records){
      console.log(record)
    }

    // To read the next page, check and use the nextPageToken in the paging object.
    if (jsonObj.paging.hasOwnProperty('nextPageToken') && jsonObj.paging.nextPageToken != "") {
      var pageToken = jsonObj.paging.nextPageToken
      // Make sure not to exceed the API rate limit of 40 API calls per minute
      sleep(1200)
      console.log("Read content from the next page ...")
      list_contents(pageToken)
    }else{
      console.log("Done reading all pages")
    }
  } catch (e) {
    console.log("CUnable to call list contents API. Error: " + e.message);
  }
}

const sleep = async (ms) => {
  await new Promise(r => setTimeout(r, ms));
from ringcentral import SDK
import os,sys,json,time
from pathlib import Path
from dotenv import load_dotenv
load_dotenv()

#
#  List contents from all connected channels
#
def list_contents(pageToken):
    try:
        queryParams = {
          'perPage': 50
        }
        if pageToken != "":
            queryParams['pageToken'] = pageToken

        endpoint = "/cx/social-messaging/v1/contents"
        resp = platform.get(endpoint, queryParams)
        jsonObj = resp.json_dict()
        for record in jsonObj['records']:
            print(json.dumps(record, indent=2, sort_keys=True))

        # To read the next page, check and use the nextPageToken in the paging object.
        if jsonObj['paging'].get('nextPageToken'):
            pageToken = jsonObj['paging']['nextPageToken']
            # Make sure not to exceed the API rate limit of 40 API calls per minute
            time.sleep(1.2)
            print ("Read contents from the next page ...")
            list_contents(pageToken)
        else:
            print ("Done! No more next page.")
    except Exception as e:
        print ("Unable to call list contents API. " + str(e))

# Instantiate the SDK and get the platform instance
rcsdk = SDK( os.environ.get('RC_CLIENT_ID'),
             os.environ.get('RC_CLIENT_SECRET'),
             "https://platform.ringcentral.com" )
platform = rcsdk.platform()

# Authenticate a user using a personal JWT token
def login():
    try:
      platform.login( jwt=os.environ.get('RC_JWT') )
      list_contents("")
    except Exception as e:
      sys.exit("Unable to authenticate to platform. Check credentials." + str(e))

login()
<?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();

# Instantiate the SDK and get the platform instance
$rcsdk = new RingCentral\SDK\SDK( "https://platform.ringcentral.com",
                                  $_ENV['RC_CLIENT_SECRET'],
                                  $_ENV['RC_SERVER_URL'] );
$platform = $rcsdk->platform();

// Authenticate a user using a personal JWT token
try {
  $platform->login( [ "jwt" => $_ENV['RC_JWT'] ] );
  list_contents("");
} catch (\RingCentral\SDK\Http\ApiException $e) {
  exit("Unable to authenticate to platform. Check credentials. " . $e->getMessage() . PHP_EOL);
}

/*
* List contents from all connected channels
*/
function list_contents($pageToken){
  global $platform;
  try {
    $queryParams = array (
      'perPage' => 50
    );

    if ($pageToken != "")
      $queryParams['pageToken'] = $pageToken;

    $endpoint = "/cx/social-messaging/v1/contents";

    $resp = $platform->get($endpoint, $queryParams);
    $jsonObj = $resp->json();
    foreach ($jsonObj->records as $record){
        print_r (json_encode($record, JSON_PRETTY_PRINT) . PHP_EOL);
    }

    // To read the next page, check and use the nextPageToken in the paging object.
    if (property_exists($jsonObj->paging, 'nextPageToken') && $jsonObj->paging->nextPageToken != "") {
      $pageToken = $jsonObj->paging->nextPageToken;
      // Make sure not to exceed the API rate limit of 40 API calls per minute
      usleep(1200000);
      print ("Read content from the next page ..." . PHP_EOL);
      list_contents($pageToken);
    }else{
      print ("Done reading all pages." . PHP_EOL);
    }
  } catch (\RingCentral\SDK\Http\ApiException $e) {
    print_r ("Unable to call list content API. " . $e->getMessage() . PHP_EOL);
  }
}
?>
require 'ringcentral'
require 'dotenv'
require 'json'

# Remember to modify the path to where you saved your .env file!
Dotenv.load("./../.env")

#
#  List contents from all connected channels
#
def list_contents(pageToken)
    queryParams = {
      'perPage': 50
    }
    if pageToken != ""
      queryParams['pageToken'] = pageToken
    end

    endpoint = "/cx/social-messaging/v1/contents"
    begin
      resp = $platform.get(endpoint, queryParams)
      jsonObj = resp.body
      for record in jsonObj['records'] do
          puts (JSON.pretty_generate(record))
      end
      # To read the next page, check and use the nextPageToken in the paging object.
      if jsonObj['paging']['nextPageToken'] and jsonObj['paging']['nextPageToken'] != ""
        pageToken = jsonObj['paging']['nextPageToken']
        # Make sure not to exceed the API rate limit of 40 API calls per minute
        sleep(1.2)
        puts ("Read contents from the next page.")
        list_contents(pageToken)
      else
        puts ("Done! No more next page.")
      end
    rescue StandardError => e
      puts ("Unable to call list contents API. " + e.to_s)
    end
end

# Instantiate the SDK and get the platform instance
$platform = RingCentral.new( ENV['RC_CLIENT_ID'], ENV['RC_CLIENT_SECRET'], "https://platform.ringcentral.com" )

# Authenticate a user using a personal JWT token
def login()
  begin
    $platform.authorize(jwt: ENV['RC_JWT'])
    list_contents("")
  rescue StandardError => e
    puts ("Unable to authenticate to platform. Check credentials." + e.to_s)
  end
end

login()

Sample response

{
  "records": [
    {
      "id": "65d69849a330900007d1c6d7",
      "creationTime": "2024-02-22T00:41:45Z",
      "lastModifiedTime": "2024-02-22T00:41:45Z",
      "authorIdentityId": "65c3fe3e729ae3000785aac1",
      "body": "Server alive and well!",
      "bodyInputFormat": "Text",
      "categoryIds": [],
      "creatorId": "63317565004",
      "interventionId": null,
      "language": "En",
      "remotelyDeleted": false,
      "sourceId": "65c3fdd9527bf900079cefcb",
      "sourceUri": null,
      "synchronizationStatus": "Success",
      "status": "UserReply",
      "threadId": "65c40163c092e4000768f688",
      "inReplyToContentId": "65d684cc2796550007054f17",
      "inReplyToAuthorIdentityId": "65c40163c092e4000768f685",
      "attachments": [],
      "autoSubmitted": false,
      "identityGroupId": "65c3fe3e729ae3000785aac2",
      "bodyFormatted": {
        "Text": "Server alive and well!",
        "Html": "<p>Server alive and well!</p>"
      },
      "contextData": null,
      "createdFrom": "Api",
      "public": false,
      "published": true,
      "sourceType": "WhatsApp",
      "structuredContentSupported": true,
      "type": "Message",
      "synchronizationError": null,
      "capabilitiesSupported": [
        "template",
        "list"
      ]
    },
    {
      "id": "65d684cc2796550007054f17",
      "creationTime": "2024-02-21T23:18:34Z",
      "lastModifiedTime": "2024-02-22T00:41:45Z",
      "authorIdentityId": "65c40163c092e4000768f685",
      "body": "Great 👍. Sending attachment now to you.",
      "bodyInputFormat": "Text",
      "categoryIds": [],
      "creatorId": null,
      "interventionId": null,
      "language": "En",
      "remotelyDeleted": false,
      "sourceId": "65c3fdd9527bf900079cefcb",
      "sourceUri": null,
      "synchronizationStatus": "Success",
      "status": "Replied",
      "threadId": "65c40163c092e4000768f688",
      "inReplyToContentId": null,
      "inReplyToAuthorIdentityId": "65c3fe3e729ae3000785aac1",
      "attachments": [
        {
          "id": "65d684cc2796550007054f19",
          "creationTime": "2024-02-21T23:18:37Z",
          "lastModifiedTime": "2024-02-21T23:18:37Z",
          "contentType": "image/jpeg",
          "filename": "1511912166322685.jpeg",
          "size": 326705,
          "videoMetadata": [],
          "embedded": false,
          "public": false,
          "attachableId": "65d684cc2796550007054f17",
          "attachableType": "Content",
          "uri": "https://advanced-messaging-demo-1.digital.ringcentral.com/attachments/65d684cc2796550007054f19?xxx"
        }
      ],
      "autoSubmitted": false,
      "identityGroupId": "65c40163c092e4000768f686",
      "bodyFormatted": {
        "Text": "Great 👍. Sending attachment now to you.",
        "Html": "<p>Great 👍. Sending attachment now to you.</p>"
      },
      "contextData": null,
      "createdFrom": "Synchronizer",
      "public": false,
      "published": true,
      "sourceType": "WhatsApp",
      "structuredContentSupported": true,
      "type": "Message",
      "synchronizationError": null,
      "capabilitiesSupported": [
        "template",
        "list"
      ]
    },
    {
      "id": "65d6848c8be02f00072f35f2",
      "creationTime": "2024-02-21T23:17:33Z",
      "lastModifiedTime": "2024-02-21T23:17:44Z",
      "authorIdentityId": "65c3fe3e729ae3000785aac1",
      "body": "Thanks for your message!",
      "bodyInputFormat": "Text",
      "categoryIds": [],
      "creatorId": "63317565004",
      "interventionId": null,
      "language": "En",
      "remotelyDeleted": false,
      "sourceId": "65c3fdd9527bf900079cefcb",
      "sourceUri": null,
      "synchronizationStatus": "Success",
      "status": "UserReply",
      "threadId": "65c40163c092e4000768f688",
      "inReplyToContentId": "65d683cee26da1000789ad3f",
      "inReplyToAuthorIdentityId": "65c40163c092e4000768f685",
      "attachments": [],
      "autoSubmitted": false,
      "identityGroupId": "65c3fe3e729ae3000785aac2",
      "bodyFormatted": {
        "Text": "Thanks for your message!",
        "Html": "<p>Thanks for your message!</p>"
      },
      "contextData": null,
      "createdFrom": "Api",
      "public": false,
      "published": true,
      "sourceType": "WhatsApp",
      "structuredContentSupported": true,
      "type": "Message",
      "synchronizationError": null,
      "capabilitiesSupported": [
        "template",
        "list"
      ]
    }
  ],
  "paging": {
    "pageToken": "eyJ2YWx1ZSI6MTcwODU2MjUwNS44MDgsIm...",
    "perPage": 20,
    "nextPageToken": "eyJ2YWx1ZSI6MTcwNzM0NDIyNi4wLCJmaWVsZ..."
  }
}