What are Webhooks? Example use case of payment Gateway.
In this article, we will see what is webhooks? and a use case for it and how to test webhook locally.
Webhooks are just like callbacks but the only difference is there are HTTP callbacks.
It is triggered by some event in web application.
Let's see this use-case in detail.
Suppose we have an online site which sells T-shirts and for that we need some payment gateway.
For that, we have decided to use a Razorpay payment gateway.
So here the flow will be somewhat like this.
Users log in to the website and add some T-shirts into the cart and do checkout.
Backend side when a user does checkout:
Will create an order for the user with payment status 'pending' and will log
that in our database with respect to that user.
Then we create a payment order for the user using Razorpay APIs and send a payment checkout link to the user. (Consider this payment checkout link is of third party i.e Razorpay)
How will we know if the user has done with checkout or started payment? Or he may pay for the order the next day.
So here we can't know the status of the user as the payment link is third party.
For this purpose, Razorpay has provided a webhook to let us know about the different life cycles of that transaction.
Like the user started payment but failed then again started and paid money successfully.
So that we can update the latest payment status of his order in our database.
Login to Razorpay and create an account(More information check documentation).
Then in setting, you have a webhook URL option.
Here you have to configure a URL.
So whenever a user pays money in the cart checkout, Razorpay will send an HTTP POST payload to your configured URL regarding the status of the payment so that you can update details in your database.
As for testing this thing we need a URL
(One we can create using AWS API gateway and can add a lambda to it.
And then we can check logs of lambda for webhook event information)
But what if you want to test webhooks locally?
There are 2 options:
Just login and then create a requestbin.
Then you will get an endpoint URL that you can configure to webhook and can watch any request to that URL.
Note:(Here you can start quick testing by creating and canceling subscription in test mode for Razorpay and then capture this event.)
Just download ngrok for your operating system.
Run command (Inside the ngrok terminal): ngrok http 80 (This will expose your local server to public)
You will get a ngrok URL which you can configure as webHook URL.