An Interest In:
Web News this Week
- April 24, 2024
- April 23, 2024
- April 22, 2024
- April 21, 2024
- April 20, 2024
- April 19, 2024
- April 18, 2024
Webhook - Part II
Continue from previous post, let's build our first Webhook Provider.
We going to build using Laravel, and a package from Spatie, Laravel Webhook Server.
Create New Laravel Project
Let's create a new Laravel project:
laravel new webhook-client --git --jet --stack=livewire php artisan queue:tablephp artisan migrate
Install & Configure the Package
And install the package:
composer require spatie/laravel-webhook-serverphp artisan vendor:publish --provider="Spatie\WebhookServer\WebhookServerServiceProvider"
By default, Spatie already pre-configured your Webhook, as in config/webhook-server.php
:
<?phpreturn [ 'queue' => 'default', 'connection' => null, 'http_verb' => 'post', 'signer' => \Spatie\WebhookServer\Signer\DefaultSigner::class, 'signature_header_name' => 'Signature', 'headers' => [ 'Content-Type' => 'application/json', ], 'timeout_in_seconds' => 3, 'tries' => 3, 'backoff_strategy' => \Spatie\WebhookServer\BackoffStrategy\ExponentialBackoffStrategy::class, 'verify_ssl' => env('WEBHOOK_VERIFY_SSL', false), 'throw_exception_on_failure' => false, 'tags' => [],];
As for development, the verify_ssl
, I want to turn it off - you can make it configurable by set as following:
'verify_ssl` = env('WEBHOOK_VERIFY_SSL', false),
So by default, verify SSL is optional - unless in production I recommended to turn it on.
Another configuration that you might interested is setting the headers. This allow you to have some sort of identifier, that the payload is coming from you. I would suggest to add:
'headers' => [ 'Content-Type' => 'application/json', 'X-App' => env('APP_NAME'), 'X-Version' => 1.0],
Next, we going to use database queue, update the .env
:
QUEUE_CONNECTION=database
The Syntax
Now the fun part, send the payload. Sending the payload is a straightforward setup, as per in the documentation:
WebhookCall::create() ->url('https://other-app.com/webhooks') ->payload(['key' => 'value']) ->useSecret('sign-using-this-secret') ->dispatch();
As you can see here, it's just a few line of codes. Let's describe it a little bit.
The url()
method, you need to provide the Webhook Consumer endpoint that receiving the data / information / payload from the Webhook Provider.
The payload()
accept an array of data, which all the information you want to share with your Webhook Consumer.
The useSecret()
is a secret key that your Webhook Consumer will share with you. So that, when Webhook Consumer receiving the payload, they will check against the signature sent by the Webhook Provider.
The dispatch()
, basically send the payload to the queue job, to send the information to Webhook consumer. By default, the package will use the default queue. You can configure this in the config/webhook-server.php
.
Sending the Payload
For this post, let's send to a Webhook Consumer, which need to know any newly created user from Webhook Provider.
Let's keep it simple, in your app/Models/User.php
, add the following code snipppet:
public static function boot() { parent::boot(); static::created(function(User $model) { WebhookCall::create() ->url(url('webhook/handler')) ->payload($model->toArray()) ->throwExceptionOnFailure() ->useSecret('sign-using-this-secret') ->dispatch(); });}
What above code does, basically to call send information about the newly created user to the url('webhook/handler')
, using the secret key provided and we set to throw an exception in case sending to Webhook Consumer is failed.
That's all for sending the data to Webhook Consumer.
Handling the Payload
For the sake of demonstrate that this Webhook Provide works, we going to receive the payload in the same Laravel app.
Create new route, in routes/web.php
Route::post('webhook/handler', function(Request $request) { logger()->info([ 'payload' => $request->all(), 'headers' => $request->headers, ]);});
Then we need to disable the Verify CSRF Token:
protected $except = [ 'webhook/handler'];
Testing the Webhook
Now, let's test the webhook:
# Run in first terminalphp artisan serve# Run in second terminalphp artisan queue:work
Visit the URL http://localhost:8000
, then do the registration.
Once completed the registration, open up the storage/logs/laravel.log
. You should see something like following:
[2022-07-12 03:03:17] local.INFO: array ( 'payload' => array ( 'name' => 'Kirby Porter', 'email' => '[email protected]', 'updated_at' => '2022-07-12T02:59:03.000000Z', 'created_at' => '2022-07-12T02:59:03.000000Z', 'id' => 5, 'profile_photo_url' => 'https://ui-avatars.com/api/?name=K+P&color=7F9CF5&background=EBF4FF', ), 'headers' => Symfony\Component\HttpFoundation\HeaderBag::__set_state(array( 'headers' => array ( 'host' => array ( 0 => '127.0.0.1:8000', ), 'user-agent' => array ( 0 => 'GuzzleHttp/7', ), 'content-type' => array ( 0 => 'application/json', ), 'x-app' => array ( 0 => 'Laravel', ), 'x-version' => array ( 0 => '1', ), 'signature' => array ( 0 => '665fcd8bd35088d46d577865ad1e2aa5e6ac51c8e1ea7cdc83cc700eec0d19c2', ), 'content-length' => array ( 0 => '240', ), ), 'cacheControl' => array ( ), )),)
Congratulations! You have successfully setup the Webhook Server!
Next, we going to setup the Webhook Consumer application. Read more at Webhook: Part III.
Original Link: https://dev.to/nasrulhazim/webhook-part-ii-1b3
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To