How to Verify Phone Numbers with PHP, Symfony and Twilio

In this post we’ll learn how to verify phone numbers with Twilio in a Symfony project. We will discover how to model and validate a user’s phone number, and then use Twilio’s PHP SDK to create a call flow where the user has to enter a 6 digit code to verify themselves. The frontend view will provide a form to capture their number, displaying further instructions or validation errors, and then seamlessly redirect the user to another page once they’ve been verified.

If you need a refresher on Symfony, check out creating a Symfony 3 project with basic user handling. Those of you who don’t use Symfony should be able to carry the core ideas across to your framework of choice. Knp University’s screencast on Joyful Development with Symfony 3 is also helpful for starting a new project.

Check out this example project on GitHub with the code to the verification process that grants user access to premium blog posts.

Getting started

There are 4 steps you need to take before we begin verifying phone numbers:

Installing dependencies

You’ll need to install a couple of extra dependencies in your Symfony project: the Twilio PHP SDK so you can interact with the REST API and the FOSJsRoutingBundle to expose application URLs in JavaScript. Run the following command in your terminal:

Make sure to follow both the installation and usage instructions for FOSJsRoutingBundle.

Creating a tunnel

We’re going to use ngrok to create a secure tunnel between the Internet and your local development environment. By doing so, Twilio can make requests and respond to your application, which is crucial for testing our implementation. Start your Symfony application with the built in PHP web-server by running the following command:

In a separate terminal, run the following command to securely expose the server to the outside world:

You should then see output similar to the following:

From this point onwards, you should access your application through the http://ngrok.io forwarding address so Symfony generates absolute URLs that are publicly accessible.

Creating a Twilio account

You will need a Twilio account and a phone number. If you don’t already have those, here are the instructions.
Once you’re logged in, visit the console dashboard and grab your account SID and auth token. The support article “How does Twilio’s Free Trial work?” will guide you on how to get your first Twilio phone number (make sure it has voice capabilities!)
It’s also important to mention that trial accounts have to first verify any non-Twilio number that will be receiving calls, e.g. your mobile number. When you’re ready to use Twilio in production, upgrade your account to communicate with non-verified phone numbers.

Configuring the SDK

Back in the Symfony project, add your account SID, auth token, and newly acquired Twilio phone number to app/config/parameters.yml:

Next, we create a new service definition in app/config/services.yml to expose an API client that’s configured with your credentials. We’ll be using this later to make a voice call:

Number verification with Twilio

Having a user verify their phone number will be a multi-step process. In the next few sections we shall:

  • Create a Doctrine value object to model a phone number.
  • Create a Symfony validator to correctly format and validate the phone number.
  • Create a Symfony controller & form to capture the user’s phone number.
  • Make an automated call with the Twilio API to instruct them (using text-to-speech) to input the verification code that’s displayed on-screen by using their keypad, correlating the incoming phone number with the entered digits and flagging them as verified.

Modeling a phone number

Let’s begin by creating a value object that models a user’s phone number. We use Doctrine ORM annotations to map the object (“entity”) to the underlying database so its values will be persisted.
Create a file called PhoneNumber.php in src/AppBundle/Entity and add the following code:

A common trait that Symfony projects share is loading users from a database, assuming your project already has a User entity present (if not, check out this blog post on basic user handling), we can embed this value object into it using the embeddable annotation.

Add the code contained within the example class below (variable & annotation, constructor, getter/setter) to your own User class:

Validating a phone number

Before making a call, we should check that the user’s phone number is actually valid. In fact, Twilio’s REST API prefers numbers to be in the E.164 format, and we can’t rely on the user inputting their number the way we need it. Luckily, Twilio offers a lookup service that will handle both number validation and formatting for us.
Let’s implement a custom validation constraint that gets applied to the value object and formats the phone number. Create a file called E164Number.php in src/AppBundle/Validator/Constraints and add the following code:

Next, create a file called E164NumberValidator.php in the same directory and add the following code:

We then need to register this class in the service container and tag it so that Symfony knows it’s a validator, as well as inject the Twilio SDK client we registered previously. Add the following to app/config/services.yml:

The validator’s implementation is fairly straightforward. We use the Twilio SDK client to submit the phone number to the Lookup API. If we get 404 response in return then the number isn’t valid, so we add a constraint violation.
Finally, we’ll need to update the PhoneNumber class docblock to assert our new constraint:

Using the @AssertGroupSequence annotation means that the prior NotBlank constraints on the number and country fields are validated beforehand, ensuring that they’ll have values when accessed by the E164Number class constraint.

Capturing the user’s phone number

Now we’ll implement a controller method that captures, validates, and saves a user’s phone number. To begin with, generate a new controller by running the following command:

Next, replace the generated method with the following code:

