Block Spam Calls and Robocalls with PHP and Laravel

Block spam calls with PHP and Laravel

Spam, scams, and robocalls are at best annoying. For high-volume customer service centers, they can significantly impact the bottom line. Let’s leverage the Twilio Marketplace and our PHP skills to block spam callers, robocallers, and scammers.

Before getting started, you should already know how to handle incoming calls with Twilio.

Get a Spam Filtering Add-on

The Twilio Add-ons Marketplace is a great place to find Add-ons for your Twilio apps. You can integrate third-party technologies without leaving the comfort of the Twilio API. You can access the Add-ons from your Twilio Console. Today, we’re going to look at a few Voice Add-ons that can help us with this spam problem. They are, in no particular order, Whitepages Pro Phone Reputation, Marchex Clean Call, and Nomorobo Spam Score:

Voice Spam Add-ons

We’ll be writing code to work with all three of these Add-ons, but you can research which one you think will work best for your requirements. Also, keep an eye on the Marketplace, as new Add-ons are always showing up.

Installing the Add-on

Once you’ve decided on the Add-on you’d like to use, click the Install button and agree to the terms. In our use case today, we want to make use of these Add-ons while handling incoming voice calls, so make sure the “Incoming Voice Call” box for “Use In” is checked and click Save to save any changes:

Use in incoming voice call

Note the “Unique Name” setting. You need to use this in the code that you will write to read the Add-on’s results. In the code for this guide, we are sticking with the default names.

Check Phone Number Score in PHP and Laravel

When Twilio receives a phone call from your phone number, it will send details of the call to your webhook (more on how to configure that later). In your webhook code, you create a TwiML response to tell Twilio how to handle the call.

For spam-checking, our code needs to check the spam score of the number and deal with the call differently depending on whether the Add-on considers the caller to be a spammer or not. In our example code here, we’ll return a TwiML tag to send spammers packing and a TwiML tag to welcome legit callers.

The code is a simple Laravel application. The code that filters requests is conveniently implemented as Laravel Middleware.

Loading Code Samples...
Language
<?php

namespace App\Http\Middleware;

use Closure;
use Flow\JSONPath\JSONPath;

class ValidateVoiceRequest
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $requestJson = new JSONPath($request->json()->all());

        $validateJSONPath = function ($JSONPath) use ($requestJson) {
            return $requestJson->find($JSONPath)->valid();
        };

        $rejectIncomingCall = function () {
            $twiml = new \Twilio\Twiml();
            $twiml->reject();
            return response($twiml)->header('Content-Type', 'text/xml');
        };

        if (!$validateJSONPath('$.AddOns')) {
          return $next($request);
        }

        $JSONPaths = [
            'isWhitePagesSpam' => '$..whitepages_pro_phone_rep..[?(@.type=="ScamOrFraud")]',
            'isNomoroboSpam' => '$.*.*.nomorobo_spamscore..[?(@.score==1)]',
            'nomoroboFailed' => '$.*.*.[?(@.status=="failed")]',
            'isMarchexSpam' => '$.*.*.marchex_cleancall..[?(@.recommendation!="PASS")]'
        ];

        foreach ($JSONPaths as $JSONPath) {
            if ($validateJSONPath($JSONPath)) {
                return $rejectIncomingCall();
            }
        }

        return $next($request);
    }
}
A Middleware which expects valid incoming calls to not match any of the JSONPath queries.
Block Spam Calls with PHP/Laravel

A Middleware which expects valid incoming calls to not match any of the JSONPath queries.

Notice the code has checks for all three of the Add-ons we mentioned before. The code is written to be very flexible and handle missing data in the JSON response, so feel free to copy and paste even if you only plan to use one of the Add-ons. Next, we'll analyze this application in more details.

How to Check Whitepages Pro Phone Reputation

Here’s an example of what Whitepages Pro Phone Reputation will return in the “AddOns” form parameter:

Loading Code Samples...
Language
{
  "status": "successful",
  "message": null,
  "code": null,
  "results": {
    "whitepages_pro_phone_rep": {
        "code": null,
        "message": null,
        "request_sid": "XR63dbb880c4fcd054a810f603f304bd31",
        "result": {
            "error": null,
            "id": "Phone.4d796fef-a2df-4b08-cfe3-bc7128b6f6bb.Durable",
            "phone_number": "2069735100",
            "report_count": 1,
            "reputation_details": {
                "category": null,
                "score": 0,
                "type": "NotSpamType"
            },
            "reputation_level": 1,
            "volume_score": 1,
            "warnings": []
        },
        "status": "successful"
    }
  }
}
White Pages Pro Reputation Add-on JSON Response

The middleware parses the request body and either rejects or accepts the incoming call as follows:

Loading Code Samples...
Language
<?php

namespace App\Http\Middleware;

use Closure;
use Flow\JSONPath\JSONPath;

