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

 SPATIE  

laravel-stripe-webhooks-go
==========================

spatie.be/open-source

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

 Version   v1      

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

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

 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 into a Stripe object ](#content-transforming-the-webhook-payload-into-a-stripe-object)
6. [ About Cashier ](#content-about-cashier)

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

All accepted incoming webhook requests are written to the database before processing. After investigating and fixing a failure, retry processing the stored call rather than sending an unsigned HTTP request:

```
call, err := model.Find[webhookclient.WebhookCall](ctx, id)
if err != nil {
    return err
}
return stripewebhooks.Retry(ctx, &call)
```

Use an application context from a handler, job or command. `Retry` clears the previous exception and dispatches the configured first-stage processing job. That job saves missing-type, listener and dispatch failures. A successful enqueue does not mean a queued application job has completed. Later execution failures belong to Laravel's failed-job handling.

The default first-stage job serializes the complete selected call as a snapshot. Load the current stored call before retrying, as above. Your own application job can use a `queue:"model"` field to reload its native model when a worker executes it.

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

You can add logic before or after event and job dispatch by replacing `ProcessingJob`:

```
type CustomProcessing struct {
    Call webhookclient.WebhookCall `json:"call"`
}

func (j CustomProcessing) Handle(ctx context.Context) error {
    if err := beforeStripe(ctx, j.Call); err != nil {
        return err
    }
    if err := (stripewebhooks.ProcessStripeWebhookJob[webhookclient.WebhookCall]{Call: j.Call}).Handle(ctx); err != nil {
        return err
    }
    return afterStripe(ctx, j.Call)
}

// In the configuration callback:
processing := webhookclient.NewQueuedJob(func(call webhookclient.WebhookCall) CustomProcessing {
    return CustomProcessing{Call: call}
})
cfg.ProcessingJob = &processing
```

`beforeStripe` and `afterStripe` are your application functions. A fully replaced processing job owns its own exception handling. Delegating to `ProcessStripeWebhookJob.Handle` retains the standard event dispatch, mapped job dispatch and exception handling for that part of the work.

Replace storage with `NewWithModel`. A custom storage type implements `CallModel[YourCall]`:

```
type CallModel[T any] interface {
    StoreWebhook(context.Context, *web.Request, webhookclient.WebhookConfig, []webhookclient.Attachment) (T, error)
    SaveException(context.Context, *T, error) error
    Payload(T) map[string]any
    HasEvent(context.Context, string) (bool, error)
}
```

`StoreWebhook` persists and returns your own call type. `SaveException` stores or clears an error. `Payload` exposes the stored event, and `HasEvent` performs duplicate lookup in the same storage. Both default and named endpoints use that model.

```
stripewebhooks.NewWithModel(InvoiceCallModel{}, func(cfg *stripewebhooks.ModelConfig[InvoiceCall]) {
    cfg.WithoutMigration = true
    cfg.ConfigureClient = func(client *webhookclient.Config) {
        client.DeleteAfterDays = nil
    }
})
```

`InvoiceCallModel` and `InvoiceCall` are application-owned types. Register their migration in the application. Disabling default retention prevents the default pruning command from querying `webhook_calls` when you use another table. Schedule your model's own pruning policy instead.

Custom calls remain their original type in `Event[InvoiceCall]`, mapped jobs, replacement processing jobs and `Retry`. The [custom model integration test](https://github.com/spatie/laravel-stripe-webhooks-go/blob/main/webhooks_test.go) contains a complete storage implementation with a distinct table and real serialized-worker replay.

Add before-and-after processing logic with a custom processor. Keep signature validation ahead of storage and business logic.

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 use a different duplicate policy. A profile is not a replacement for signature validation.

```
duplicates := cfg.Webhook.WebhookProfile
cfg.Webhook.WebhookProfile = func(r *web.Request) (bool, error) {
    payload, err := r.Bind[map[string]any]()
    if err != nil {
        return false, err
    }
    kind, _ := payload["type"].(string)
    if !strings.HasPrefix(kind, "invoice.") {
        return false, nil
    }
    return duplicates(r)
}
```

This example wraps the selected model's default duplicate profile. Assigning an unrelated profile replaces duplicate filtering too. The default profile uses a non-empty string ID from the body, then the query only if the body lacks an ID. It checks only stored Stripe events. Its lookup and insert can race under concurrent deliveries.

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

When using [Stripe Connect](https://stripe.com/connect), you may need multiple endpoints and signing secrets. Select the secret from an explicitly configured endpoint, not an unverified `account` field in the payload. Unknown endpoint names must fail instead of falling back to the default secret.

```
stripewebhooks.New(func(cfg *stripewebhooks.Config) {
    cfg.SigningSecrets["account"] = accountSecret
    cfg.SigningSecrets["connect"] = connectSecret
})
```

This registers `/stripe-webhooks/account` and `/stripe-webhooks/connect`, in addition to the default endpoint. With a custom `Path`, that path becomes the prefix. Secret names may contain ASCII letters, numbers, hyphens and underscores. Unknown endpoint names return 404. They never fall back to the default signing secret. Load secrets from your application's secret store rather than literal strings in source.

After verification, the payload's `account` identifies the connected account. Preserve that field when passing the call to a job. Keep test-mode and live-mode endpoints separate.

Transforming the Webhook payload into a Stripe object
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

The complete event payload contains `data.object`. Decode it into an application-owned Go struct or a type from the Stripe Go SDK when typed access is useful. The package does not need a Stripe API key or an outgoing API request to validate a webhook signature.

```
type Invoice struct {
    ID string `json:"id"`
    AmountPaid int64 `json:"amount_paid"`
}

data, err := json.Marshal(call.Payload.V["data"])
if err != nil {
    return err
}
var envelope struct {
    Object Invoice `json:"object"`
}
if err := json.Unmarshal(data, &envelope); err != nil {
    return err
}
invoice := envelope.Object
```

Import `encoding/json/v2`. The Stripe endpoint's configured API version determines payload fields. Model only the fields your application needs. For outgoing API calls from a job, use Laravel's HTTP client with the job context, a timeout and successful-status checking. Keep API keys separate from webhook secrets.

About Cashier
-----------------------------------------------------------------------------------------------

The PHP package can be installed alongside Laravel Cashier. This does not establish compatibility with a Go Cashier port. No Go Cashier integration has been verified here.

 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)
