Laravel webhooks

Laravel webhooks DEFAULT

Receive webhooks in Laravel apps

Latest Version on PackagistGitHub Workflow StatusTotal Downloads

A webhook is a way for an app to provide information to another app about a specific event. The way the two apps communicate is with a simple HTTP request.

This package allows you to receive webhooks in a Laravel app. It has support for verifying signed calls, storing payloads and processing the payloads in a queued job.

If you need to send webhooks, take a look at our laravel-webhook-server package.

Support us

We invest a lot of resources into creating best in class open source packages. You can support us by buying one of our paid products.

We highly appreciate you sending us a postcard from your hometown, mentioning which of our package(s) you are using. You'll find our address on our contact page. We publish all received postcards on our virtual postcard wall.

Installation

You can install the package via composer:

composer require spatie/laravel-webhook-client

Configuring the package

You can publish the config file with:

php artisan vendor:publish --provider="Spatie\WebhookClient\WebhookClientServiceProvider" --tag="webhook-client-config"

This is the contents of the file that will be published at :

return [ 'configs' => [ [ /* * This package supports multiple webhook receiving endpoints. If you only have * one endpoint receiving webhooks, you can use 'default'. */'name' => 'default', /* * We expect that every webhook call will be signed using a secret. This secret * is used to verify that the payload has not been tampered with. */'signing_secret' => env('WEBHOOK_CLIENT_SECRET'), /* * The name of the header containing the signature. */'signature_header_name' => 'Signature', /* * This class will verify that the content of the signature header is valid. * * It should implement \Spatie\WebhookClient\SignatureValidator\SignatureValidator */'signature_validator' => \Spatie\WebhookClient\SignatureValidator\DefaultSignatureValidator::class, /* * This class determines if the webhook call should be stored and processed. */'webhook_profile' => \Spatie\WebhookClient\WebhookProfile\ProcessEverythingWebhookProfile::class, /* * This class determines the response on a valid webhook call. */'webhook_response' => \Spatie\WebhookClient\WebhookResponse\DefaultRespondsTo::class, /* * The classname of the model to be used to store call. The class should be equal * or extend Spatie\WebhookClient\Models\WebhookCall. */'webhook_model' => \Spatie\WebhookClient\Models\WebhookCall::class, /* * The class name of the job that will process the webhook request. * * This should be set to a class that extends \Spatie\WebhookClient\Jobs\ProcessWebhookJob. */'process_webhook_job' => '', ], ],

In the key of the config file, you should add a valid webhook secret. This value should be provided by the app that will send you webhooks.

This package will try to store and respond to the webhook as fast as possible. Processing the payload of the request is done via a queued job. It's recommended to not use the driver but a real queue driver. You should specify the job that will handle processing webhook requests in the of the config file. A valid job is any class that extends and has a method.

Preparing the database

By default, all webhook calls will get saved in the database.

To create the table that holds the webhook calls, you must publish the migration with:

php artisan vendor:publish --provider="Spatie\WebhookClient\WebhookClientServiceProvider" --tag="webhook-client-migrations"

After the migration has been published, you can create the table by running the migrations:

Taking care of routing

Finally, let's take care of the routing. At the app that sends webhooks, you probably configure an URL where you want your webhook requests to be sent. In the routes file of your app, you must pass that route to . Here's an example:

Route::webhooks('webhook-receiving-url');

Behind the scenes, this will register a route to a controller provided by this package. Because the app that sends webhooks to you has no way of getting a csrf-token, you must add that route to the array of the middleware:

protected$except = [ 'webhook-receiving-url', ];

Usage

With the installation out of the way, let's take a look at how this package handles webhooks. First, it will verify if the signature of the request is valid. If it is not, we'll throw an exception and fire off the event. Requests with invalid signatures will not be stored in the database.

Next, the request will be passed to a webhook profile. A webhook profile is a class that determines if a request should be stored and processed by your app. It allows you to filter out webhook requests that are of interest to your app. You can easily create your own webhook profile.

If the webhook profile determines that request should be stored and processed, we'll first store it in the table. After that, we'll pass that newly created model to a queued job. Most webhook sending apps expect you to respond very quickly. Offloading the real processing work allows for speedy responses. You can specify which job should process the webhook in the in the config file. Should an exception be thrown while queueing the job, the package will store that exception in the attribute on the model.

After the job has been dispatched, the request will be passed to a webhook response. A webhook response is a class that determines the HTTP response for the request. An 'ok' message response with status code is returned by default, but you can easily create your own webhook response.

Verifying the signature of incoming webhooks

This package assumes that an incoming webhook request has a header that can be used to verify the payload has not been tampered with. The name of the header containing the signature can be configured in the key of the config file. By default, the package uses the to validate signatures. This is how that class will compute the signature.

$computedSignature = hash_hmac('sha256', $request->getContent(), $configuredSigningSecret);

If the does match the value, the request will be passed to the webhook profile. If does not match the value in the signature header, the package will respond with a and discard the request.

Creating your own signature validator

A signature validator is any class that implements . Here's what that interface looks like.

useIlluminate\Http\Request; useSpatie\WebhookClient\WebhookConfig; interfaceSignatureValidator { publicfunctionisValid(Request$request, WebhookConfig$config): bool; }

is a data transfer object that lets you easily pull up the config (containing the header name that contains the signature and the secret) for the webhook request.

After creating your own you must register it in the in the config file.

Determining which webhook requests should be stored and processed

After the signature of an incoming webhook request is validated, the request will be passed to a webhook profile. A webhook profile is a class that determines if the request should be stored and processed. If the webhook sending app sends out request where your app isn't interested in, you can use this class to filter out such events.

By default the class is used. As its name implies, this default class will determine that all incoming requests should be stored and processed.

Creating your own webhook profile

A webhook profile is any class that implements . This is what that interface looks like:

namespaceSpatie\WebhookClient\WebhookProfile; useIlluminate\Http\Request; interfaceWebhookProfile { publicfunctionshouldProcess(Request$request): bool; }

After creating your own you must register it in the key in the config file.

Storing and processing webhooks

After the signature is validated and the webhook profile has determined that the request should be processed, the package will store and process the request.

The request will first be stored in the table. This is done using the model.

Should you want to customize the table name or anything on the storage behavior, you can let the package use an alternative model. A webhook storing model can be specified in the . Make sure you model extends .

You can change how the webhook is stored by overriding the method of . In the method you should return a saved model.

Next, the newly created model will be passed to a queued job that will process the request. Any class that extends is a valid job. Here's an example:

namespaceApp\Jobs; useSpatie\WebhookClient\Jobs\ProcessWebhookJobasSpatieProcessWebhookJob; classProcessWebhookJobextendsSpatieProcessWebhookJob { publicfunctionhandle() { // perform the work here } }

You should specify the class name of your job in the of the config file.

Creating your own webhook response

A webhook response is any class that implements . This is what that interface looks like:

namespaceSpatie\WebhookClient\WebhookResponse; useIlluminate\Http\Request; useSpatie\WebhookClient\WebhookConfig; interfaceRespondsToWebhook { publicfunctionrespondToValidWebhook(Request$request, WebhookConfig$config); }

After creating your own you must register it in the key in the config file.

Handling incoming webhook request for multiple apps

This package allows webhooks to be received from multiple different apps. Let's take a look at an example config file where we add support for two webhook URLs. All comments from the config have been removed for brevity.

return [ 'configs' => [ [ 'name' => 'webhook-sending-app-1', 'signing_secret' => 'secret-for-webhook-sending-app-1', 'signature_header_name' => 'Signature-for-app-1', 'signature_validator' => \Spatie\WebhookClient\SignatureValidator\DefaultSignatureValidator::class, 'webhook_profile' => \Spatie\WebhookClient\WebhookProfile\ProcessEverythingWebhookProfile::class, 'webhook_response' => \Spatie\WebhookClient\WebhookResponse\DefaultRespondsTo::class, 'webhook_model' => \Spatie\WebhookClient\Models\WebhookCall::class, 'process_webhook_job' => '', ], [ 'name' => 'webhook-sending-app-2', 'signing_secret' => 'secret-for-webhook-sending-app-2', 'signature_header_name' => 'Signature-for-app-2', 'signature_validator' => \Spatie\WebhookClient\SignatureValidator\DefaultSignatureValidator::class, 'webhook_profile' => \Spatie\WebhookClient\WebhookProfile\ProcessEverythingWebhookProfile::class, 'webhook_response' => \Spatie\WebhookClient\WebhookResponse\DefaultRespondsTo::class, 'webhook_model' => \Spatie\WebhookClient\Models\WebhookCall::class, 'process_webhook_job' => '', ], ], ];

When registering routes for the package, you should pass the of the config as a second parameter.

Route::webhooks('receiving-url-for-app-1', 'webhook-sending-app-1'); Route::webhooks('receiving-url-for-app-2', 'webhook-sending-app-2');

Using the package without a controller

If you don't want to use the routes and controller provided by your macro, you can programmatically add support for webhooks to your own controller.

is a class that verifies the signature, calls the web profile, stores the webhook request, and starts a queued job to process the stored webhook request. The controller provided by this package also uses that class under the hood.

It can be used like this:

$webhookConfig = new \Spatie\WebhookClient\WebhookConfig([ 'name' => 'webhook-sending-app-1', 'signing_secret' => 'secret-for-webhook-sending-app-1', 'signature_header_name' => 'Signature', 'signature_validator' => \Spatie\WebhookClient\SignatureValidator\DefaultSignatureValidator::class, 'webhook_profile' => \Spatie\WebhookClient\WebhookProfile\ProcessEverythingWebhookProfile::class, 'webhook_response' => \Spatie\WebhookClient\WebhookResponse\DefaultRespondsTo::class, 'webhook_model' => \Spatie\WebhookClient\Models\WebhookCall::class, 'process_webhook_job' => '', ]); (new \Spatie\WebhookClient\WebhookProcessor($request, $webhookConfig))->process();

Testing

Changelog

Please see CHANGELOG for more information on what has changed recently.

Contributing

Please see CONTRIBUTING for details.

Security

If you discover any security-related issues, please email [email protected] instead of using the issue tracker.

Postcardware

You're free to use this package, but if it makes it to your production environment, we highly appreciate you sending us a postcard from your hometown, mentioning which of our package(s) you are using.

Our address is: Spatie, Kruikstraat 22, 2018 Antwerp, Belgium.

We publish all received postcards on our company website.

Credits

License

The MIT License (MIT). Please see License File for more information.

Sours: https://github.com/spatie/laravel-webhook-client

Send webhooks from Laravel apps

Latest Version on PackagistGitHub Workflow StatusTotal Downloads

A webhook is a way for an app to provide information to another app about a particular event. The way the two apps communicate is with a simple HTTP request.

This package allows you to configure and send webhooks in a Laravel app easily. It has support for signing calls, retrying calls and backoff strategies.

If you need to receive and process webhooks take a look at our laravel-webhook-client package.

Support us

We invest a lot of resources into creating best in class open source packages. You can support us by buying one of our paid products.

We highly appreciate you sending us a postcard from your hometown, mentioning which of our package(s) you are using. You'll find our address on our contact page. We publish all received postcards on our virtual postcard wall.

Installation

You can install the package via composer:

composer require spatie/laravel-webhook-server

You can publish the config file with:

php artisan vendor:publish --provider="Spatie\WebhookServer\WebhookServerServiceProvider"

This is the contents of the file that will be published at :

return [ /* * The default queue that should be used to send webhook requests. */'queue' => 'default', /* * The default http verb to use. */'http_verb' => 'post', /* * This class is responsible for calculating the signature that will be added to * the headers of the webhook request. A webhook client can use the signature * to verify the request hasn't been tampered with. */'signer' => \Spatie\WebhookServer\Signer\DefaultSigner::class, /* * This is the name of the header where the signature will be added. */'signature_header_name' => 'Signature', /* * These are the headers that will be added to all webhook requests. */'headers' => [], /* * If a call to a webhook takes longer that this amount of seconds * the attempt will be considered failed. */'timeout_in_seconds' => 3, /* * The amount of times the webhook should be called before we give up. */'tries' => 3, /* * This class determines how many seconds there should be between attempts. */'backoff_strategy' => \Spatie\WebhookServer\BackoffStrategy\ExponentialBackoffStrategy::class, /* * By default we will verify that the ssl certificate of the destination * of the webhook is valid. */'verify_ssl' => true, ];

By default, the package uses queues to retry failed webhook requests. Be sure to set up a real queue other than in non-local environments.

Usage

This is the simplest way to call a webhook:

WebhookCall::create() ->url('https://other-app.com/webhooks') ->payload(['key' => 'value']) ->useSecret('sign-using-this-secret') ->dispatch();

This will send a post request to . The body of the request will be JSON encoded version of the array passed to . The request will have a header called that will contain a signature the receiving app can use to verify the payload hasn't been tampered with.

If the receiving app doesn't respond with a response code starting with , the package will retry calling the webhook after 10 seconds. If that second attempt fails, the package will attempt to call the webhook a final time after 100 seconds. Should that attempt fail, the will be raised.

Send webhook synchronously

If you would like to call the webhook immediately (synchronously), you may use the dispatchSync method. When using this method, the webhook will not be queued and will be run immediately. This can be helpfull in situation where sending the webhook is part of a bigger job that already has been queued.

WebhookCall::create() ... ->dispatchSync();

How signing requests works

When setting up, it's common to generate, store, and share a secret between your app and the app that wants to receive webhooks. Generating the secret could be done with , but it's entirely up to you. The package will use the secret to sign a webhook call.

By default, the package will add a header called that will contain a signature the receiving app can use the payload hasn't been tampered with. This is how that signature is calculated:

// payload is the array passed to the `payload` method of the webhook// secret is the string given to the `signUsingSecret` method on the webhook.$payloadJson = json_encode($payload); $signature = hash_hmac('sha256', $payloadJson, $secret);

Skip signing request

We don't recommend this, but if you don't want the web hook request to be signed call the method.

WebhookCall::create() ->doNotSign() ...

By calling this method, the header will not be set.

Customizing signing requests

If you want to customize the signing process, you can create your own custom signer. A signer is any class that implements .

This is what that interface looks like.

namespaceSpatie\WebhookServer\Signer; interfaceSigner { publicfunctionsignatureHeaderName(): string; publicfunctioncalculateSignature(array$payload, string$secret): string; }

After creating your signer, you can specify it's class name in the key of the config file. Your signer will then be used by default in all webhook calls.

You can also specify a signer for a specific webhook call:

WebhookCall::create() ->signUsing(YourCustomSigner::class) ... ->dispatch();

If you want to customize the name of the header, you don't need to use a custom signer, but you can change the value in the in the config file.

Retrying failed webhooks

When the app to which we're sending the webhook fails to send a response with a status code the package will consider the call as failed. The call will also be considered failed if the remote app doesn't respond within 3 seconds.

You can configure that default timeout in the key of the config file. Alternatively, you can override the timeout for a specific webhook like this:

WebhookCall::create() ->timeoutInSeconds(5) ... ->dispatch();

When a webhook call fails, we'll retry the call two more times. You can set the default amount of times we retry the webhook call in the key of the config file. Alternatively, you can specify the number of tries for a specific webhook like this:

WebhookCall::create() ->maximumTries(5) ... ->dispatch();

To not hammer the remote app we'll wait some time between each attempt. By default, we wait 10 seconds between the first and second attempt, 100 seconds between the third and the fourth, 1000 between the fourth and the fifth and so on. The maximum amount of seconds that we'll wait is 100 000, which is about 27 hours. This behavior is implemented in the default .

You can define your own backoff strategy by creating a class that implements . This is what that interface looks like:

namespaceSpatie\WebhookServer\BackoffStrategy; interfaceBackoffStrategy { publicfunctionwaitInSecondsAfterAttempt(int$attempt): int; }

You can make your custom strategy the default strategy by specifying it's fully qualified class name in the of the config file. Alternatively, you can specify a strategy for a specific webhook like this.

WebhookCall::create() ->useBackoffStrategy(YourBackoffStrategy::class) ... ->dispatch();

Under the hood, the retrying of the webhook calls is implemented using delayed dispatching. Amazon SQS only has support for a small maximum delay. If you're using Amazon SQS for your queues, make sure you do not configure the package in a way so there are more than 15 minutes between each attempt.

Customizing the HTTP verb

By default, all webhooks will use the method. You can customize that by specifying the HTTP verb you want in the key of the config file.

You can also override the default for a specific call by using the method.

WebhookCall::create() ->useHttpVerb('get') ... ->dispatch();

Adding extra headers

You can use extra headers by adding them to the key in the config file. If you want to add additional headers for a specific webhook, you can use the call.

WebhookCall::create() ->withHeaders([ 'Another Header' => 'Value of Another Header' ]) ... ->dispatch();

Verifying the SSL certificate of the receiving app

When using an URL that starts with the package will verify if the SSL certificate of the receiving party is valid. If it is not, we will consider the webhook call failed. We don't recommend this, but you can turn off this verification by setting the key in the config file to .

You can also disable the verification per webhook call with the method.

WebhookCall::create() ->doNotVerifySsl() ... ->dispatch();

Adding meta information

You can add extra meta information to the webhook. This meta information will not be transmitted, and it will only be used to pass to the events this package fires.

This is how you can add meta information:

WebhookCall::create() ->meta($arrayWithMetaInformation) ... ->dispatch();

Adding tags

If you're using Laravel Horizon for your queues, you'll be happy to know that we support tags.

To add tags to the underlying job that'll perform the webhook call, simply specify them in the key of the config file or use the method:

WebhookCall::create() ->withTags($tags) ... ->dispatch();

Exception handling

By default, the package will not log any exceptions that are thrown when sending a webhook.

To handle exceptions you need to create listeners for the and/or events.

Events

The package fires these events:

  • : the remote app responded with a response code.
  • : the remote app responded with a non response code, or it did not respond at all
  • : the final attempt to call the webhook failed.

All these events have these properties:

  • : the verb used to perform the request
  • : the URL to where the request was sent
  • : the used payload
  • : the headers that were sent. This array includes the signature header
  • : the array of values passed to the webhook with the call
  • : the array of tags used
  • : the attempt number
  • : the response returned by the remote app. Can be an instance of or .
  • : a unique string to identify this call. This uuid will be the same for all attempts of a webhook call.

Testing

Testing Webhooks

When using the package in automated tests, you'll want to perform one of the following to ensure that no webhooks are sent out to genuine websites

Bus

useIlluminate\Support\Facades\Bus; useSpatie\WebhookServer\CallWebhookJob; useTests\TestCase; classTestFileextendsTestCase { publicfunctiontestJobIsDispatched() { Bus::fake(); ...Perform webhook call ... Bus::assertDispatched(CallWebhookJob::class); } }

Queue

useIlluminate\Support\Facades\Queue; useSpatie\WebhookServer\CallWebhookJob; useTests\TestCase; classTestFileextendsTestCase { publicfunctiontestJobIsQueued() { Queue::fake(); ...Perform webhook call ... Queue::assertPushed(CallWebhookJob::class); } }

Changelog

Please see CHANGELOG for more information on what has changed recently.

Contributing

Please see CONTRIBUTING for details.

Security

If you discover any security-related issues, please email [email protected] instead of using the issue tracker.

Postcardware

You're free to use this package, but if it makes it to your production environment, we highly appreciate you sending us a postcard from your hometown, mentioning which of our package(s) you are using.

Our address is: Spatie, Kruikstraat 22, 2018 Antwerp, Belgium.

We publish all received postcards on our company website.

Credits

License

The MIT License (MIT). Please see License File for more information.

Sours: https://github.com/spatie/laravel-webhook-server
  1. Hoist mi5 used
  2. Maxpreps colorado basketball
  3. Champagne bucket amazon

Automated docs deploy with Laravel and Webhooks

Imagine you push to your project's repository and the documentation updates automatically on your website. Magic? No, Webhooks!

Do your homework - write docs!

If you have a lot of different products like we do, it's important to provide detailed documentation for users. It may be even more important to keep the documentation up to date - and that can become a hassle the more products you have.

That's why we implemented an automatic process to keep our documentation organized as well as up to date and centralized on our website, matching with our UI and style. You can check out all of our documentation on the website.

Every product has a docs folder in its repository which is automatically transmitted to our platform and converted to blade templates.

Communication is magic

As soon as we push some code to an app repository, for example Expose, the repository notifies our platform. The Laravel app then executes a command and the Expose documentation is automatically updated from the Expose repository right to our website. Sounds like magic, right? 🦄

The secret sauce behind all this sorcery is Webhooks. Webhooks are, simply put, a great way to communicate from server to server. We can use them to integrate payment providers, automate processes based on what's happening and much more.

How do Webhooks work?

In short, Webhooks are HTTP callbacks. Server 2 has an endpoint that can be called if something happens. Unless like with regular polling, Server 2 doesn't ask Server 1 permanently if something happened, but vice-versa: Server 1 is doing its tasks, and when something happens that is relevant for Server 2 (e.g. a payment is processed), it sends a request with payload data to the endpoint that Server 1 provides. If you want to learn more, you can check out this page of the GitHub documentation.

I made a fancy little diagram for our example to visualize what is happening between GitHub and our Laravel App: How Webhooks Work

Add a Webhook to your GitHub Repository

Adding a Webhook to your GitHub Repository is easy: Go to »Settings → Webhooks« to add a new one with the following settings: How Webhooks work

You'll have to adjust the Payload URL with for your application and change the secret. After saving this, GitHub will send a test payload to your application - this will fail for now, because we haven't done anything on the Laravel side yet. But we will change this right now!

Testing Webhooks during development

GitHub needs a Payload URL for the Webhook setup, so working with a localhost development URL would not work. But you can't deploy your code to production every time you make a little change, right? For this reason, we developed Expose – set up a free account in seconds, share your local site and receive the payload of the Webhook on your local machine. Inspect and replay the request until you are ready to deploy to production.

Handle the Webhook in Laravel

We have to set up an endpoint in our routes file like this:

GitHub is sending a post request, so we need a post route that calls the This is the entry point to our implementation and contains the method with a Request parameter:

In this case we just want to know that a push has happened in a specific repository, we don't care about the content of the data sent by GitHub – except for the repository name and the signature for the authentication. The latter ensures that the request to our Laravel application is valid. We do this by calling the method and check the signature in there – if the signature is invalid or false, it throws a or . Remember to set your GitHub webhook secret in your file and add the entry to your config ( in this case).

The method extracts the name of the repository from the request, for example We need the full qualifier to receive the documentation of the repository in the next step, which is done in the .

It can take some time to update the documentation, especially when you have a lot of files to process. Therefore we want the process to be executed in the queue and dispatch the in .

Create an artisan command

The actual processing takes place in an artisan command that is called inside the job to keep it short and clean. You can create an artisan command by calling

This makes the testing during development easier, because you don't have to fire a webhook every time.

This command handles a few things – I'll go over some helpful details instead of just pasting the whole code here, because the process will be different for each application.

Pull the documentation from the GitHub repository

There are a few steps to take for this command, so I highly recommend that you sum them up in private methods and call these from the method of the command. This keeps your code nice and tidy and gives you the possibility to log execution of every step like this:

How Webhooks work

We have registered our command with the signature and it takes the full repository qualifier ( in the screenshot above) as an argument.

For a start, the command clones the whole repository from GitHub. Why don't just use the ZIP file GitHub is providing, you ask? Depending on your configuration, it won't contain the docs folder. By cloning the repo via SSH, we make sure we get everything the repository contains.

We use the symfony/process package to execute CLI-level commands in our application. The first argument of the constructor is the command itself, the second (optional) defines the working directory where the is performed. contains the path of a temporary directory created in the constructor of the Artisan command, located in the of the app:

Please note that a package like won't work in this case - does not seem to have access to these.

Detecting the docs folder

After cloning the repository, we should check if it even has a folder!

With the handy function we can list all directories contained in a given path. It searches for the folder and returns the full path for further processing if it exists.

Moving the docs to your application

The last step is to copy the docs directory to the desired spot in your Laravel application by using the path we just detected. In our case, we duplicate the docs to . Due to more great Laravel helpers, and , this is just two more lines, so we execute this right in the method of the command:

What to do with all the markdown?

Now you have a folder in the resources of your Laravel app that is automatically updated whenever you push to your projects repository. To integrate it properly into your website, you could use a markdown parser like Parsedown and give your docs a nice layout. This step of the process is too individual to describe in a single tutorial, but you'll find a way for sure!

Sours: https://beyondco.de/blog/automated-documentation-deployment-laravel-webhooks
Laravel 8 API Tutorial - Laravel API vs Webhook - Update Stock via API / Webhook - Laravel Webhook

May 2021 · ian

Introduction

This post will be a walkthrough of how to implement HostedHooks - Webhooks as a Service platform using the PHP Laravel framework.

Before you dive into integrating the API you should go through the process to correctly setup your HostedHooks instance. This will give you the requisite ids and setup the test endpoint that you will be sending your webhook messages to.

We cover that setup in this post - How To Setup Your HostedHooks Instance

If you have already setup your instance, you can skip that and continue on with the Laravel implementation.

We will walk through how to use Laravel to construct the API calls needed to send Webhook messages to your susbcribers.

API Setup

For every HostedHooks API call you will need to pass in your API_KEY, this can be found in your settings here.

We'll reference that API key in the examples with the environment variable

Now that we have our API key we need to grab some data for the API call. In the example below we will be sending a webhook message whenever a new user has been created. I've setup this webhook event on the HostedHooks platform and labeled it as 'user.created'.

There are two ways to send webhook API calls:

  1. Send the message to the app level, which will notify all subscribers of that app that are also subscribed to the specific webhook event that was triggered (user.created in our case). This method is easy, but may not work if you need to send record specific data to your subscribers. If that is the case you should use the 2nd method.
  2. Send the message directly to an endpoint, which will notify only the subscriber of that endpoint. This method is much more direct, but requires you to map subscriberid and endpointid to your users.

We'll walk through both examples and then move on to the sample code.

Method 1: Send a Message to an App

For this API call we will be sending a POST request to the messages (app) API but will be targeting a specific app. To make this call we will need the App UUID that we want to send the message to. You can copy that UUID by heading to your dashboard, clicking on the App that you want to use and copy the UUID at the top of the page.

Hosted Hooks - copy app uuid

We will need to take that App UUID and pass it into the Messages API URL which will look like this:

If you need to send subscriber specific data inside your webhook message than this next method is likely the route you will want to take.

Method 2: Send a Message to an Endpoint

For this API call we will be sending a POST request to the messages (endpoint) API, but will be targeting a specific endpoint. To make this call we will need the Subscription UUID for the Subscriber and the respective Endpoint UUID which defines where we will send the message to. You can copy that UUIDs by heading to your dashboard, clicking on the Subscriber that you want to use and copy the UUID at the top of the page.

Hosted Hooks - copy subscription uuid

Hosted Hooks - copy endpoint uuid

We will need to take that Subscription UUID and Endpoint UUID and pass it into the Messages API URL which will look like this:

Now that we have all of the data required for the API call, let's walk through the code.

Setting Up The Code

Lastly, we will want to update the data JSON object which is being sent. You are free to put whatever you want inside that data object. We will pass everything inside onto your subscribers. For the sake of this example we will add a nested user object and add some user data.

Outside of the data object there are a few additional parts of the message payload, let's go through them here:

  • version - This is the version of the payload that you are sending (more info here)
  • event_type - This is the event that you are sending webhooks on behalf of (user.created in our case)
  • eventid - This is a unique string that HostedHooks will check to maintain idempotency. You should generate this on your end and could store this if you wanted to. We will ignore multiple requests with the same eventid

Once you've constructed your request payload, you can now make the request using whatever HTTP library you want. In our example we've used the Laravel HTTP Facade. See the example request below. Note we have provided two URIs, one for each method of sending messages. You would need to pick which one suits your usecase.

By default the header is set to , so no need to explicitly specifiy that. Also SSL certificate verification is set to by default.

The withToken() method sets the token properly in the Authorization header.

Here is the sample code to make a POST request to the HostedHooks API using Laravel.

If that request is succesful you will get back a 200 and JSON response like below.

Once that message has been submitted, it will be processed by HostedHooks and routed to the correct subscribers. If there are any deliverabiliy issues, we will retry (with exponential backoffs) for a total of 5 times and then notify you if that still fails.

You can view your deliverability stats in your Provider dashboard.

We hope this tutorial has been helpful and shows you how simple it is to get HostedHooks webhooks implemented using Laravel.

Sours: https://www.hostedhooks.com/blog/build-webhooks-using-laravel

Webhooks laravel

.

Laravel Webhooks : Use cases and implementation

.

You will also like:

.



2418 2419 2420 2421 2422