class ValidateVoiceRequest
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $requestJson = new JSONPath($request->json()->all());

        $validateJSONPath = function ($JSONPath) use ($requestJson) {
            return $requestJson->find($JSONPath)->valid();
        };

        $rejectIncomingCall = function () {
            $twiml = new \Twilio\Twiml();
            $twiml->reject();
            return response($twiml)->header('Content-Type', 'text/xml');
        };

        if (!$validateJSONPath('$.AddOns')) {
          return $next($request);
        }

        $JSONPaths = [
            'isWhitePagesSpam' => '$..whitepages_pro_phone_rep..[?(@.type=="ScamOrFraud")]',
            'isNomoroboSpam' => '$.*.*.nomorobo_spamscore..[?(@.score==1)]',
            'nomoroboFailed' => '$.*.*.[?(@.status=="failed")]',
            'isMarchexSpam' => '$.*.*.marchex_cleancall..[?(@.recommendation!="PASS")]'
        ];

        foreach ($JSONPaths as $JSONPath) {
            if ($validateJSONPath($JSONPath)) {
                return $rejectIncomingCall();
            }
        }

        return $next($request);
    }
}
Use a simple JSONPath expression to reject calls.
Decide to block the call based on White Pages Pro

Use a simple JSONPath expression to reject calls.

This particular JSONPath expression filters incoming requests by whitepages reputation level. All reputation levels are acceptable except 4. In this case, the call should be rejected.

How to Check Marchex Clean Call

Here’s an example of what Marchex Clean Call will return:

Loading Code Samples...
Language
{
  "status": "successful",
  "message": null,
  "code": null,
  "results": {
    "marchex_cleancall": {
      "request_sid": "XRxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
      "status": "successful",
      "message": null,
      "code": null,
      "result": {
        "result": {
          "recommendation": "PASS",
          "reason": "CleanCall"
        }
      }
    }
  }
}
Marchex Clean Call Add-on JSON result

In PHP/Laravel you can simply access the JSON data as follows:

Loading Code Samples...
Language
<?php

namespace App\Http\Middleware;

use Closure;
use Flow\JSONPath\JSONPath;

class ValidateVoiceRequest
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $requestJson = new JSONPath($request->json()->all());

        $validateJSONPath = function ($JSONPath) use ($requestJson) {
            return $requestJson->find($JSONPath)->valid();
        };

        $rejectIncomingCall = function () {
            $twiml = new \Twilio\Twiml();
            $twiml->reject();
            return response($twiml)->header('Content-Type', 'text/xml');
        };

        if (!$validateJSONPath('$.AddOns')) {
          return $next($request);
        }

        $JSONPaths = [
            'isWhitePagesSpam' => '$..whitepages_pro_phone_rep..[?(@.type=="ScamOrFraud")]',
            'isNomoroboSpam' => '$.*.*.nomorobo_spamscore..[?(@.score==1)]',
            'nomoroboFailed' => '$.*.*.[?(@.status=="failed")]',
            'isMarchexSpam' => '$.*.*.marchex_cleancall..[?(@.recommendation!="PASS")]'
        ];

        foreach ($JSONPaths as $JSONPath) {
            if ($validateJSONPath($JSONPath)) {
                return $rejectIncomingCall();
            }
        }

        return $next($request);
    }
}
Make sure the Add-on processed the call successfully and followed Marchex' recommendation to decide to block the call or not
Decide to block the call based on Marchex Clean Call

Make sure the Add-on processed the call successfully and followed Marchex' recommendation to decide to block the call or not

This block of code uses only information found in the key results.marchex_cleancall. Here we advise blocking the call if Marchex' recommendation is not set to PASS.

How to Check Nomorobo Spam Score

Here’s an example of what Nomorobo Spam Score will return:

Loading Code Samples...
Language
{
  "status": "successful",
  "message": null,
  "code": null,
  "results": {
    "nomorobo_spamscore": {
      "request_sid": "XRxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
      "status": "successful",
      "message": null,
      "code": null,
      "result": {
        "status": "success",
        "message": "success",
        "score": 0
      }
    }
  }
}
Nomorobo Add-on JSON result

Again, we can see how we use JSONPath to validate the incoming call

Loading Code Samples...
Language
<?php

namespace App\Http\Middleware;

use Closure;
use Flow\JSONPath\JSONPath;

