2

I am working with a Webhook based of of SendGrid's API v3. The Webhook is completely set up with an endpoint that SendGrid posts to, but I need to be able to receive that parsed data and store it in a database using PHP, but do not know how to do that.

I have worked with APIs before where I initiate the retrieval or POST of data, but when the API server is the one POSTing, how do I catch the data being parsed through the Webhook endpoint? I have some simple thus far, but am really unclear of how to tackle this:

<?php

$json = file_get_contents('https://example.com/webhook.php');
$json_decoded = json_decode($json, true);
$var_dump(json_decoded);

?>

I have tried sending multiple emails to the host, but every time I make this call I return NULL.

Jodo1992
  • 745
  • 2
  • 10
  • 32

1 Answers1

7

Try using the code from this example. This will give you the raw HTTP request body bytes to decode.

<?php
$data = file_get_contents("php://input");
$events = json_decode($data, true);

foreach ($events as $event) {
  // Here, you now have each event and can process them how you like
  process_event($event);
}
?>

More info on php://input

Community
  • 1
  • 1
bwest
  • 9,182
  • 3
  • 28
  • 58
  • Where would I call the url that SendGrid is POSTing to? – Jodo1992 Aug 30 '16 at 16:57
  • You don't. that code goes into the file that your webhook URL points to... you then need to have that page hosted and available. You are creating a server to respond to requests. This post might help: https://sendgrid.com/blog/whats-webhook/ – bwest Aug 30 '16 at 17:15