Create your own webhook mechanism with Laravel notification.

Tram Ho

Preamble

Today I will show you how to create your own webhook mechanism. we have known for a long time and use the webhook function of github, facebook … They kind of let me enter a Payload URL and select the event so that when the event happens, github will also send http request to Payload URL of the user.

Similarly, in this demo we will allow users to enter their webhook url. and when there is an event on our system, the system also proceeds to send http requests to their url (request including body and header).

What is webhook?

Install Dependencies

First we need to install the package for sending HTTP requests. Here I use quite popular library is Guzzle:

Data migration

Next we create the user table. In this demo, I will save name , email , password , api_token and especially have the webhook_url field which is the user’s enpoint when registering Webhook End Point on our system.

Create a model

Next is to create the User model

This model is quite easy to understand. I have 2 more functions getSigningKey and getWebhookUrl to get api_key and webhook_url

Create notification channels

Next we need to create a notification channel. Then laravel support us create as well as custom notification channels here .

Proceed to create WebhookChannel

The send function is where we write the code to make the send http request to the user’s endpoint (webhook_url).

Next I proceed to write the send function

Firstly ,

That’s it, 1 notification channels. Next, I just need to call Webhook notification and use it.

Make webhook notification

Next we create the notification by command

Proceed to write the code.

ok That’s it! Now we can create events and send notifications to the endpoint that the user has registered.

Conclude

Thank you for reading here.

Reference: https://laravel.com/docs/5.6/notifications#custom-channels ,

Source code: https://github.com/phamtuananh1996/laravel-webhook-demo

Share the news now

Source : Viblo