Skip to content
Advertisement

Issues creating a PHP webhook for Twilio

So I have the following CURL command in PHP, if I send it https://webhook.site I can extract all the required data in JSON format.

Instead of using webhook.site, I would like to create my own PHP webhook client.

The code below is the CURL command that works 100% when using webhook.site:

<?php

   $curl = curl_init();

   curl_setopt_array($curl, array(
   CURLOPT_URL => 'https://webhook.site/832090f1-f54f-4847-8c0d-5ec9208541a1',
   CURLOPT_RETURNTRANSFER => true,
   CURLOPT_ENCODING => '',
   CURLOPT_MAXREDIRS => 10,
   CURLOPT_TIMEOUT => 0,
   CURLOPT_FOLLOWLOCATION => true,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => 'POST',
  CURLOPT_POSTFIELDS => array('SmsSid' => 'SMe8723661742d423fbf3fa9f7bbede050','SmsStatus' => 'sent','MessageStatus' => 'sent','ChannelToAddress' => '+1788123XXXX','To' => 'whatsapp:+15196978899','ChannelPrefix' => 'whatsapp','MessageSid' => 'SMe8723661742d423fbf3fa9f7bbede050','AccountSid' => 'AC306a09582e77715b0eb72df90de4c590','StructuredMessage' => 'false','From' => 'whatsapp:+154xxxxxx','MediaUrl0' => 'https://api.twilio.com/2010-04-01/Accounts/werwersdsdg72df90de4c590/Messages/wweugryuwyr7762b11ea/Media/wjeruwiy6243742

'),
  CURLOPT_HTTPHEADER => array(
    'user-agent: TwilioProxy/1.1',
    'host: Postman'
  ),
));

$response = curl_exec($curl);

curl_close($curl);
echo $response;

I then tried to use PHP to create a basic webhook just to pull the data:

<?php
if($json = json_decode(file_get_contents("php://input"), true)){
   $data = $json;
   $fp = file_put_contents( 'request.log', $data );
}
print_r($data);
?>

But I keep coming with a blank request.log file – what am I doing wrong??? Thanks in advance

Advertisement

Answer

Twilio developer evangelist here.

By default, curl will make a POST request with the Content-Type header application/x-www-form-urlencoded. This is actually the same content type that Twilio uses when it sends a webhook request.

Your PHP to receive the request is trying to json_decode the data, which won’t work with form encoded data. Instead, you can access $_POST to get an associative array of the parameters sent to your script. You can then write them to a log file however you like.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement