I needed to “validate” incoming SMS messages from the service SignalWire (aka, make sure SignalWire was the one who actually sent it). This was for a PHP application, where the incoming SMS was being sent via webhook (and “LAML”) to a URL I specified.
Unfortunately, SignalWire’s documentation at the time of this writing only covers Node.js and Python, and just tells you to use those libraries. There’s no validation help or examples for PHP.
It took me a long time, but I eventually figured out what to do, so I am going to post the answer below for others it might help in the future.
For those who may not know, SignalWire’s PHP libraries rely on Twilio’s libraries to function. Their LAML webhook is meant to be 100% compatible with Twilio. So, we end up having to use Twilio objects & code to perform the validation / verification.
Use composer to get the PHP libraries for SignalWire:
composer require signalwire-community/signalwire
In your PHP code, where you actually are receiving the POST request when an SMS comes in, your code should look similar to this:
require_once('signalwire/vendor/autoload.php'); // Include the SignalWire lib
$signing_key = 'PF_KJ45jk3jhy....uU3'; // On your SignalWire API page.
$validator = new TwilioSecurityRequestValidator($signing_key);
$headers = getallheaders();
$signature = $headers['X-Twilio-Signature'];
$url = 'https://example.com/handle-incoming-sms'; // Whatever your URL is
// Get rid of any POST variables which SignalWire didn't send you!
unset($_POST['some_non_signalwire_var']);
unset($_POST['some_other_non_signalwire_var']);
// VERY important: sort the keys of the POST into alphabetical order!!
ksort($_POST);
// Actually perform validation finally:
$result = $validator->validate($signature, $url, $_POST);
if (intval($result) === 0) {
// FAILURE. DID NOT VALIDATE. Do code here to handle that.
}
I know the intval() at the end probably isn’t necessary, as the function returns a FALSE (I believe), but my personal preference is to explicitly convert to int so I can use ===.
I hope others find this helpful!