class ValidateVoiceRequest
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $requestJson = new JSONPath($request->json()->all());

        $validateJSONPath = function ($JSONPath) use ($requestJson) {
            return $requestJson->find($JSONPath)->valid();
        };

        $rejectIncomingCall = function () {
            $twiml = new \Twilio\Twiml();
            $twiml->reject();
            return response($twiml)->header('Content-Type', 'text/xml');
        };

        if (!$validateJSONPath('$.AddOns')) {
          return $next($request);
        }

        $JSONPaths = [
            'isWhitePagesSpam' => '$..whitepages_pro_phone_rep..[?(@.type=="ScamOrFraud")]',
            'isNomoroboSpam' => '$.*.*.nomorobo_spamscore..[?(@.score==1)]',
            'nomoroboFailed' => '$.*.*.[?(@.status=="failed")]',
            'isMarchexSpam' => '$.*.*.marchex_cleancall..[?(@.recommendation!="PASS")]'
        ];

        foreach ($JSONPaths as $JSONPath) {
            if ($validateJSONPath($JSONPath)) {
                return $rejectIncomingCall();
            }
        }

        return $next($request);
    }
}
Make sure the Add-on processed the call successfully and checked Nomorobo Spam Score to decide to block the call or not
Decide to block the call based on Nomorobo Spam Score

Make sure the Add-on processed the call successfully and checked Nomorobo Spam Score to decide to block the call or not

This block of code uses only information found in the key results.nomorobo_spamscore. Here we advise blocking the call if Nomorobo Spam Score is 1.

Now we've seen how to get advice from each Add-on but we have different options for handling the call. Let's look at how we're making the final decision.

Making a decision

In our example, unanimity is required for accepting a call. So we look at the advice from each add-on, and if even one of them tells us to block it, we'll reject the call.

Loading Code Samples...
Language
<?php
use Illuminate\Http\Request;

Route::middleware('auth:api')->get('/user', function (Request $request) {
    return $request->user();
});

Route::middleware('validate.voice')->post('/voice', function (Request $request) {
    //Call has successfully passed spam screening.
    $twiml = new Twilio\Twiml();
    $twiml->say('Welcome to the jungle.',
        array('voice' => 'woman', 'language' => 'en-gb'));
    $twiml->hangup();
    return response($twiml)->header('Content-Type', 'text/xml');
});
Accepts all calls that have cleared spam filters in the call validation middleware.
A Route That Handles Incoming Voice Calls

Accepts all calls that have cleared spam filters in the call validation middleware.

We could have also implemented it differently by using a majority rule. In any case, once we make a decision all that is left to do is act on the call.

Call Handling Options

Rejection Options

Using <Reject> is the simplest way to turn away spammers. However, you may want to handle them differently. The whole universe of TwiML is open to you. For example, you might want to record the call, have the recording transcribed using another Add-on, and log the transcription somewhere for someone to review.

Loading Code Samples...
Language
<?php

namespace App\Http\Middleware;

use Closure;
use Flow\JSONPath\JSONPath;

class ValidateVoiceRequest
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $requestJson = new JSONPath($request->json()->all());

        $validateJSONPath = function ($JSONPath) use ($requestJson) {
            return $requestJson->find($JSONPath)->valid();
        };

        $rejectIncomingCall = function () {
            $twiml = new \Twilio\Twiml();
            $twiml->reject();
            return response($twiml)->header('Content-Type', 'text/xml');
        };

        if (!$validateJSONPath('$.AddOns')) {
          return $next($request);
        }

        $JSONPaths = [
            'isWhitePagesSpam' => '$..whitepages_pro_phone_rep..[?(@.type=="ScamOrFraud")]',
            'isNomoroboSpam' => '$.*.*.nomorobo_spamscore..[?(@.score==1)]',
            'nomoroboFailed' => '$.*.*.[?(@.status=="failed")]',
            'isMarchexSpam' => '$.*.*.marchex_cleancall..[?(@.recommendation!="PASS")]'
        ];

        foreach ($JSONPaths as $JSONPath) {
            if ($validateJSONPath($JSONPath)) {
                return $rejectIncomingCall();
            }
        }

        return $next($request);
    }
}
Block the spammer with <Reject>

Call Accept Options

For this example, we’re just greeting the caller. In a real-world scenario, you would likely want to connect the call using <Dial> (to call another number or Twilio Client), <Enqueue> the call to be handled by TaskRouter, or build an IVR using <Gather>.

Loading Code Samples...
Language
<?php
use Illuminate\Http\Request;

Route::middleware('auth:api')->get('/user', function (Request $request) {
    return $request->user();
});

Route::middleware('validate.voice')->post('/voice', function (Request $request) {
    //Call has successfully passed spam screening.
    $twiml = new Twilio\Twiml();
    $twiml->say('Welcome to the jungle.',
        array('voice' => 'woman', 'language' => 'en-gb'));
    $twiml->hangup();
    return response($twiml)->header('Content-Type', 'text/xml');
});
Greet the non-spammer with <Say>

Configuring a Phone Number Webhook

Now we need to configure our Twilio phone number to call our application whenever a call comes in. So we just need a public host for our application. You can serve it any way you like as long as it's publicly accessible or you can use ngrok to test locally.

Armed with the URL to the application, open the Twilio Console and find the phone number you want to use (or buy a new number). On the configuration page for the number, scroll down to "Voice" and next to "A CALL COMES IN," select "Webhook" and paste in the function URL. (Be sure "HTTP POST" is selected, as well.)

block-spam-calls-php/routes/api.php Voice Webhook config

Everything is set up now, you can pick up your phone and call your Twilio number. Hopefully, if you are not a spammer your call should be accepted and you should hear the greeting.

Testing a Blocked Call

You can quickly call your Twilio number to make sure your call goes through. However, how can we test a blocked spam result? The easiest way is to write some unit tests that pass some dummied up JSON to our controller action. For example, if we wanted to test a Nomorobo “BLOCK” recommendation, we could use the following JSON:

Loading Code Samples...
Language
{
  "status": "successful",
  "message": null,
  "code": null,
  "results": {
    "nomorobo_spamscore": {
      "request_sid": "XRxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
      "status": "successful",
      "message": null,
      "code": null,
      "result": {
        "status": "success",
        "message": "success",
        "score": 1
      }
    }
  }
}
Nomorobo Add-on JSON result (blocked)

With that as our test fixture, we can write a test like the following to ensure that our call is blocked when we see the right data in the AddOns JSON:

Loading Code Samples...
Language
<?php

namespace Tests\Feature;

use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Illuminate\Foundation\Testing\WithoutMiddleware;
use SimpleXMLElement;
use Tests\TestCase;

class VoiceRouteTest extends TestCase
{
    protected static $AddOnValues;

    /**
     * Load JSON from file contained in fixtures directory.
     * @param  [string] $jsonFile file name.
     * @return [mixed] Object representing JSON decoded from file.
     */
    public static function loadJson($jsonFile)
    {
        $fixturesDir = './tests/fixtures';
        return json_decode(file_get_contents("${fixturesDir}/{$jsonFile}"));
    }

    public static function setUpBeforeClass()
    {
        $fixturesDir = './tests/fixtures';
        $fixtures = preg_grep("/\w/", scandir($fixturesDir)); 
        $AddOnValues = new \stdClass;

        foreach ($fixtures as $filename) {
            $fixtureKey = preg_replace("/\.json/", "", $filename);
            $AddOnValues->$fixtureKey = self::loadJson($filename);
        }

        self::$AddOnValues = $AddOnValues;
    }

    /**
     * Should fail without addons on /api/voice POST
     *
     * @return void
     */
    public function testSuccessWithoutAddonsOnPOST()
    {
        $response = $this->post('/api/voice');
        $response->assertHeader('Content-Type', 'text/xml; charset=UTF-8');

        $xmlResponse = new SimpleXMLElement($response->getContent());
        $rejectElements = $xmlResponse->xpath('/Response/Reject');
        $hasRejectVerb = count($rejectElements) > 0;
        $this->assertFalse($hasRejectVerb);

        $response->assertStatus(200);
    }

    /**
     * Should be successful when the incoming number is listed in the
     * whitepages with a reputation level not equal to 4 /api/voice POST
     *
     * @return void
     */
    public function testSuccessIfNumberIsInWhitepagesOnPOST()
    {
        $response = $this->json('POST', '/api/voice', [ 'AddOns' => self::$AddOnValues->successful_whitepages]);

        $xmlResponse = new SimpleXMLElement($response->getContent());
        $hasRejectVerb = count($xmlResponse->xpath('/Response/Reject')) > 0;
        $this->assertFalse($hasRejectVerb);

        $hasSayVerb = count($xmlResponse->xpath('/Response/Say')) > 0;
        $this->assertTrue($hasSayVerb);

        $hasHangUpVerb = count($xmlResponse->xpath('/Response/Hangup')) > 0;
        $this->assertTrue($hasHangUpVerb);

        $response->assertStatus(200);
    }

    /**
     * Should fail when the incoming number has a whitepages reputation level of 4 /api/voice POST
     *
     * @return void
     */
    public function testFailWhenWhitePagesReputationIsLowOnPOST()
    {
        $response = $this->json('POST', '/api/voice', [ 'AddOns' => self::$AddOnValues->spam_whitepages]);

        $xmlResponse = new SimpleXMLElement($response->getContent());
        $hasRejectVerb = count($xmlResponse->xpath('/Response/Reject')) > 0;
        $this->assertTrue($hasRejectVerb);

        $response->assertStatus(200);
    }

    /**
     * Should succeed when the incoming number has a Nomorobo score of 0  /api/voice POST
     *
     * @return void
     */
    public function testSucceedWhenNomoroboNotSpamOnPOST()
    {
        $response = $this->json('POST', '/api/voice', [ 'AddOns' => self::$AddOnValues->successful_nomorobo]);

        $xmlResponse = new SimpleXMLElement($response->getContent());
        $hasRejectVerb = count($xmlResponse->xpath('/Response/Reject')) > 0;
        $this->assertFalse($hasRejectVerb);

        $hasSayVerb = count($xmlResponse->xpath('/Response/Say')) > 0;
        $this->assertTrue($hasSayVerb);

        $hasHangUpVerb = count($xmlResponse->xpath('/Response/Hangup')) > 0;
        $this->assertTrue($hasHangUpVerb);

        $response->assertStatus(200);
    }

