what is a webhook?

You may have heard so much about WebHooks lately and on many websites especially Github, you may have seen WebHooks settings. so what is WebHooks?

WebHooks

The concept of a WebHook is simple. A WebHook is an HTTP callback: an HTTP POST that occurs when something happens; a simple event-notification via HTTP POST.

A web application implementing WebHooks will POST a message to a URL when certain things happen. WebHooks are a way to receive valuable information when it happens, rather than continually polling for that data and receiving nothing valuable most of the time. WebHooks have enormous potential and are limited only by your imagination!

So it is basically same as API but in this case, you don’t send any response back. you host your API somewhere, provide this URL to say for example stripe, then for any events occurring at the stripe, it will POST the data to this URL. so you get notified whenever someone pays in your application using stripe.

WebHooks are meant to do something. To get your imagination spinning with your own ideas, here are is one such example,

Most famous Stripe payment gateway provides WebHooks for many events such as when someone pays in your application then source. the chargeable event is fired. so you can create a simple API which parses the POST data and looks for a positive event such as new order. whenever such events occur, it will play a beep sound. isn’t it a fun? It’s kind of cash counter sound whenever you get a new order.

Implementation

WebHook can be implemented in the same way as any other API. you can use any language you’re comfortable with. I have used here php because I like the php silex lightweight framework to create API fast.

Go to your php project folder and install silex using composer :

composer require silex/silex "2.0"

create index.php and insert below code :

<?php 
require_once __DIR__.'/../vendor/autoload.php';
    $app = new Silex\Application();
    $app->post('/webhook', function (Request $request) {
header('Content-Type: application/json');
$request = file_get_contents('php://input');
$req_dump = print_r( $request, true );
$fp = file_put_contents( 'webhook_request.log', $req_dump );
});
    $app->run();
?>

Test

Call this URL and it will save the POST request in webhook_request.log in the project folder. But check the permission of folder if you’re using Linux. It won’t print anything and will give an error if the server does not have enough permission to write.

Generally, this URL will be called by other application but for testing, you can call it. If you want to test WebHooks on your localhost then checkout Ultrahook. It’s a free utility that routes all WebHooks to your localhost.

Conclusion

And that’s it! Did this work for you? Please leave any questions and comments below!

Thank you for reading!

If you found this article helpful, 👏👏👏.