Usage | laravel-webhook-client-rust | Spatie       

 SPATIE  

  Laravel Webhook Client Rust 
==============================

spatie.be/open-source

  [Docs](https://spatie.be/docs)  [Laravel-webhook-client-rust](https://spatie.be/docs/laravel-webhook-client-rust/v1)  Usage

 Version   v1      

 Other versions for crawler [v1](https://spatie.be/docs/laravel-webhook-client-rust/v1) 

  Usage    
- [ Introduction ](https://spatie.be/docs/laravel-webhook-client-rust/v1/introduction)
- [ Support us ](https://spatie.be/docs/laravel-webhook-client-rust/v1/support-us)
- [ Installation and setup ](https://spatie.be/docs/laravel-webhook-client-rust/v1/installation-and-setup)
- [ Usage ](https://spatie.be/docs/laravel-webhook-client-rust/v1/usage)
- [ Customizing the package ](https://spatie.be/docs/laravel-webhook-client-rust/v1/customizing-the-package)
- [ Storing attachments ](https://spatie.be/docs/laravel-webhook-client-rust/v1/attachments)
- [ Testing ](https://spatie.be/docs/laravel-webhook-client-rust/v1/testing)
- [ Changelog ](https://spatie.be/docs/laravel-webhook-client-rust/v1/changelog)

 Usage
=====

###  On this page 

1. [ Storing and processing webhooks ](#content-storing-and-processing-webhooks)
2. [ Verifying the signature of incoming webhooks ](#content-verifying-the-signature-of-incoming-webhooks)
3. [ Determining which webhook requests should be stored and processed ](#content-determining-which-webhook-requests-should-be-stored-and-processed)
4. [ Handling incoming webhook requests for multiple apps ](#content-handling-incoming-webhook-requests-for-multiple-apps)
5. [ Change route method ](#content-change-route-method)
6. [ Using the package without a controller ](#content-using-the-package-without-a-controller)
7. [ Deleting models ](#content-deleting-models)
8. [ Making outgoing HTTP calls ](#content-making-outgoing-http-calls)

Storing and processing webhooks
-----------------------------------------------------------------------------------------------------------------------------------------------------

Create your own native Laravel queue job. It receives the stored call's ID and can reload it in the worker. Job options, queue names, retries and timeouts use Laravel's `#[job]` attribute.

```
use laravel::{http::{Request, Response}, queue::{job, Queueable}};
use spatie_laravel_webhook_client::{DatabaseWebhookCallModel, Error, QueuedJob, WebhookCall, WebhookConfig, WebhookProcessor};

#[derive(Queueable)]
pub struct ProcessPayment { pub webhook_call_id: i64 }

#[job(name = "process-payment", tries = 3)]
impl ProcessPayment {
    async fn handle(self) -> laravel::Result<()> {
        let call = WebhookCall::find(self.webhook_call_id).await
            .map_err(|error| laravel::abort_with(500, error.to_string()))?;
        if let Some(call) = call {
            // Apply your payment update using call.payload.
            println!("Payment event: {}", call.payload);
        }
        Ok(())
    }
}

pub async fn receive(request: Request) -> Result<Response, Error> {
    let config = WebhookConfig::new("payments", std::env::var("PAYMENT_WEBHOOK_SECRET").unwrap_or_default());
    let processor = WebhookProcessor::new(config, DatabaseWebhookCallModel,
        QueuedJob::new(|call: WebhookCall| ProcessPayment { webhook_call_id: call.id }));
    processor.process(request).await
}

pub fn routes(route: &mut laravel::routing::Router) {
    route.post("/webhooks/payments", receive);
}
```

This example needs the configured database, migration and queue connection. The endpoint returns `{"message":"ok"}` only after storing and dispatching. The worker handles the job later. Use a durable queue connection in production and run Laravel's `queue:work` command.

Verifying the signature of incoming webhooks
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

The default validator requires a `Signature` header containing lowercase hex HMAC-SHA256 of the exact body. Missing, malformed, wrong-secret and tampered-body signatures are rejected with HTTP 400. An empty signing secret is a configuration error, not permission to accept unsigned requests.

Laravel retains the original bytes separately from parsed input. Do not reconstruct JSON to verify a signature. The processor loads input when called outside a route handler too. Multipart bodies do not retain raw bytes in Laravel; use a sender-specific validator for those endpoints, as described under [attachments](attachments).

Invalid signatures emit `InvalidWebhookSignatureEvent` through Laravel events before rejection. The event contains the request and endpoint configuration. Register listeners with `with_events`.

Determining which webhook requests should be stored and processed
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

A `WebhookProfile` runs only after authentication. Returning false acknowledges the request using your configured response, without storing it or dispatching a job. The default profile processes everything.

Handling incoming webhook requests for multiple apps
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

Give each handler its own `WebhookConfig` and processor. `WebhookConfigRepository::add_config` and `get_config` provide named lookup when endpoints come from application configuration. Names are explicit, so route-name suffixes cannot change which secret is selected.

Change route method
-----------------------------------------------------------------------------------------------------------------

Use Laravel's `route.get`, `route.put`, `route.patch`, `route.delete` or `route.on` for endpoints that require another method. Use distinct route names for endpoints sharing a handler.

Using the package without a controller
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------

Call `processor.process(request).await` inside your application scope. For retrying an existing stored call, call `processor.dispatch(&mut call).await`. Dispatch clears its previous exception. If dispatch fails, the model stores the error message and backtrace before the error is returned. Worker failures use Laravel's normal failed-job and retry handling.

Deleting models
-----------------------------------------------------------------------------------------------------

Run `WebhookCall::prune(Some(30)).await` to delete calls strictly older than 30 days. Pass `None` to disable pruning. The `webhook-client:prune` command reads `Config::delete_after_days`; schedule it through Laravel's scheduler. See [customizing the package](customizing-the-package) for alternate models.

Making outgoing HTTP calls
--------------------------------------------------------------------------------------------------------------------------------------

Webhook verification itself makes no outgoing request. If your processing job fetches more data from the sender, use Laravel's native `laravel::http::client` rather than creating a separate HTTP client.

 A good
match?
-------------

### What we do best

- All things Laravel
- Custom frontend components
- Building APIs
- AI-powered features
- Simplifying things
- Clean solutions
- Integrating services

### Not our cup of tea

- WordPress themes
- Cutting corners
- Free mockups to win a job
- "Just execute the briefing"

 In short: we'd like to be a **substantial part** of your project.

 [ Get in touch via email ](mailto:info@spatie.be?subject=A%20good%20match%21&body=Tell%20us%20as%20much%20as%20you%20can%20about%0A-%20your%20online%20project%0A-%20your%20planning%0A-%20your%20budget%0A-%20%E2%80%A6%0A%0AAnything%20that%20helps%20us%20to%20start%20straightforward%21)