Also update the generated verify.html.twig template so that it renders the Symfony form created in the above controller action, so the user can enter their phone number:

We’re almost ready to call the user. To demonstrate what we’ve achieved so far in the context of my example project, submitting a phone number will format it and save it to the user database. However, if I submit an invalid number then this is what I’d see:

Calling the user

Once the user has submitted the form, we need to kick off a phone call to them as well as display their verification code. First off we’ll address that 2nd TODO comment in the verifyAction method by making a call with Twilio’s REST API:

The first two parameters are fairly self-explanatory as this is an outgoing call to the user from our Twilio number. However, once the call connects, how do we control what happens next? Enter TwiML, a markup language that defines a set of instructions to dictate call flow. If we implement a controller action that renders an initial TwiML document, passing its absolute URL as the third parameter, Twilio will know how to continue the call once the user picks up.
Important: Remember to use the ngrok URL we generated earlier when testing the Twilio integration. Otherwise Symfony will generate an absolute URL with a local hostname, which will be inaccessible.
Time to begin implementing our verification call flow. First, generate a new controller by running the following command:

Next, replace the generated class with the following code so the controller defaults to responding with XML and the action has the correct route name:

Since we’ll be building in some retry logic in case the user accidentally hits the wrong digit, let’s start off the above method’s TODO by handling what happens when they reach the maximum number of retries:

Requesting http://xxxxxxxx.ngrok.io/twilio/voice/verify?retries=3 (make sure to use your own ngrok URL) will return the following TwiML document:

A voice will say goodbye and then Twilio will end the call because there are no more TwiML verbs to process. Simple enough right? Next, we’ll continue adding to our voiceVerifyAction method and instruct the user to enter their verification code:

Requesting the same URL without the query-string will return the following TwiML document:

This TwiML document is a bit more nuanced, so let’s break it down. The initial Gather verb will capture the first 6 digits the user enters and POST them to the current document URL (hence the Digits parameter check in the Symfony request object). We’ve nested a Say verb so that instructions will play while waiting for input. If no input is gathered after 5 seconds then Twilio will fall through to the next verb – Redirect – which will trigger a request to our controller action, but this time with an incremented retry count, continuing the call flow to once again ask for input.
Finally, we’ll try and find a user matching the recipient phone number and the verification code that was entered. If we get a match then the phone number should be flagged as verified. Otherwise we’ll inform them that their input wasn’t valid and let them try again. Continue adding to the voiceVerifyAction method:

With our call flow completed we can now focus on displaying the user’s verification code and automatically redirecting them to another view such as their profile page (I’ll leave the route choice up to you). Add the following code to the verifyAction method body in the PhoneController class, using the commented code as guidelines:

Next, let’s update the verify.html.twig template to display instructions to the user. We’ll also implement a small slice of JavaScript which polls our controller action every 5 seconds to check if the page should be redirected:

To demonstrate what we’ve achieved by using my example project, here’s what the user will see while they verify their phone number before being redirected:

Validating incoming Twilio requests

An important point to consider is the authenticity of data being sent to our TwiML endpoint. Twilio cryptographically signs their requests, so it’s best that we protect ourselves from any spoofed requests by a malicious third party.
Luckily, it’s very easy in Symfony to inspect the request for an entire group of controller actions before they’re invoked by implementing an event listener. Let’s begin by making an instance of Twilio’s request validator available in the service container by adding the following to app/config/services.yml:

In the event listener itself, we’ll first check for the existence of the header Twilio uses to send across the cryptographic signature. Then we call their library’s validate function, which takes the signature, request URL, and POST payload as parameters, to determine if the request is from Twilio:

For the 2nd parameter, we must reconstruct the URL rather than rely on the Request::getUri method. This is because getUri returns a normalised value, meaning any query string parameters in the URL have been rearranged alphabetically. Because the normalised URL no longer matches the one Twilio used to compute the expected signature, our computed signature would fail validation and so the payload would be rejected.
The last thing to do is register the class in the service container and tag it so that Symfony knows it’s an event listener, as well as inject the request validator we registered above. Add the following to app/config/services.yml:

That’s all, folks!

That’s the end of our Twilio integration. We’ve cleanly modeled and captured a user’s phone number, implemented a verification call flow that will flag the number as verified if the verification code is entered correctly, and seamlessly redirect the verified user to a different page. As part of Twilio’s security best practices, we also implemented an event listener to verify that requests handled by our controller are originating from Twilio.
To see this integration in a real-world context, check out this example project on GitHub where I use the same verification process to grant users access to premium blog posts.

Thank you for following my tutorial. I’m a software engineer at Codevate, a custom web and mobile app development company based in Birmingham, UK. You can find my other blog posts on the Codevate software development blog or follow me on GitHub. Thanks for reading!