    /**
     * Should fail when the incoming number has a Nomorobo score of 1  /api/voice POST
     *
     * @return void
     */
    public function testFailWhenNomoroboIsSpamOnPOST()
    {
        $response = $this->json('POST', '/api/voice', [ 'AddOns' => self::$AddOnValues->spam_nomorobo]);

        $xmlResponse = new SimpleXMLElement($response->getContent());
        $hasRejectVerb = count($xmlResponse->xpath('/Response/Reject')) > 0;
        $this->assertTrue($hasRejectVerb);

        $response->assertStatus(200);
    }

    /**
     * Should fail when the incoming number Nomorobo result failed  /api/voice POST
     *
     * @return void
     */
    public function testFailWhenNomoroboFailedOnPOST()
    {
        $response = $this->json('POST', '/api/voice', [ 'AddOns' => self::$AddOnValues->failed_nomorobo]);

        $xmlResponse = new SimpleXMLElement($response->getContent());
        $hasRejectVerb = count($xmlResponse->xpath('/Response/Reject')) > 0;
        $this->assertTrue($hasRejectVerb);

        $response->assertStatus(200);
    }

    /**
     * Should succeed when the incoming number is recomended by Marchex to be given a PASS on /api/voice POST
     *
     * @return void
     */
    public function testSucceedWhenMarchexNotSpamOnPOST()
    {
        $response = $this->json('POST', '/api/voice', [ 'AddOns' => self::$AddOnValues->successful_marchex]);

        $xmlResponse = new SimpleXMLElement($response->getContent());
        $hasRejectVerb = count($xmlResponse->xpath('/Response/Reject')) > 0;
        $this->assertFalse($hasRejectVerb);

        $hasSayVerb = count($xmlResponse->xpath('/Response/Say')) > 0;
        $this->assertTrue($hasSayVerb);

        $hasHangUpVerb = count($xmlResponse->xpath('/Response/Hangup')) > 0;
        $this->assertTrue($hasHangUpVerb);

        $response->assertStatus(200);
    }

    /**
     * Should fail when the incoming number is recomended by Marchex to be BLOCKED on /api/voice POST
     *
     * @return void
     */
    public function testSucceedWhenMarchexIsSpamOnPOST()
    {
        $response = $this->json('POST', '/api/voice', [ 'AddOns' => self::$AddOnValues->spam_marchex]);

        $xmlResponse = new SimpleXMLElement($response->getContent());
        $hasRejectVerb = count($xmlResponse->xpath('/Response/Reject')) > 0;
        $this->assertTrue($hasRejectVerb);

        $response->assertStatus(200);
    }
}
Uses the previous fixture to ensure we block a call not recommended by Nomorobo
Testing a blocked call with Nomorobo

Uses the previous fixture to ensure we block a call not recommended by Nomorobo

What’s Next?

As you can see, the Twilio Add-ons Marketplace gives you a lot of options for extending your Twilio apps. Next, you might want to dig into the Add-ons reference or perhaps glean some pearls from our other PHP tutorials. Wherever you’re headed next, you can confidently put spammers in your rearview mirror.

Jose Oliveros
Samuel Mendes
Agustin Camino
David Prothero

Need some help?

We all do sometimes; code is hard. Get help now from our support team, or lean on the wisdom of the crowd browsing the Twilio tag on Stack Overflow.

1 / 1
Loading Code Samples...
<?php

namespace App\Http\Middleware;

use Closure;
use Flow\JSONPath\JSONPath;

class ValidateVoiceRequest
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $requestJson = new JSONPath($request->json()->all());

        $validateJSONPath = function ($JSONPath) use ($requestJson) {
            return $requestJson->find($JSONPath)->valid();
        };

        $rejectIncomingCall = function () {
            $twiml = new \Twilio\Twiml();
            $twiml->reject();
            return response($twiml)->header('Content-Type', 'text/xml');
        };

        if (!$validateJSONPath('$.AddOns')) {
          return $next($request);
        }

        $JSONPaths = [
            'isWhitePagesSpam' => '$..whitepages_pro_phone_rep..[?(@.type=="ScamOrFraud")]',
            'isNomoroboSpam' => '$.*.*.nomorobo_spamscore..[?(@.score==1)]',
            'nomoroboFailed' => '$.*.*.[?(@.status=="failed")]',
            'isMarchexSpam' => '$.*.*.marchex_cleancall..[?(@.recommendation!="PASS")]'
        ];

        foreach ($JSONPaths as $JSONPath) {
            if ($validateJSONPath($JSONPath)) {
                return $rejectIncomingCall();
            }
        }

        return $next($request);
    }
}
{
  "status": "successful",
  "message": null,
  "code": null,
  "results": {
    "whitepages_pro_phone_rep": {
        "code": null,
        "message": null,
        "request_sid": "XR63dbb880c4fcd054a810f603f304bd31",
        "result": {
            "error": null,
            "id": "Phone.4d796fef-a2df-4b08-cfe3-bc7128b6f6bb.Durable",
            "phone_number": "2069735100",
            "report_count": 1,
            "reputation_details": {
                "category": null,
                "score": 0,
                "type": "NotSpamType"
            },
            "reputation_level": 1,
            "volume_score": 1,
            "warnings": []
        },
        "status": "successful"
    }
  }
}
<?php

