I need to validate incoming SMS messages from the service SignalWire (make sure SignalWire it's sent from) for a PHP application where the SMS is sent via webhook and LAML to a URL I specify.
SignalWire's documentation only covers Node.js and Python, and tells to use those libraries. There are no examples for PHP.
SignalWire's PHP libraries rely on Twilio's libraries. Their LAML webhook is compatible with Twilio. Use Composer to get the PHP libraries for SignalWire:
composer require signalwire-community/signalwire
PHP where receiving the POST request when an SMS comes in 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 Twilio\Security\RequestValidator($signing_key);
$headers = getallheaders();
$signature = $headers['X-Twilio-Signature'];
$url = 'https://example.com/handle-incoming-sms'; // Whatever your URL is.
// Get rid of POST variables SignalWire didn't send.
unset($_POST['some_non_signalwire_var']);
unset($_POST['some_other_non_signalwire_var']);
// Sort the keys of the POST in alphabetical order.
ksort($_POST);
// Perform validation:
$result = $validator->validate($signature, $url, $_POST);
if (intval($result) === 0) {
// Failure to validate (code here to handle that).
}
intval()
isn't necessary (the function returns FALSE
I believe), but I convert to int so I can use ===
.