Introduction

With this tutorial we will show you how to build a small application in PHP that allows you to receive SMS messages sent with Nexmo's SMS API.

Receiving an SMS is free with Nexmo, but you will need to buy a phone number that people can send messages to. When Nexmo receives an SMS for a phone number that you own, they make a HTTP request to an URL that you’ve configured containing all of the information about the SMS.


Audience

This tutorial is useful for web developers, PHP programmers or other developers who are interested in integrating the Nexmo SMS API into their applications.


Prerequisites

For this tutorial to work, you need to be a production user of the Nexmo SMS API and the Nexmo Phone Numbers API. You also need:

  • Some basic PHP knowledge.
  • A PHP and a PHP dependency manager (Composer) installed.
  • An SMS enabled Nexmo virtual number rented. You can do so by using Nexmo's Phone Numbers API in our KPN API Store.
  • A webhook (you will define in the PHP code).
  • Ngrok, to expose your local server to the internet so Nexmo can reach it.


1. Getting set up

First, make sure you have all the things you need for this tutorial. If you already have any of the below sorted, you can skip the step.


Install PHP

You need PHP and a dependency manager for PHP (Composer) to download your dependencies. The code in this tutorial should work on PHP 5.6 and above.


Install the Slim framework

To receive the incoming SMS content, you are going to be using the Slim framework. We will show you how to install it with Composer:

In a terminal window type the following and press Enter:

composer require slim/slim "^3.0"


Get Nexmo's Phone Numbers and SMS APIs

You will need to create a working production app on the KPN API Store with the Nexmo Phone Numbers API and the Nexmo SMS API included. For this to work, you will also need a Nexmo telephone number. Follow these steps:

  1. Create an account on the KPN API Store.
  2. Create an app in your 'My apps' dashboard with the Nexmo's Phone Numbers API and Nexmo's SMS API included.
  3. Click Production request to start using the app in production.
  4. When your app is in production, buy a Nexmo phone number using the Nexmo Phone Numbers API: POST /number/buy.

To check which countries are supported, please view the Nexmo help page.


2. Write the PHP code

Now, when Nexmo receives an SMS for a phone number that you own, they make a HTTP request to a URL that you've configured containing all of the information about the SMS. In this step, you are going to log all of the information that Nexmo provides to the console. In the real world, you could store this in a file or a database.

Nexmo can make either a GET or a POST request to your application with the data. In this tutorial, we'll show you how to write an application that can handle both HTTP GET and POST methods.

Let's go through the code step by step:

The first lines of code you'll need:

  1. <?php
  2. use \Psr\Http\Message\ServerRequestInterface as Request;
  3. use \Psr\Http\Message\ResponseInterface as Response;
  4.  
  5. require 'vendor/autoload.php';


Bootstrap your Slim app

Now, you have to bootstrap your slim app. This is done with a simple one-liner.

  1. $app = new \Slim\App;


Define a handler and log the parameters

Here, you need to define a handler that returns a HTTP 204 response and then instruct Slim to use this handler whenever you receive a GET or a POST request to /my_webhook.

To log the parameters you received, you need to check if there is any data returned by $request->getParsedBody().

  • If so, it's a POST request and you can carry on.
  • If not, call $request->getQueryParams() to read the GET parameters.

At this point, all parameters are stored in a variable named $params and you can output them to the terminal using _error_log(print_r($params, true));

The handler code should now look like the following:

  1. $handler = function (Request $request, Response $response) {
  2. $params = $request->getParsedBody();
  3. // Fall back to query parameters if needed
  4. if (!count($params)){
  5. $params = $request->getQueryParams();
  6. }
  7. error_log(print_r($params, true));
  8. return $response->withStatus(204);
  9. };


Add the webhook

In this step you add the webhook for the GET and POST requests. You finish with $app->run();

  1. $app->get('/my_webhook', $handler);
  2. $app->post('/my_webhook', $handler);
  3.  
  4. $app->run();


Save the file

The finished source code looks like this. Save it as index.php.

  1. <?php
  2. use \Psr\Http\Message\ServerRequestInterface as Request;
  3. use \Psr\Http\Message\ResponseInterface as Response;
  4.  
  5. require 'vendor/autoload.php';
  6.  
  7. $app = new \Slim\App;
  8.  
  9. $handler = function (Request $request, Response $response) {
  10. $params = $request->getParsedBody();
  11.  
  12. // Fall back to query parameters if needed
  13. if (!count($params)){
  14. $params = $request->getQueryParams();
  15. }
  16.  
  17. error_log(print_r($params, true));
  18.  
  19. return $response->withStatus(204);
  20. };
  21.  
  22. $app->get('/my_webhook', $handler);
  23. $app->post('/my_webhook', $handler);
  24.  
  25. $app->run();
  26.  


3. Start the server

Open a new terminal window and type the following and press Enter. This will start the build process and the server on port 8000:

php -t . -S localhost:8000

Check that the server has started with:

PHP 7.4.2 Development Server (http://localhost:8000) started


4. Open the PHP application

Open your PHP application in the browser, for example: http://localhost:8000/index.php.

In the terminal, check that the application is being called:

[Wed Feb 12 16:06:51 2020] [::1]:59344 Accepted
[Wed Feb 12 16:06:51 2020] [::1]:59345 Accepted
[Wed Feb 12 16:06:52 2020] [::1]:59344 [404]: GET /index.php
[Wed Feb 12 16:06:52 2020] [::1]:59344 Closing


5. Expose your PHP application

Note: Don't ever do this in a corporate network or corporate VPN! Ever!

To send a HTTP request to your application, Nexmo needs to know which URL your application is running on.

Use ngrok to expose your local application to the internet:

  1. Download ngrok. and execute ngrok.exe.
  2. In the ngrok window, type ngrok http 8000 and press Enter.
    In the ngrok window, you will see something similar to the following:
Forwarding            http://460d5b19.ngrok.io -> http://localhost:8000
Forwarding            https://460d5b19.ngrok.io -> http://localhost:8000 
  1. Make a note of the generated ngrok URL. This is the exposed webhook URL that Nexmo will call when an SMS is received. The inbound SMS messages will be delivered to this registered webhook and then send to your PHP application. The URL will look like this: http://460d5b19.ngrok.io.


6. Register webhook endpoint with your Nexmo number

Now you have to register your webhook with the Nexmo virtual number, meaning you have to tell Nexmo where it should send the SMS message.

With a test application, you can try inbound messaging by registering your webhook against your own phone number that you use for testing, without buying a virtual number.

Note: This is not applicable if you apply for production usage.

  1. Take your webhook URL from the previous step. In this case: /my_webhook.
  2. Go to the Nexmo Phone Numbers API endpoint: POST ​/number​/update.
  3. Enter the country code, the phone number and the webhook URL that you want to connect to the phone number and click Execute.
Parameter Description Example
country The two character country code in ISO 3166-1 alpha-2 format. NL
msisdn The inbound number to which you want to connect the webhook. For example: 3197012345678
moHttpUrl Append the webhook from the code to the ngrok URL. http://460d5b19.ngrok.io/my_webhook

For more, click here: Update a phone number.


7. Receive SMS in PHP application

At this point, you can send an SMS to your virtual Nexmo number and watch as it appears in your terminal. You can use a mobile phone or the Nexmo SMS API to send the SMS.

If you want to use Nexmo SMS API, follow these steps:

  1. Go to POST ​/send in SwaggerHub.
  2. Use the client_id and client_secret from your app in the KPN API Store.
  3. In the SwaggerHub user interface, enter:
    • The telephone number you want to send the SMS from.
    • The telephone number you want to send the SMS to, in this case your Nexmo virtual number.
    • The message of the API.
  4. Click Execute.

The SMS should arrive soon!

The message will look similar to this:

    [msisdn] => 319711111111
    [to] => 3197012345678
    [messageId] => 160000029F1BC6BC
    [text] => This is my first SMS received in a PHP application. Congratulations.
    [type] => text
    [keyword] => MY
    [api-key] => 12345678
    [message-timestamp] => 2020-02-12 14:30:30
Parameter Description
[msisdn] Number that sent the SMS. In this case your Nexmo SMS number or your mobile phone number.
[to] Number that received the SMS. In this case your Nexmo virtual number.
[text] Content of the message.


Well done!

Congratulations, you've successfully received your first inbound SMS by the Nexmo SMS API using a PHP application!


Get help

Don't hesitate to contact us if you have any questions about this post.


What’s next?

Check out some of these tutorials

  • Send SMS with KPN SMS and Node-RED (soon)
  • Use the WeSeeDo API with Node-RED (soon)
  • Use the Registered E-mail API with Node-RED (soon)