namespace App\Http\Middleware;

use Closure;
use Flow\JSONPath\JSONPath;

class ValidateVoiceRequest
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $requestJson = new JSONPath($request->json()->all());

        $validateJSONPath = function ($JSONPath) use ($requestJson) {
            return $requestJson->find($JSONPath)->valid();
        };

        $rejectIncomingCall = function () {
            $twiml = new \Twilio\Twiml();
            $twiml->reject();
            return response($twiml)->header('Content-Type', 'text/xml');
        };

        if (!$validateJSONPath('$.AddOns')) {
          return $next($request);
        }

        $JSONPaths = [
            'isWhitePagesSpam' => '$..whitepages_pro_phone_rep..[?(@.type=="ScamOrFraud")]',
            'isNomoroboSpam' => '$.*.*.nomorobo_spamscore..[?(@.score==1)]',
            'nomoroboFailed' => '$.*.*.[?(@.status=="failed")]',
            'isMarchexSpam' => '$.*.*.marchex_cleancall..[?(@.recommendation!="PASS")]'
        ];

        foreach ($JSONPaths as $JSONPath) {
            if ($validateJSONPath($JSONPath)) {
                return $rejectIncomingCall();
            }
        }

        return $next($request);
    }
}
{
  "status": "successful",
  "message": null,
  "code": null,
  "results": {
    "marchex_cleancall": {
      "request_sid": "XRxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
      "status": "successful",
      "message": null,
      "code": null,
      "result": {
        "result": {
          "recommendation": "PASS",
          "reason": "CleanCall"
        }
      }
    }
  }
}
<?php

namespace App\Http\Middleware;

use Closure;
use Flow\JSONPath\JSONPath;

class ValidateVoiceRequest
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $requestJson = new JSONPath($request->json()->all());

        $validateJSONPath = function ($JSONPath) use ($requestJson) {
            return $requestJson->find($JSONPath)->valid();
        };

        $rejectIncomingCall = function () {
            $twiml = new \Twilio\Twiml();
            $twiml->reject();
            return response($twiml)->header('Content-Type', 'text/xml');
        };

        if (!$validateJSONPath('$.AddOns')) {
          return $next($request);
        }

        $JSONPaths = [
            'isWhitePagesSpam' => '$..whitepages_pro_phone_rep..[?(@.type=="ScamOrFraud")]',
            'isNomoroboSpam' => '$.*.*.nomorobo_spamscore..[?(@.score==1)]',
            'nomoroboFailed' => '$.*.*.[?(@.status=="failed")]',
            'isMarchexSpam' => '$.*.*.marchex_cleancall..[?(@.recommendation!="PASS")]'
        ];

        foreach ($JSONPaths as $JSONPath) {
            if ($validateJSONPath($JSONPath)) {
                return $rejectIncomingCall();
            }
        }

        return $next($request);
    }
}
{
  "status": "successful",
  "message": null,
  "code": null,
  "results": {
    "nomorobo_spamscore": {
      "request_sid": "XRxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
      "status": "successful",
      "message": null,
      "code": null,
      "result": {
        "status": "success",
        "message": "success",
        "score": 0
      }
    }
  }
}
<?php

namespace App\Http\Middleware;

use Closure;
use Flow\JSONPath\JSONPath;

class ValidateVoiceRequest
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $requestJson = new JSONPath($request->json()->all());

        $validateJSONPath = function ($JSONPath) use ($requestJson) {
            return $requestJson->find($JSONPath)->valid();
        };

        $rejectIncomingCall = function () {
            $twiml = new \Twilio\Twiml();
            $twiml->reject();
            return response($twiml)->header('Content-Type', 'text/xml');
        };

        if (!$validateJSONPath('$.AddOns')) {
          return $next($request);
        }

        $JSONPaths = [
            'isWhitePagesSpam' => '$..whitepages_pro_phone_rep..[?(@.type=="ScamOrFraud")]',
            'isNomoroboSpam' => '$.*.*.nomorobo_spamscore..[?(@.score==1)]',
            'nomoroboFailed' => '$.*.*.[?(@.status=="failed")]',
            'isMarchexSpam' => '$.*.*.marchex_cleancall..[?(@.recommendation!="PASS")]'
        ];

        foreach ($JSONPaths as $JSONPath) {
            if ($validateJSONPath($JSONPath)) {
                return $rejectIncomingCall();
            }
        }

        return $next($request);
    }
}
<?php
use Illuminate\Http\Request;

