How to Receive and Respond to Incoming SMS Messages in PHP with Laravel and Plivo

How to Receive and Respond to Incoming SMS Messages in PHP with Laravel and Plivo

Sending an outbound message using the Plivo SMS platform is easy, but communication should be a two-way street. Customers should be able to text you, and you should acknowledge their messages and address their concerns. To do this, you can build a PHP Laravel application to receive and respond to incoming SMS messages on a Plivo phone number. In this post, we walk you through how to implement this.

Prerequisites

Before you get started, you’ll need:

  • A Plivo account — sign up for one for free if you don’t have one already.
  • An SMS-enabled Plivo phone number as you want to receive incoming SMS messages. To search for and buy an available number, go to Phone Numbers > Buy Numbers on the Plivo console.
  • Laravel and Plivo PHP packages.
  • ngrok — a utility that exposes your local development server to the internet over secure tunnels.

Create a Laravel application to receive SMS messages

First, you need to install Laravel if you haven’t installed it already. We suggest using Composer to install it. Add a new Laravel project with boilerplate code with the command composer create-project laravel/laravel receive_sms --prefer-dist. This will create a receive_sms directory with the necessary folders and files for development. Then change to the newly created “receive_sms” project directory and install the Plivo PHP package (composer require plivo/plivo-php).

Once you’ve installed Laravel and the Plivo PHP SDK, run php artisan make:controller SMSController to create a Laravel controller to handle incoming SMS messages on a Plivo number. Use this code:

<?php

namespace App\Http\Controllers;
require '../vendor/autoload.php';
use Illuminate\Http\Request;

class SMSController extends Controller
{
    public function receivesms()
    {
         $from_number = $_REQUEST["From"];
         $to_number = $_REQUEST["To"];
         $text = $_REQUEST["Text"];
         echo("Message received - From $from_number, To: $to_number, Text: $text");
    }
}

Now, you need to add a route for the “receivesms” function in the SMSController class. Open the routes/web.php file and add this line at the end of the file:

Route::match(['get', 'post'], '/receivesms', 'App\Http\Controllers\SMSController@receivesms');

Return a Message XML document to reply to incoming messages

To reply to an incoming SMS message, you need to return an XML document from the URL configured as the message_url in the application assigned to the Plivo number. The PHP SDK can manage the XML document generation, and you can use the Message XML element to reply to incoming SMS messages. Use this code:

<?php

namespace App\Http\Controllers;
require '../vendor/autoload.php';
use Plivo\RestClient;
use Plivo\XML\Response;
use Illuminate\Http\Request;

class SMSController extends Controller
{
    public function receivesms()
    {
         $from_number = $_REQUEST["From"];
         $to_number = $_REQUEST["To"];
         $text = $_REQUEST["Text"];
         echo("Message received - From $from_number, To: $to_number, Text: $text");
    }

    public function replysms()
    {
        $number = $_REQUEST["From"];
        $to = $_REQUEST["To"];
        $text = $_REQUEST["Text"];
        $response = new Response();
        $params = array(
            'src' => $to,
            'dst' => $number,
            'callbackUrl' => "https://www.foo.com/sms_status/",
            'callbackMethod' => "POST"
        );
        $message_body = "Thank you, we have received your request.";
        $response->addMessage($message_body, $params);

        Header('Content-type: text/xml');
        return $response->toXML();
    }
}

As we did earlier, we need to add a route for the “replysms” function in the SMSController class. Open the routes/web.php file and add this line at the end of the file:

Route::match(['get', 'post'], '/replysms', 'App\Http\Controllers\SMSController@replysms');

Note: We need to add the route of the app to the “except” array to disable CSRF verification - app/Http/Middleware/VerifyCsrfToken.php

<?php

namespace App\Http\Middleware;

use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as Middleware;

class VerifyCsrfToken extends Middleware
{
    /**
     * The URIs that should be excluded from CSRF verification.
     *
     * @var array
     */
    protected $except = [
        '/receivesms',
        '/replysms'
    ];
}

Test the code locally

Now the SMSController is ready to handle incoming SMS messages to your Plivo number using Laravel and Plivo PHP SDK. To run the code on the Laravel server, use the command

You should see your basic server application in action on http://127.0.0.1:8000/replysms.

Expose the local server to the internet using ngrok

Once you see the application working locally, the next step is to connect the application to the internet to receive and reply to messages. For that, we recommend using ngrok, which exposes local servers behind NATs and firewalls to the public internet over secure tunnels. Install it and run ngrok on the command line, specifying the port that hosts the application on which you want to receive messages (8000 in this case, as our local Laravel application is running there):

Ngrok will display a forwarding link that you can use as a webhook to access your local server over the public network.

Ngrok CLI

Test the link by opening the ngrok URL(https://b82335d346bb.ngrok.io/replysms) in a browser. We used HTTPie to check the XML response from the ngrok URL.

XML document with Message XML element

Connect the Laravel application to a Plivo number

The final step is to configure the app as a Plivo messaging application and assign it to a Plivo number on which you want to receive SMS messages.

Go to the Plivo console and navigate to Messaging > Applications > XML, then click on the Add New Application button in the upper right.

Provide a friendly name for the app — we used “App-Incoming-SMS” — and configure the ngrok URL https://b82335d346bb.ngrok.io/replysms as the Message URL. Select the HTTP verb as POST, then click Create Application.

Create Plivo App to handle incoming SMS messages

Now go to Phone Numbers > Your Numbers and click on the number to which you want to assign the application. From the Plivo Application drop-down, choose the message application you just created. Finally, click Update Number.

Assign the Plivo App to a Plivo Number

Test the application

Send an SMS to the Plivo number you selected. You should see that the Laravel application automatically sends a reply back to your mobile number.

And that’s how simple it is to receive and respond to incoming SMS messages using Plivo’s PHP SDK and a Laravel application.

Haven’t tried Plivo yet? Getting started is easy and only takes five minutes! Sign up today.

Get Volume Pricing

Thousands of businesses in more than 220 countries trust Plivo’s cloud communications platform

The best communications platform forthe world’s leading entertainment service

Frequently asked questions

No items found.
footer bg

Subscribe to Our Newsletter

Get monthly product and feature updates, the latest industry news, and more!

Thank you icon
Thank you!
Thank you for subscribing
Oops! Something went wrong while submitting the form.

POSTS YOU MIGHT LIKE