A webhook is also known as a “reverse API.” It is a tool that enables one system or application to communicate and deliver real-time notifications about a specific event to another system or application. Webhook working mechanism is simple, Let’s understand it using below architecture diagram which differentiate between pooling (API) vs Webhook.
Below is simple implementation of webhook concept, We have a server or service provider which provides services that multiple consumers consumer1, consumer2, consumer..n can access. Each consumer has to provide a publicly accessible endpoint to the service provider and subscribe for particular events like (order place, shipment creation) etc.
Whenever such events takes place at service providers end, service provider traverse the consumers endpoints and POST the event specific payload to the endpoint, at consumer end, consumer have logic to read standard input stream data and utilises it for further processing.
Below is service provider post data file for consumers.
webhook_post.sh
#! /bin/bash
curl -X POST -H 'Content-Type: application/json' -d '[ { "id"": "001", "type": "MESSAGE", "status": "DONE" } ]' http://localhost:8188/webhook_callback.php
ShellScriptwebhook_callback.php
<?php
$entityBody = file_get_contents('php://input');
$data = json_decode(utf8_encode($entityBody));
if (json_last_error()) {
$error = "JSON parsing error: " . json_last_error();
print $error;
// To-do Add some logging for errors
return;
}
print_r($data);
// Process data recived from webhook
?>
PHPREADME.md
## RUN WEBHOOK RECIEVER ENDPOINT SERVER ##
- To run the server and expose "webhook_callback.php" file to publically
`php -S localhost:8188`
## POST DATA TO WEBHOOK ENDPOINT WITH PAYLOAD ##
- To post data to webhook endpoint
`./webhook_post.sh`