Route::middleware('auth:api')->get('/user', function (Request $request) {
    return $request->user();
});

Route::middleware('validate.voice')->post('/voice', function (Request $request) {
    //Call has successfully passed spam screening.
    $twiml = new Twilio\Twiml();
    $twiml->say('Welcome to the jungle.',
        array('voice' => 'woman', 'language' => 'en-gb'));
    $twiml->hangup();
    return response($twiml)->header('Content-Type', 'text/xml');
});
<?php

namespace App\Http\Middleware;

use Closure;
use Flow\JSONPath\JSONPath;

class ValidateVoiceRequest
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $requestJson = new JSONPath($request->json()->all());

        $validateJSONPath = function ($JSONPath) use ($requestJson) {
            return $requestJson->find($JSONPath)->valid();
        };

        $rejectIncomingCall = function () {
            $twiml = new \Twilio\Twiml();
            $twiml->reject();
            return response($twiml)->header('Content-Type', 'text/xml');
        };

        if (!$validateJSONPath('$.AddOns')) {
          return $next($request);
        }

        $JSONPaths = [
            'isWhitePagesSpam' => '$..whitepages_pro_phone_rep..[?(@.type=="ScamOrFraud")]',
            'isNomoroboSpam' => '$.*.*.nomorobo_spamscore..[?(@.score==1)]',
            'nomoroboFailed' => '$.*.*.[?(@.status=="failed")]',
            'isMarchexSpam' => '$.*.*.marchex_cleancall..[?(@.recommendation!="PASS")]'
        ];

        foreach ($JSONPaths as $JSONPath) {
            if ($validateJSONPath($JSONPath)) {
                return $rejectIncomingCall();
            }
        }

        return $next($request);
    }
}
<?php
use Illuminate\Http\Request;

Route::middleware('auth:api')->get('/user', function (Request $request) {
    return $request->user();
});

Route::middleware('validate.voice')->post('/voice', function (Request $request) {
    //Call has successfully passed spam screening.
    $twiml = new Twilio\Twiml();
    $twiml->say('Welcome to the jungle.',
        array('voice' => 'woman', 'language' => 'en-gb'));
    $twiml->hangup();
    return response($twiml)->header('Content-Type', 'text/xml');
});
{
  "status": "successful",
  "message": null,
  "code": null,
  "results": {
    "nomorobo_spamscore": {
      "request_sid": "XRxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
      "status": "successful",
      "message": null,
      "code": null,
      "result": {
        "status": "success",
        "message": "success",
        "score": 1
      }
    }
  }
}
<?php

namespace Tests\Feature;

use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Illuminate\Foundation\Testing\WithoutMiddleware;
use SimpleXMLElement;
use Tests\TestCase;

class VoiceRouteTest extends TestCase
{
    protected static $AddOnValues;

    /**
     * Load JSON from file contained in fixtures directory.
     * @param  [string] $jsonFile file name.
     * @return [mixed] Object representing JSON decoded from file.
     */
    public static function loadJson($jsonFile)
    {
        $fixturesDir = './tests/fixtures';
        return json_decode(file_get_contents("${fixturesDir}/{$jsonFile}"));
    }

    public static function setUpBeforeClass()
    {
        $fixturesDir = './tests/fixtures';
        $fixtures = preg_grep("/\w/", scandir($fixturesDir)); 
        $AddOnValues = new \stdClass;

        foreach ($fixtures as $filename) {
            $fixtureKey = preg_replace("/\.json/", "", $filename);
            $AddOnValues->$fixtureKey = self::loadJson($filename);
        }

        self::$AddOnValues = $AddOnValues;
    }

    /**
     * Should fail without addons on /api/voice POST
     *
     * @return void
     */
    public function testSuccessWithoutAddonsOnPOST()
    {
        $response = $this->post('/api/voice');
        $response->assertHeader('Content-Type', 'text/xml; charset=UTF-8');

        $xmlResponse = new SimpleXMLElement($response->getContent());
        $rejectElements = $xmlResponse->xpath('/Response/Reject');
        $hasRejectVerb = count($rejectElements) > 0;
        $this->assertFalse($hasRejectVerb);

        $response->assertStatus(200);
    }

