I'm having trouble with Twilio signature validation in my PHP webhook. I am working alongside their support team but the validation still seems to fail, leading to a rejected response. Here is the code snippet that's causing issues:
<?php
require '/path/to/vendor/autoload.php';
use Twilio\Security\RequestValidator;
use Twilio\TwiML\VoiceResponse;
// Load configuration from the ini file
$config = parse_ini_file('/path/to/config.ini', true);
if (!$config) {
error_log("Failed to parse config.ini");
$response = new VoiceResponse();
$response->say("Failed to parse config.ini");
header('Content-Type: text/xml');
echo $response;
exit;
}
$token = $config['twilio']['token'];
$validator = new RequestValidator($token);
$signature = $_SERVER['HTTP_X_TWILIO_SIGNATURE'] ?? '';
$url = 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
$response = new VoiceResponse();
if ($validator->validate($signature, $url)) {
$response->say("Confirmed to have come from Twilio.");
error_log("Confirmed to have come from Twilio.");
} else {
error_log("Invalid Twilio signature received");
error_log("Signature received: " . $signature);
error_log("URL used for validation: " . $url);
$server_data = print_r($_SERVER, true);
error_log("Server Data: " . $server_data);
$response->reject();
}
header('Content-Type: text/xml');
echo $response;
?>
Each time the validation fails and I receive the Rejection and the error logs that I put in.
If I remove the validation code, I can succesfully make a call to my Twilio number and have it respond as desired.
Just for more clarification, I'm using Cloudflare on my site in case that may affect any headers.
I've been struggling with this for a long time so any help is hugely appreciated.
Kind regards