Using RingCentral API in Google Apps Script
See how to use the RingCentral API in Google Apps Script.
Join the DZone community and get the full member experience.
Join For Free
Google Apps Script is provided by Google to help developers to create and publish g-suit add-ons easily, and RingCentral provides cloud communication services such as SMS, Call, and Fax.
In this article, we show how to authorize and call the RingCentral API in Google Apps Script so we can easily integrate RingCentral service with Google Sheets, Docs, Slides, and Forms.
You might also like: Work With RingCentral APIs
Prerequisites
- 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 log in to our RingCentral Developers account and create an app. To create an app, follow the steps in this tutorial.
Make sure that in step 2 you select Browser-based for platform type. We need an authorization code flow to authorize the RingCentral API in the Google apps script. The apps script is run as a web app.

In Step3, add the permissions that you need and keep the redirect URI blank. We will add the redirect URI in the 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 the script editor:

Just create a new GS file, sucj as Code.gs
Setup OAuth2 Library
For RingCentral API service, it uses OAuth2 for authorization. So, we need to import the OAuth2 library. Just follow the steps to set up.

Then, we need to add the following redirect URI into the RingCentral app in the RingCentral developer app settings.
https://script.google.com/macros/d/{SCRIPT ID}/usercallback
We can find SCRIPT ID in the 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 the Sidebar
We also need to add an 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 testing, we need to connect the script with Google Docs. Go to Run>>Test as add-on, select docs, and click the Test button.

Run the add-on and click the authorization link in the 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 here. Hopefully this article was helpful. Please let us know what you think by leaving your questions and comments.
Further Reading
Opinions expressed by DZone contributors are their own.
Trending
-
Working on an Unfamiliar Codebase
-
Building and Deploying Microservices With Spring Boot and Docker
-
What Is mTLS? How To Implement It With Istio
-
How To Design Reliable IIoT Architecture
Comments