RingCentral SMS app Round II

Last time I wrote, I mentioned that I wanted to learn how to receive an SMS using Ring Central’s API and I did an example using RingCentral + ngrok + Formstack, you can check it out here.

I also mentioned that I wanted to develop something I could use in my own home, so this time I decided to use SMS Ring Central’s API to notify me when a light has turned on in my house.
And why the hell would anyone mind if your lights are on?
Well I could enumerate a few examples, but you can use your imagination for that.

I have a few Philips HUE lights in my home, most of them at my game-room / office and a few white lights at bedrooms.

Ingredients needed :

STEPS:

1.- HUE Philips API

You need to discover the IP address of the HUE Philips bridge network.

The easiest way is to try this address: https://discovery.meethue.com/, if you can’t find it there, you can also try this detailed steps from the developers at HUE, or like I did, just check the IP at your router. I have three Google routers inside my home, and they work flawlessly, I just opened the Google Wifi app and checked for all connected devices and looked for the Philips hue IP:

Curious about Google’s wifi routers?
You can check them out here

Now that we have the IP, open up a browser and type your IP address followed by /debug/clip.html
This endpoint is HUE’S bridge API debugger:

Let’s generate a username for our device:

  • In the URL field type : /api
  • In the Message Body field type: {“devicetype”:”my_hue_app#Juan“}
  • Hit the POST button.
What is wrong?

Noticed the error message?
“link button not pressed”
We are missing something important here:

The problem is, that we have to physically authenticate with the device before attempting to create a username.It is a security step to prove that we have access to control the lights. So head over to your hue bridge and press the link button.

Now press that POST again and voila.

We have now created our username.

Now you have a username with permissions that you can use to interact with all your lights.

The next endpoint:

https://BRIDGEIPADRESS/api/USERNAME/lights/ returns all the current info on our lights, for this tutorial I am only interested in the light state property named on which is a boolean value. ( true or false).

Here is an example of the API response:

You can use POSTMAN to test call the API.

2.- PHP Script

Let’s have more fun now with some coding. We have to create a simple script that will GET the data that we need from our lights. For this example I will get the name of the light and from the state I want to know the on value (true,false).

<?php
$curl = curl_init();

$internalIp = 'YOUR-IP';
$user       = 'YOUR-USERNAME';
$url        = $internalIp.'/api/'.$user.'/lights';

curl_setopt_array($curl,
    [
    CURLOPT_URL            => $url,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_ENCODING       => "",
    CURLOPT_MAXREDIRS      => 10,
    CURLOPT_TIMEOUT        => 0,
    CURLOPT_FOLLOWLOCATION => true,
    CURLOPT_HTTP_VERSION   => CURL_HTTP_VERSION_1_1,
    CURLOPT_CUSTOMREQUEST  => "GET",
    ]
);

$response = curl_exec($curl);
$result   = json_decode($response, true);
curl_close($curl);

$lights = [];
foreach($result as $key=> $light) {

    $lights[$key]['state'] = $light['state']['on'];
    $lights[$key]['name']  = $light['name'];
}

var_dump($lights);

In this small script we will save in the $lights array key, value information of our light’s name and state->on.

Here you can see an example of some of my lights:

3.- PHP Script using Ring Central’s SMS API

I will use RingCentral’s API to notify if a light state->on property changes to true.

I won’t go into details on how to setup an account with Ring Central, you can follow step by step on this post, check step 5(Setup RingCentral SMS API) it is pretty easy and quick to get a developer account.

We already have the first part that calls HUE’S API:

<?php
require('vendor/autoload.php');

$curl = curl_init();

// Hue Lights credentials
$internalIp = 'YOUR-IP';
$user       = 'YOUR-USERNAME';
$url        = $internalIp.'/api/'.$user.'/lights';

// Call Hue Philips API
curl_setopt_array($curl,
    [
    CURLOPT_URL            => $url,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_ENCODING       => "",
    CURLOPT_MAXREDIRS      => 10,
    CURLOPT_TIMEOUT        => 0,
    CURLOPT_FOLLOWLOCATION => true,
    CURLOPT_HTTP_VERSION   => CURL_HTTP_VERSION_1_1,
    CURLOPT_CUSTOMREQUEST  => "GET",
    ]
);

$response = curl_exec($curl);
$result   = json_decode($response, true);
curl_close($curl);

foreach($result as $key=> $light) {
    if ($light['state']['on'] === true){
        smsRingCentralAlert($light['name']);
    }
}

Now we just add RingCentral’s API

// Call Ring Central SMS API
function smsRingCentralAlert($light)
{

    $message = $light. ' light has been turned on';

$RECIPIENT                = 'YOUR-TEST-PHONE-NUMBER';
$RINGCENTRAL_CLIENTID     = 'YOUR-CLIENT-ID';
$RINGCENTRAL_CLIENTSECRET = 'YOUR-SECRET';
$RINGCENTRAL_SERVER       = 'https://platform.devtest.ringcentral.com';
$RINGCENTRAL_USERNAME     = 'YOUR-USERNAME';
$RINGCENTRAL_PASSWORD     = 'YOUR-PASSWORD';
$RINGCENTRAL_EXTENSION    = 'YOUR-EXTENSION';

$rcsdk    = new RingCentral\SDK\SDK($RINGCENTRAL_CLIENTID, $RINGCENTRAL_CLIENTSECRET, $RINGCENTRAL_SERVER);
$platform = $rcsdk->platform();
$platform->login($RINGCENTRAL_USERNAME, $RINGCENTRAL_EXTENSION, $RINGCENTRAL_PASSWORD);

$platform->post('/account/~/extension/~/sms',
    [
        'from' => [ 'phoneNumber' => $RINGCENTRAL_USERNAME],
        'to'   => [['phoneNumber' => $RECIPIENT]],
        'text' => $message
    ]
);
}

Remember to use your credentials!

If everything goes well, you should receive a sms for each of your lights that is on.

4.- Bonus step – Cron Job

In order to keep checking if the lights are on, we would have to run our PHP script again, and again and again, this is an endless task todo manually, if we use a simple cron job that checks the light status for us that would be a lot easier.

  • To create a cron job we need a few ingredients:
  • Timing – Set minutes, hours, days, months
  • Execute – The cron job needs to the PHP exe to run.
  • Path to script – Full path of where your script is located.
  • Output – (optional) you can save the output of your script or log errors.

To create a cron job just open your CLI and type:

crontab -e

Make sure to check your current path to your PHP exe. This command will help:

whereis php

The php path is usually :
/usr/bin/php

After you run the crontab, most likely an editor will open, this is an example of the cron I used for this post:
*/1 * * * * /usr/bin/php /Users/juan/DEV/RingCentral/smsLights.php >/tmp/stdout.log 2>/tmp/stderr.log

The first part sets the script to run every minute: */1 * * * *
Next is the route to my php exe file /usr/bin/php
Now we need the full path to our script /Users/juan/DEV/RingCentral/smsLights.php
And finally I decided to add a log:
>/tmp/stdout.log 2>/tmp/stderr.log

This is just a simple script that tries to explain how to use all this tools together, after you test remember to comment your cron job, or change the timing, or else you will be spammed every minute haha.

RingCentral SMS app

I wanted to learn how to receive an SMS using Ring Central’s API and write about my experience, I thought of how a simple idea of communication between integrations can benefit any person in numerous ways.

I had many ideas on my mind and I will probably be using them in the future, for example: Receive an SMS when a security camera in my house is activated by motion or sound by my curious golden retriever Floki, or a SMS when a door sensor is activated, when a light turns on inside the house, or maybe even get a SMS when someone pushes code to a repository.

Floki don’t be sad, I will be back in a few hours.

For the SMS API example I wanted to test something simple and that could be very productive, that is why I chose to integrate SMS Ring Central’s API with Formstack.

Formstack is a workplace productivity solution built to transform the way people collect information and put it to work, so what If I could use a Formstack form to collect data and depending on the submit response I got from a user, I could trigger an SMS using Ring Central’s API?

Ingredients needed :

STEPS:

1 Create a simple form in Formstack.

For this example I only used a Name and a Rating field.

Need help creating a form…
https://help.formstack.com/hc/en-us/articles/360019520271-Creating-a-New-Form

2 Install and run temporarily ngrok

Download the package and unzip it, then run:
./ngrok http 8080 (or any other port you would like to use)

It should look something like this:

Need more help using Ngrok:
https://ngrok.com/docs

We are now ready to tunnel:

3 Back in Formstack:

Go to Settings -> Emails & Actions and let’s supercharge this form by adding a Webhook, copy the ngrok forwarding IP to the Webhook URL, select Post with sub-field names and Post with API-friendly keys.

Need more help on webhooks:
https://help.formstack.com/hc/en-us/articles/360019516191-WebHook-Submit-Actions

4 Run a temp PHP web server

For this test, I created a folder named RingCentral, and added a php file named index.php

Inside that folder I ran the following command to start my php web server:

php -S localhost:8080

Sample content of the file:

<?php
echo 'hello Blog API Test';

We can make a quick test, to make sure we communicate with our localhost when submitting a form, so go ahead and submit your test form.

You can check the request data sent in http://127.0.0.1:4040/inspect/http

As you can see, I got my 5 star response value from the Rating field did_you_like_this_blog_tutorial and the name field with value Test1, and we can also see that my local web server responded with hello Blog API Test.

5 Setup RingCentral SMS API

And now for the most interesting part, we can now use the data submitted by the Formstack form that was sent to the localhost through ngrok and send a SMS with RIngCentral’s API.

First we need a developer account for Ring Central’s API, you should be able to create an account here: https://developers.ringcentral.com/

Once you have created an account simply create an SMP APP with one click:

Don’t have the link?
Don’t worry here it is:
https://developer.ringcentral.com/new-app?name=SMS+Quick+Start+App&desc=A+simple+app+to+demo+sending+an+SMS+on+RingCentral&public=false&type=ServerOther&carriers=7710,7310,3420&permissions=SMS,ReadMessages&redirectUri=

Now that your sandbox app is created we need to download the PHP SDK to get started: (Make sure to download to the same directory where you started your php web server and where the file index.php is located.

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

Now simply edit the index.php file we created earlier and enter this code:

<?php
require('vendor/autoload.php');

$RECIPIENT = '<ENTER PHONE NUMBER>';

$RINGCENTRAL_CLIENTID = '<ENTER CLIENT ID>';
$RINGCENTRAL_CLIENTSECRET = '<ENTER CLIENT SECRET>';
$RINGCENTRAL_SERVER = 'https://platform.devtest.ringcentral.com';

$RINGCENTRAL_USERNAME = '<YOUR ACCOUNT PHONE NUMBER>';
$RINGCENTRAL_PASSWORD = '<YOUR ACCOUNT PASSWORD>';
$RINGCENTRAL_EXTENSION = '<YOUR EXTENSION, PROBABLY "101">';

$rcsdk = new RingCentral\SDK\SDK($RINGCENTRAL_CLIENTID, $RINGCENTRAL_CLIENTSECRET, $RINGCENTRAL_SERVER);

$platform = $rcsdk->platform();
$platform->login($RINGCENTRAL_USERNAME, $RINGCENTRAL_EXTENSION, $RINGCENTRAL_PASSWORD);

$resp = $platform->post('/account/~/extension/~/sms',
    array(
       'from' => array ('phoneNumber' => $RINGCENTRAL_USERNAME),
       'to' => array(array('phoneNumber' => $RECIPIENT)),
       'text' => 'Hello World from PHP'
     ));
print_r ("SMS sent. Message status: " . $resp->json()->messageStatus);
?>

Submit another form, check the request at: http://127.0.0.1:4040/inspect/http

And you should see a response like this one:

And immediately receive an sms that says:

Now to integrate everything together, just add this to the code before your credentials:

$find      = ['first =','last ='];
$name      = str_replace($find,'',$_REQUEST['name']);
$stars     = $_REQUEST['did_you_like_this_blog_tutorial'];
$message   = 'You received '. $stars . ' stars from'. $name;

And replace the $resp array text value to: $message

$resp = $platform->post('/account/~/extension/~/sms',
    array(
        'from' => array ('phoneNumber' => $RINGCENTRAL_USERNAME),
        'to'   => array(array('phoneNumber' => $RECIPIENT)),
        'text' => $message
    ));
Looks like someone rated me with 5 stars!

And that is it for now. I hope you enjoyed learning how to integrate Formstack, ngrok and RingCentral’s SMS API, because I sured did.