Advanced usage | laravel-stripe-webhooks-rust | Spatie       

 SPATIE  

laravel-stripe-webhooks-rust
============================

spatie.be/open-source

  [Docs](https://spatie.be/docs)  [Laravel-stripe-webhooks-rust](https://spatie.be/docs/laravel-stripe-webhooks-rust/v1)  Advanced usage

 Version   v1      

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

  Advanced usage    
- [ Introduction ](https://spatie.be/docs/laravel-stripe-webhooks-rust/v1/introduction)
- [ Support us ](https://spatie.be/docs/laravel-stripe-webhooks-rust/v1/support-us)
- [ Installation and setup ](https://spatie.be/docs/laravel-stripe-webhooks-rust/v1/installation-and-setup)
- [ Usage ](https://spatie.be/docs/laravel-stripe-webhooks-rust/v1/usage)
- [ Advanced usage ](https://spatie.be/docs/laravel-stripe-webhooks-rust/v1/advanced-usage)
- [ Testing ](https://spatie.be/docs/laravel-stripe-webhooks-rust/v1/testing)
- [ Changelog ](https://spatie.be/docs/laravel-stripe-webhooks-rust/v1/changelog)

 Advanced usage
==============

###  On this page 

1. [ Retry handling a webhook ](#content-retry-handling-a-webhook)
2. [ Performing custom logic ](#content-performing-custom-logic)
3. [ Determine if a request should be processed ](#content-determine-if-a-request-should-be-processed)
4. [ Handling multiple signing secrets ](#content-handling-multiple-signing-secrets)
5. [ Transforming the webhook payload ](#content-transforming-the-webhook-payload)
6. [ Outgoing Stripe requests ](#content-outgoing-stripe-requests)

Retry handling a webhook
--------------------------------------------------------------------------------------------------------------------------------

Inspect the stored call and its processing error before retrying. Correct the underlying problem, then dispatch processing for that stored call again. A retry must use the stored payload rather than making another unsigned HTTP request.

Inside an application scope with the configured database:

```
use spatie_laravel_stripe_webhooks::webhook_client::WebhookCall;

if let Some(mut call) = WebhookCall::find(42).await? {
    config.processor().dispatch(&mut call).await?;
}
```

This clears the previous exception before dispatch and records a new one if dispatch fails. For asynchronous queue jobs, later execution failures belong to Laravel's failed-job handling; a successful enqueue does not mean the application job completed.

Your jobs should tolerate repeated execution. Sending a successful webhook response prevents an HTTP retry; it does not guarantee a queued job ran exactly once.

Performing custom logic
-----------------------------------------------------------------------------------------------------------------------------

Replace the webhook model or processing behavior to add application-specific persistence and business logic. Keep signature validation ahead of storage and processing. Prefer queueable jobs for work that could delay the HTTP response.

The webhook-client extension points allow applications to replace the signature validator, profile, response and model. Per-event jobs remain application-owned.

- Assign an `Arc<dyn SignatureValidator>` to `config.webhook.signature_validator`.
- Assign an `Arc<dyn WebhookProfile>` to `config.webhook.webhook_profile`.
- Assign an `Arc<dyn RespondsToWebhook>` to `config.webhook.webhook_response`.
- Pass a custom `WebhookCallModel` to `WebhookProcessor::new(config.webhook_config(None)?, model, jobs)`.
- Map an application dispatcher with `.job(event_type, dispatcher)` or replace the entire processing dispatcher.

A model's associated `Call` type remains intact through storage, retries, events and jobs. Implement `StripeWebhookCall::stripe_payload()` for your call type to use `ProcessStripeWebhookJob<YourCall>`, and listen for `StripeWebhookEvent<YourCall>`. You can instead implement `ProcessWebhookJob<YourCall>` directly. If your model stores elsewhere, replace the default profile too, since it queries `webhook_calls`.

See the client's [customization guide](https://spatie.be/docs/laravel-webhook-client-rust/v1/customizing-the-package) for its trait contracts.

Determine if a request should be processed
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

Use a custom profile to decide whether a validated request should be stored and processed. For example, a profile can restrict accepted event types or apply your own duplicate policy.

A profile is not a replacement for signature validation. Authorize the sender before trusting payload fields.

```
use std::sync::Arc;
use async_trait::async_trait;
use laravel::http::Request;
use spatie_laravel_stripe_webhooks::Config;
use spatie_laravel_stripe_webhooks::webhook_client::{Error, WebhookProfile};

struct OnlyInvoices;

#[async_trait]
impl WebhookProfile for OnlyInvoices {
    async fn should_process(&self, request: &Request) -> Result<bool, Error> {
        let event: serde_json::Value = request.parse()?;
        Ok(event["type"].as_str().is_some_and(|kind| kind.starts_with("invoice.")))
    }
}

let mut config = Config::new("whsec_example");
config.webhook.webhook_profile = Arc::new(OnlyInvoices);
```

This replaces, rather than wraps, the default duplicate lookup. Add `async-trait` to your application when implementing an async client trait.

Handling multiple signing secrets
-----------------------------------------------------------------------------------------------------------------------------------------------------------

Stripe Connect can send account and connected-account events to different endpoints, each with its own signing secret. Select the configured secret using the endpoint's route, not the unverified `account` field in the payload.

An unknown endpoint key must fail rather than fall back to another endpoint's secret. Keep test-mode and live-mode endpoints separate too.

```
use spatie_laravel_stripe_webhooks::Config;

let mut config = Config::new("whsec_account");
config.signing_secrets.insert("connect".into(), "whsec_connect".into());
let connect = config.processor_for("connect")?;
```

For an explicitly routed endpoint, call `config.processor_for("connect")?.process(request).await`. Routes selecting a dynamic key must validate it against `signing_secrets`; `processor_for` already rejects unknown keys. The default route handler `stripe_webhooks` always uses the default secret.

After verification, the payload's `account` field identifies the connected account. Retain it when passing the webhook call to your job. If that job calls Stripe on the account's behalf, send the corresponding `Stripe-Account` header.

Transforming the webhook payload
--------------------------------------------------------------------------------------------------------------------------------------------------------

The stored payload contains the complete event. Deserialize `data.object` into an application-owned Rust type when typed access is useful. Stripe event payloads reflect the API version configured for the endpoint, so allow fields your application does not need to remain unmodeled.

```
use serde::Deserialize;

#[derive(Deserialize)]
struct Invoice { id: String, amount_paid: i64 }

let invoice: Invoice = serde_json::from_value(payload["data"]["object"].clone())?;
```

Outgoing Stripe requests
--------------------------------------------------------------------------------------------------------------------------------

Signature verification is local and needs no Stripe API request. If your application needs to retrieve a payment or invoice while handling an event, use Laravel Rust's `laravel::http::client` rather than introducing a separate HTTP client.

Keep API keys separate from webhook signing secrets. Use bounded timeouts, handle non-success statuses and avoid logging authorization headers. Test these calls with the framework's HTTP client fake.

This example executes against the framework fake, without calling Stripe:

```
use laravel::{http::client, time::ToSpan};
use serde_json::{Value, json};

let http = client::fake()
    .with("https://api.stripe.com/v1/invoices/in_example", json!({"id":"in_example", "paid":true}))
    .prevent_stray_requests();

let invoice: Value = client::get("https://api.stripe.com/v1/invoices/in_example")
    .token("sk_test_example")
    .header("Stripe-Account", "acct_example")
    .timeout(5.seconds())
    .ensure_successful()
    .await?
    .json()?;

assert_eq!(invoice["paid"], true);
http.assert_sent_count(1);
```

In a real job, use the verified event's connected account and your secret-store API key. Do not copy the example credentials into production.

 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)
