API Spotlight: SMS API

Mike Stowe
RingCentral Developers
5 min readApr 2, 2018

--

Check our updated tutorials for PHP, C#, Node, and Python

They say sharing is caring… and what’s a better way to highlight how to use the SMS and Subscription API, as well as show others you care than by making a PUN SMS App?

Want to test it out? Try texting “pun” to (507) 208–7802

So without further ado, here’s how to do just that using RingCentral’s APIs and your RingCentral Developer Phone number:

Step 1: Create Our Pun App

In the RingCentral Developer Console, click on “Create App.” Give your app a name (such as “My Awesome Pun App”), a description, and click next.

On the next screen, set your app to “Private” and select “Server-only (No UI)” for a platform type (this is required for the auth flow we will be using).

Finally, for permissions needed, select Edit Messages, SMS, and Webhook Subscriptions:

Step 2: Start our Script

Now that we have our application setup, we’ll need to create a script to handle incoming/ outgoing requests. Essentially, this script will be called by a RingCentral webhook when the user sends a SMS message to our phone number, and then sends back an API request with the details of the joke SMS.

It’s important to note, that for security purposes, RingCentral’s Subscription (Event Webhook) API requires that the script return back a unique validation token.

To get started, we’ll create our incoming.php file with the following code:

<?php
// Get validation token
$v = isset($_SERVER['HTTP_VALIDATION_TOKEN']) ? $_SERVER['HTTP_VALIDATION_TOKEN'] : '';
// Return validation token as header
if (strlen($v) > 0) {
header("Validation-Token: {$v}");
}

Step 3: Setup the Webhook

With the script setup, we’re now ready to setup our event subscription to send all SMS messages received to our script for handling.

For this step you’ll need to generate a Bearer token using our authentication flow. Learn how to do this in our documentation, or create a Bearer token by using our API Explorer.

First, we need to setup the subscription. We can do this using Postman or another API calling client to send the following request:

POST https://platform.devtest.ringcentral.com/restapi/v1.0/subscriptionAuthorization: Bearer %YOUR_OAUTH_GENERATED_TOKEN%
Content-Type: application/json
{
"eventFilters": ["/restapi/v1.0/account/~/extension/~/message-store"],
"deliveryMode": {
"transportType": "WebHook",
"address": "https://puns.theapi.ninja/incoming.php",
"encryption": true
},
"expiresIn": 604800
}

If the subscription is working, you’ll receive the following JSON Post to request to your incoming.php script:

{
"uuid": "6960816910640057067",
"event": "/restapi/v1.0/account/237532004/extension/237532004/message-store",
"timestamp": "2018-03-26T21:47:40.685Z",
"subscriptionId": "84a0ab34-7585-498d-bc22-0258af92dae8",
"ownerId": "237532004",
"body": {
"extensionId": 237532004,
"lastUpdated": "2018-03-26T21:47:26.469+0000",
"changes": [{
"type": "SMS",
"newCount": 1,
"updatedCount": 0
}]
}
}

To verify this is working (or for debugging purposes) you can collect the incoming JSON request using file_get_contents('php://input').

Step 4: Add In Our Puns

Now that the subscription is setup, we’re ready to start building out our array of funny puns. In this case, it’s just a simple PHP array that we’ll randomly grab the pun out of for our reply.

$puns = array(
'I wanted to be an astronaut, but I kept spacing out',
'I used to work for Coca Cola, but then I got canned',
'I tried being a window washer, but it turned out to be a real pane',
'I tried being a plumber, but my career went down the drain'
);

Step 5: Port in the SDK

Now the fun starts. To make the process easier, we’re going to take advantage of the RingCentral PHP SDK. You can find the PHP SDK here.

// Include Libraries
require('vendor/autoload.php');

Once the SDK has been added to your script, we will need to setup the RingCentral SDK client. To do this we will instantiate the class, defining our client ID, client secret, and environment (in this case the Sandbox):

// Setup Client
$sdk = new RingCentral\SDK\SDK(CLIENT_ID, CLIENT_SECRET, RingCentral\SDK\SDK::SERVER_SANDBOX);

Then we’ll check to see if we have an access token, and if not, request one via the password flow:

// Login via API
if (!$sdk->platform()->loggedIn()) {
$sdk->platform()->login(username, extension, password);
}

If you receive an unauthorized grant type error, make sure you setup your app as Server-only (No UI). If you selected Server/ Web by accident, you will not have access to the necessary auth flow to login using your username, extension (optional), and password.

Step 6: Get Unread Messages

Now we will get the most recent incoming text message via the /message-store resource. To limit what is returned, we will add the following parameters: availability, direction, and messageType.

// Get Unread SMS Messages
$apiResponse = $sdk->platform()->get('/account/~/extension/~/message-store?availability=Alive&direction=Inbound&messageType=SMS&readStatus=Unread');
$resp = $apiResponse->json();
$lastMessage = $resp->records[0];

Now that we have the last message’s data, we can get the information that will be required to respond to their request — including their phone number, and the pun we want to send:

// Set SMS Information
$smsId = $lastMessage->id;
$phoneFrom = $lastMessage->from->phoneNumber;
$phoneTo = $lastMessage->to[0]->phoneNumber;
$keyword = strtolower($lastMessage->subject);
// Select a Random Pun (remember array index is 0)
$rand = rand(1, count($puns)) - 1;

Step 7: Respond and Delete Text

Finally, in preparation to send the request we need to format the data as required by the SMS API. To make the formatting easier, the RingCentral SDK simply takes an array that it will automatically convert to JSON later:

// Setup data array to use for the SMS Post request
$data = array(
'from' => array('phoneNumber' => $phoneTo),
'to' => array(array('phoneNumber' => $phoneFrom)),
'text' => $puns[$rand]
);

The last step is to make sure the user is in fact requesting a pun from us by checking to see that they either wrote “pun” or “pun” with the Sandbox watermark prepended.

If the keyword is a match we will then send the SMS message, and delete their incoming request:

// Send SMS and Delete Message
if (preg_match('/^(Test SMS using a RingCentral Developer account - )?pun$/i', $keyword)) {
$sdk->platform()->post('/account/~/extension/~/sms', $data);
$sdk->platform()->delete('/account/~/extension/~/message-store/'.$smsId.'?purge=true');
}
?>

Test it out! Try texting “pun” to (507) 208–7802

And just like that you’ve created your own custom pun app!

A Final Caveat

While congratulations are in order, there’s one final thing to be aware of. Subscription requests expire after 7 days — so you’ll want to create a script with a cronjob that calls the subscription API and renews your message subscription at least once a week. Other than that, you’re all set!

--

--

Mike Stowe
RingCentral Developers

Developer, actor, and a *really* bad singer. Fan of APIs, Microservices, and #K8s.