    /**
     * Should be successful when the incoming number is listed in the
     * whitepages with a reputation level not equal to 4 /api/voice POST
     *
     * @return void
     */
    public function testSuccessIfNumberIsInWhitepagesOnPOST()
    {
        $response = $this->json('POST', '/api/voice', [ 'AddOns' => self::$AddOnValues->successful_whitepages]);

        $xmlResponse = new SimpleXMLElement($response->getContent());
        $hasRejectVerb = count($xmlResponse->xpath('/Response/Reject')) > 0;
        $this->assertFalse($hasRejectVerb);

        $hasSayVerb = count($xmlResponse->xpath('/Response/Say')) > 0;
        $this->assertTrue($hasSayVerb);

        $hasHangUpVerb = count($xmlResponse->xpath('/Response/Hangup')) > 0;
        $this->assertTrue($hasHangUpVerb);

        $response->assertStatus(200);
    }

    /**
     * Should fail when the incoming number has a whitepages reputation level of 4 /api/voice POST
     *
     * @return void
     */
    public function testFailWhenWhitePagesReputationIsLowOnPOST()
    {
        $response = $this->json('POST', '/api/voice', [ 'AddOns' => self::$AddOnValues->spam_whitepages]);

        $xmlResponse = new SimpleXMLElement($response->getContent());
        $hasRejectVerb = count($xmlResponse->xpath('/Response/Reject')) > 0;
        $this->assertTrue($hasRejectVerb);

        $response->assertStatus(200);
    }

    /**
     * Should succeed when the incoming number has a Nomorobo score of 0  /api/voice POST
     *
     * @return void
     */
    public function testSucceedWhenNomoroboNotSpamOnPOST()
    {
        $response = $this->json('POST', '/api/voice', [ 'AddOns' => self::$AddOnValues->successful_nomorobo]);

        $xmlResponse = new SimpleXMLElement($response->getContent());
        $hasRejectVerb = count($xmlResponse->xpath('/Response/Reject')) > 0;
        $this->assertFalse($hasRejectVerb);

        $hasSayVerb = count($xmlResponse->xpath('/Response/Say')) > 0;
        $this->assertTrue($hasSayVerb);

        $hasHangUpVerb = count($xmlResponse->xpath('/Response/Hangup')) > 0;
        $this->assertTrue($hasHangUpVerb);

        $response->assertStatus(200);
    }

    /**
     * Should fail when the incoming number has a Nomorobo score of 1  /api/voice POST
     *
     * @return void
     */
    public function testFailWhenNomoroboIsSpamOnPOST()
    {
        $response = $this->json('POST', '/api/voice', [ 'AddOns' => self::$AddOnValues->spam_nomorobo]);

        $xmlResponse = new SimpleXMLElement($response->getContent());
        $hasRejectVerb = count($xmlResponse->xpath('/Response/Reject')) > 0;
        $this->assertTrue($hasRejectVerb);

        $response->assertStatus(200);
    }

    /**
     * Should fail when the incoming number Nomorobo result failed  /api/voice POST
     *
     * @return void
     */
    public function testFailWhenNomoroboFailedOnPOST()
    {
        $response = $this->json('POST', '/api/voice', [ 'AddOns' => self::$AddOnValues->failed_nomorobo]);

        $xmlResponse = new SimpleXMLElement($response->getContent());
        $hasRejectVerb = count($xmlResponse->xpath('/Response/Reject')) > 0;
        $this->assertTrue($hasRejectVerb);

        $response->assertStatus(200);
    }

    /**
     * Should succeed when the incoming number is recomended by Marchex to be given a PASS on /api/voice POST
     *
     * @return void
     */
    public function testSucceedWhenMarchexNotSpamOnPOST()
    {
        $response = $this->json('POST', '/api/voice', [ 'AddOns' => self::$AddOnValues->successful_marchex]);

        $xmlResponse = new SimpleXMLElement($response->getContent());
        $hasRejectVerb = count($xmlResponse->xpath('/Response/Reject')) > 0;
        $this->assertFalse($hasRejectVerb);

        $hasSayVerb = count($xmlResponse->xpath('/Response/Say')) > 0;
        $this->assertTrue($hasSayVerb);

        $hasHangUpVerb = count($xmlResponse->xpath('/Response/Hangup')) > 0;
        $this->assertTrue($hasHangUpVerb);

        $response->assertStatus(200);
    }

    /**
     * Should fail when the incoming number is recomended by Marchex to be BLOCKED on /api/voice POST
     *
     * @return void
     */
    public function testSucceedWhenMarchexIsSpamOnPOST()
    {
        $response = $this->json('POST', '/api/voice', [ 'AddOns' => self::$AddOnValues->spam_marchex]);

        $xmlResponse = new SimpleXMLElement($response->getContent());
        $hasRejectVerb = count($xmlResponse->xpath('/Response/Reject')) > 0;
        $this->assertTrue($hasRejectVerb);

        $response->assertStatus(200);
    }
}