Skip to content

Instantly share code, notes, and snippets.

@kohenkatz
Created May 29, 2024 02:33
Show Gist options
  • Save kohenkatz/620f3b51f26bf75ab5d38927007623cb to your computer and use it in GitHub Desktop.
Save kohenkatz/620f3b51f26bf75ab5d38927007623cb to your computer and use it in GitHub Desktop.
Laravel 10.x - Injecting the Twilio webhook validator only if we have the Auth Token configured.
# If this has a value, it enabled the validation check
TWILIO_VALIDATE_WEBHOOKS_TOKEN=
<?php
namespace App\Providers;
use Illuminate\Contracts\Foundation\Application;
use Illuminate\Support\ServiceProvider;
use Twilio\Security\RequestValidator;
class AppServiceProvider extends ServiceProvider
{
public function register(): void
{
if (($validatorSecret = config('services.twilio.validate_webhooks_token'))) {
$this->app->singleton(RequestValidator::class, function (Application $app) use ($validatorSecret) {
return new RequestValidator($validatorSecret);
});
}
}
}
<?php
return [
'twilio' => [
'validate_webhooks_token' => env('TWILIO_VALIDATE_WEBHOOKS_TOKEN'),
],
];
<?php
namespace App\Http\Phone\Incoming;
use Illuminate\Http\Response;
use Twilio\TwiML\VoiceResponse;
class Support
{
function __invoke(TwilioWebhookRequest $request): Response
{
$response = new VoiceResponse();
$response->say('Thank you for calling us. Please hold while we connect you with the next available representative.');
$response->dial()
->sip('my-sip-queue@my-sip-domain');
return response($response)->header('Content-Type', 'text/xml');
}
}
<?php
namespace App\Http\Phone\Incoming;
use Illuminate\Foundation\Http\FormRequest;
use Twilio\Security\RequestValidator;
class TwilioWebhookRequest extends FormRequest
{
public function __construct(
// If the validator is configured, it will be injected
private ?RequestValidator $twilioValidator = null,
)
{ }
public function authorize(): bool
{
// If we do not have the validator configured, validation is skipped
if (!$this->twilioValidator) {
return true;
}
$expectedSignature = $this->header('X-Twilio-Signature');
if (!$expectedSignature) {
return false;
}
return $this->twilioValidator->validate(
$expectedSignature,
$this->fullUrl(),
$this->all(),
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment