How to receive an SMS in a PHP application
Happy with this tutorial and want to test the Vonage SMS API more? Head over to the documentation and the API reference for all the information you need to use the API.
Go to Vonage SMS documentation
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 Vonage's SMS API.
Receiving an SMS is free with Vonage (formerly called Nexmo), but you will need to buy a phone number that people can send messages to. When Vonage receives an SMS for a phone number that you own, they make an HTTP request to an URL that you’ve configured containing all of the information about the SMS.
Have a look
Audience
This tutorial is useful for web developers, PHP programmers or other developers who are interested in integrating the NVonage SMS API into their applications.
Prerequisites
For this tutorial to work, you need to be a production user of the Vonage SMS API and the Vonage Phone Numbers API. You also need:
- Some basic PHP knowledge.
- A PHP and a PHP dependency manager (Composer) installed.
- An SMS enabled Vonage virtual number rented. You can do so by using Vonage's Phone Numbers API in our KPN Developer Portal.
- A webhook (you will define in the PHP code).
- Ngrok, to expose your local server to the internet so Vonage 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 Vonage's Phone Numbers and SMS APIs
You will need to create a working production app on the KPN Developer Portal with the Vonage Phone Numbers API and the Vonage SMS API included. For this to work, you will also need a Vonage telephone number. Follow these steps:
- Create an account on the KPN Developer Portal.
- Create an app in your 'My apps' dashboard with Vonage's Phone Numbers API and Vonage's SMS API included.
- Click
Production request
to start using the app in production. - When your app is in production, buy a Vonage phone number using the Vonage Phone Numbers API:
POST /number/buy
.
To check which countries are supported, please view the Vonage help page.
2. Write the PHP code
Now, when Vonage receives an SMS for a phone number that you own, they make an 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 Vonage provides to the console. In the real world, you could store this in a file or a database.
Vonage 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:
<?php
use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;
require 'vendor/autoload.php';
Bootstrap your Slim app
Now, you have to bootstrap your slim app. This is done with a simple one-liner.
$app = new \Slim\App;
Define a handler and log the parameters
Here, you need to define a handler that returns an 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 theGET
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:
$handler = function (Request $request, Response $response) {
$params = $request->getParsedBody();
// Fall back to query parameters if needed
if (!count($params)){
$params = $request->getQueryParams();
}
error_log(print_r($params, true));
return $response->withStatus(204);
};
Add the webhook
In this step you add the webhook for the GET
and POST
requests. You finish with $app->run();
$app->get('/my_webhook', $handler);
$app->post('/my_webhook', $handler);
$app->run();
Save the file
The finished source code looks like this. Save it as index.php
.
You can also download the tutorial flow JSON code: Download from GitHub`.
<?php
use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;
require 'vendor/autoload.php';
$app = new \Slim\App;
$handler = function (Request $request, Response $response) {
$params = $request->getParsedBody();
// Fall back to query parameters if needed
if (!count($params)){
$params = $request->getQueryParams();
}
error_log(print_r($params, true));
return $response->withStatus(204);
};
$app->get('/my_webhook', $handler);
$app->post('/my_webhook', $handler);
$app->run();
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 an HTTP request to your application, Vonage needs to know which URL your application is running on.
Use ngrok to expose your local application to the internet:
- Download ngrok. and execute
ngrok.exe
. - 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
- Make a note of the generated
ngrok URL
. This is the exposed webhook URL that Vonage 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 Vonage number
Now you have to register your webhook with the Vonage virtual number, meaning you have to tell Vonage 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.
- Take your webhook URL from the previous step. In this case:
/my_webhook
. - Go to the Vonage Phone Numbers API endpoint:
POST /number/update
. - Enter the
country
code, the phone number and the webhook URL that you want to connect to the phone number and clickExecute
.
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 Vonage number and watch as it appears in your terminal. You can use a mobile phone or the Vonage SMS API to send the SMS.
If you want to use Vonage's SMS API, follow these steps:
- Go to POST /send in SwaggerHub.
- Use the
client_id
andclient_secret
from your app in the KPN Developer Portal. - 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 Vonage virtual number.
- The message of the API.
- 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 Vonage SMS number or your mobile phone number. |
[to] |
Number that received the SMS. In this case your Vonage virtual number. |
[text] |
Content of the message. |
Well done!
Congratulations, you've successfully received your first inbound SMS by the Vonage 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