Using RingCentral API in Google Apps Script

Embbnux Ji
RingCentral Developers
4 min readSep 29, 2019

Google Apps Script is provided by Google to help developer to create and publish g-suit add-on easily. In this article, we show how to authorize and call RingCentral services in Apps Script. So we can easy to integrate RingCentral service with Google Sheets, Docs, Slides, and Forms.

Prerequisites

  1. A free RingCentral Developer account to create a RingCentral app

2. Google Apps Script

Create a new RingCentral app

Before we can use the RingCentral API, we will need to create or login to our RingCentral Developers account and create an app. To create an app, go to RingCentral developer website and follow the steps in this tutorial.

Make sure that in App Type you select Browser-based for platform type. We need authorization code flow to authorize RingCentral api in google apps script. Actually apps script is run as web app.

In Step3, add permissions that you need, and keep redirect URI blank. We will add redirect URI in next step.

Create a Google Apps Script project

Before we start to code in Google Apps Script, we need to create a new project. And then open script editor:

Just create a new GS file, such as Code.gs

Setup OAuth2 library

For RingCentral API service, it uses OAuth2 for authorization. So we need to import OAuth2 library. Just following the steps to setup.

Then need to add following redirect URI into RingCentral app in RingCentral developer app settings.

https://script.google.com/macros/d/{SCRIPT ID}/usercallback

We can find SCRIPT ID in Google script page address:

Create OAuth service:

var RC_APP = {
CLIENT_ID: 'your_ringcentral_app_client_id',
CLIENT_SECRET: 'your_ringcentral_app_client_secret',
SERVER: 'https://platform.devtest.ringcentral.com', // sandbox or production server
};
function getOAuthService() {
return (
OAuth2.createService('RC')
.setAuthorizationBaseUrl(RC_APP.SERVER + '/restapi/oauth/authorize')
.setTokenUrl(RC_APP.SERVER + '/restapi/oauth/token')
.setClientId(RC_APP.CLIENT_ID)
.setClientSecret(RC_APP.CLIENT_SECRET)
.setCallbackFunction('authCallback')
.setPropertyStore(PropertiesService.getUserProperties())
.setCache(CacheService.getUserCache())
.setTokenHeaders({
Authorization: 'Basic ' + Utilities.base64EncodeWebSafe(RC_APP.CLIENT_ID + ':' + RC_APP.CLIENT_SECRET)
})
);
}
function logout() {
var service = getOAuthService();
service.reset();
}

Create OAuth redirect callback handler:

function authCallback(callbackRequest) {
try {
var service = getOAuthService()
var authorized = service.handleCallback(callbackRequest);
if (authorized) {
return HtmlService.createHtmlOutput(
'Success! <script>setTimeout(function() { top.window.close() }, 1);</script>'
);
} else {
return HtmlService.createHtmlOutput('Denied');
}
} catch (err) {
console.log('===>ERROR: auth callback', err);
return HtmlService.createHtmlOutput('Denied');
}
}

Add Authorization button in sidebar:

We also need to add authorization button for user login:

function showSidebar() {
var service = getOAuthService();
if (!service.hasAccess()) {
var authorizationUrl = service.getAuthorizationUrl();
var template = HtmlService.createTemplate(
'<a href="<?= authorizationUrl ?>" target="_blank">Authorize</a>. ' +
'Reopen the sidebar when the authorization is complete.');
template.authorizationUrl = authorizationUrl;
var page = template.evaluate();
DocumentApp.getUi().showSidebar(page);
} else {
var res = makeRequest({ path: '/restapi/v1.0/account/~/extension/~' });
var text = JSON.stringify(res, null, 2);
var template = HtmlService.createTemplate('authorized.' + text);
var page = template.evaluate();
DocumentApp.getUi().showSidebar(page);
}
}
function onOpen(e) {
DocumentApp.getUi().createAddonMenu()
.addItem('Start', 'showSidebar')
.addToUi();
}
function onInstall(e) {
onOpen(e);
}

Request RingCentral API with token

function makeRequest(options) {
var method = options.method;
var path = options.path;
var body = options.body;
if (body) {
body = JSON.stringify(body)
}
var service = getOAuthService();
var response = UrlFetchApp.fetch(RC_APP.SERVER + path, {
headers: {
Authorization: 'Bearer ' + service.getAccessToken()
},
payload: body,
contentType: 'application/json',
method: method || 'get',
muteHttpExceptions: true
});
var json = JSON.parse(response.getContentText('utf-8'));
var code = response.getResponseCode();
if (code >= 200 && code < 300) {
return json;
} else if (code == 401 || code == 403) {
console.log(
'error',
'will logout due to get code ',
code,
' when request ',
url,
' with ',
opts
);
service.reset();
throw 'Token expired';
} else {
console.log('error', 'RingCentral Backend Server Error', path, json);
throw 'RingCentral Backend Server Error: ' + (json.message || json.error_description);
}
}
function getExtensionInfo() {
var response = makeRequest({ path: '/restapi/v1.0/account/~/extension/~' });
return response;
}

Test it!

Before test, we need to connect script with google docs. Go to Run>Test as add-on, select docs and click Test button.

Run the add-on, and click authorization link in sidebar to authorize.

After authorization, we can easy to call RingCentral API with token. Such as sending SMS:

function getSMSFromNumber() {
var response = makeRequest({ path: '/restapi/v1.0/account/~/extension/~/phone-number' });
var phoneNumbers = response.records;
var smsSenders = phoneNumbers.filter(
function (p) { return p.features && p.features.indexOf('SmsSender') !== -1 }
);
console.log(smsSenders);
return smsSenders[0].phoneNumber;
}
function sendSMS() {
var senderNumber = getSMSFromNumber();
var response = makeRequest({
path: '/restapi/v1.0/account/~/extension/~/sms',
method: 'post',
body: {
to: [{ phoneNumber: "your_to_number" }],
from: { phoneNumber: senderNumber },
text: "Test SMS message from Platform server"
}
});
return response;
}

More Information

You can find more detailed information about RingCentral OAuth 2.0 and API in here. Hopefully this article was helpful. Please let us know what you think by leaving your questions and comments below.

--

--