Skip to content

Instantly share code, notes, and snippets.

@BinaryKitten
Created January 19, 2021 10:04
Show Gist options
  • Save BinaryKitten/fa872f29542b3dc2a080f642957287d3 to your computer and use it in GitHub Desktop.
Save BinaryKitten/fa872f29542b3dc2a080f642957287d3 to your computer and use it in GitHub Desktop.
<?php
// this is routes/web.php
Route::twillioWebhook('/blah', Controller::class);
<?php
public function boot()
{
if (! Route::hasMacro('twillioWebhook')) {
Route::macro('twillioWebhook', function ($uri, $action = null) {
return Route::post($url, $action)
->withoutMiddleware([\App\Http\Middleware\VerifyCsrfToken::class]
->middleware([\App\Http\Middleware\TwillioWebhookVerify::class])
});
}
}
<?php
declare(strict_types=1);
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
/**
* This should sit in app/Http/Middleware
**/
class TwillioWebhookVerify
{
public function handle(Request $request, Closure $next)
{
$authToken = getenv('TWILIO_AUTH_TOKEN'); // stored in an env var for safety
$validator = new \Twilio\Security\RequestValidator($authToken);
$signature = $request->server('HTTP_X_TWILIO_SIGNATURE',null);
$url = url()->current();
// $url = 'https://geeh.ngrok.io/hook.php';
if(!$validator->validate($signature, $url, $request->post())) {
return response('Invalid Webhook', 403);
// we may want to consider returning a custom status code like 403
}
return $next($request);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment