Usage | laravel-webhook-client-go | Spatie       

 SPATIE  

laravel-webhook-client-go
=========================

spatie.be/open-source

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

 Version   v1      

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

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

 Usage
=====

###  On this page 

1. [ Verifying the signature of incoming webhooks ](#content-verifying-the-signature-of-incoming-webhooks)
2. [ Determining which webhook requests should be stored and processed ](#content-determining-which-webhook-requests-should-be-stored-and-processed)
3. [ Storing and processing webhooks ](#content-storing-and-processing-webhooks)
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. [ Replaying stored calls ](#content-replaying-stored-calls)
8. [ Deleting models ](#content-deleting-models)

With the installation out of the way, let's take a look at how this package handles webhooks. First, it verifies if the signature of the request is valid. If it is not, the processor returns `ErrInvalidSignature` and fires `InvalidWebhookSignatureEvent`. Requests with invalid signatures will not be stored in the database. The package route responds with `500`, matching the PHP package. Your own controller or Laravel error renderer can choose another status.

Next, the request is passed to a webhook profile. A profile determines if a request should be stored and processed. It allows you to filter out requests that aren't of interest to your app. The default profile accepts every valid request.

If the profile accepts the request, the package first stores it in `webhook_calls`. After that, it passes the saved call to your queued job. Should dispatch return an error, the package stores its message, optional numeric code and stack in the call's `exception` field, then returns the error. With the sync queue, a processing error is also a dispatch error. Failures that happen later on a real worker belong to Laravel's failed-job handling, not this request's exception field.

After dispatch, a webhook response determines the HTTP response. By default, the package returns `{"message":"ok"}` with status `200`. The same response applies to profile-ignored requests. Errors bypass the success response.

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

The default validator expects a lowercase hexadecimal HMAC-SHA256 of the original request body in the `Signature` header. Set `SignatureHeaderName` to use another header. It compares the signature in constant time and leaves the raw body readable for later policies and storage. It does not re-encode parsed JSON.

```
mac := hmac.New(sha256.New, []byte(secret))
mac.Write(body)
signature := hex.EncodeToString(mac.Sum(nil))
```

Missing signatures are invalid. A present signature with no configured secret returns `ErrSigningSecretNotSet`. Multipart bodies are consumed by Laravel before the handler and return `ErrBodyUnavailable` with the default validator. Use the sender's documented authentication scheme in a custom validator for multipart requests.

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

Assign `WebhookProfile` to filter authenticated requests. It receives `*web.Request`, so it can parse input and query the application's database through the same context. Return false to acknowledge a request without storing or queuing it. Return an error to fail the request.

See [creating your own webhook profile](customizing-the-package#creating-your-own-webhook-profile).

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

The default `DatabaseWebhookCallModel` uses Laravel's native ORM. `WebhookCall.Payload.V` holds the parsed body input plus query values, with body fields taking precedence. Body field nesting follows Laravel Go's parser. Query values follow `net/url`: one value is a string, repeated values are a slice, and bracketed query names remain literal keys. This differs from PHP's bracketed query parsing. Use a custom model when a sender needs another payload shape.

Headers are not stored by default. Set `StoreHeaders = []string{"Signature", "X-Request-ID"}` to keep selected headers or `[]string{"*"}` to keep all. Names are case-insensitive and repeated header values remain separate. Avoid storing authorization credentials unnecessarily.

Read calls with Laravel's model API:

```
call, err := model.Query[webhookclient.WebhookCall]().
    WhereEq("name", "stripe").
    WhereEq("payload->id", "evt_123").
    First(ctx)
```

`model.Find[webhookclient.WebhookCall](ctx, id)` reads a call by ID. Custom models use their own native queries and can add fields, change tables, redact input or use another storage system.

Providers and queues can deliver the same event more than once. Use database constraints and transactions for idempotent business updates. A profile lookup alone is not an atomic deduplication mechanism.

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

Create a processor for each sender with its own `NewWebhookConfig(name, secret)` and policies. Add their endpoints to one package configuration:

```
cfg.Endpoints = []webhookclient.Endpoint{
    first.Endpoint("/receiving-url-for-app-1"),
    second.Endpoint("/receiving-url-for-app-2"),
    first.Endpoint("/another-url-for-app-1"),
}
```

The name is stored on each call. Processors with the same call type may use different storage models or jobs. They do not share mutable application state.

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

POST is the default. The PHP package's GET, QUERY, POST, PUT, PATCH and DELETE methods are supported, case-insensitively. Pass several methods to one endpoint:

```
processor.Endpoint("/receiving-url", "post", "put", "query")
```

An unsupported method fails package registration. Laravel's own router can register other methods when you use your own controller.

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

`Processor.Process` verifies the signature, calls the profile, stores the request and queues your job. Use it in your own handler:

```
response, err := processor.Process(r)
if err != nil {
    return web.Fail(err)
}
return response
```

Call `processor.Job.Register(app)` in your package's registrar, or register the concrete job with `laravel.Options.Jobs`, when you don't install a package endpoint. Register `webhookclient.Migration` if using default storage without `webhookclient.New`. Direct processors use their explicit configuration, without the package's environment fallback.

Replaying stored calls
--------------------------------------------------------------------------------------------------------------------------

Find the saved call with your model's lookup API, then pass it to the same processor:

```
if err := processor.Dispatch(ctx, &call); err != nil {
    return err
}
```

Replay clears the previous exception before enqueueing. A new dispatch failure is saved and returned. It does not revalidate a request, run the profile or create a second row. The custom model and job remain in use.

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

Accepted calls accumulate in the database. The default retention is 30 days. Set `WEBHOOK_CLIENT_DELETE_AFTER_DAYS`, override `cfg.DeleteAfterDays` in code or set it to nil to disable deletion.

Schedule `webhook-client:prune` in your application's schedule at an interval you choose:

```
s.Command("webhook-client:prune").Daily()
```

Only calls strictly older than the calendar-day cutoff are deleted. The package uses Laravel's clock, including test time travel. You may also call `webhookclient.Prune(ctx, &days)` directly. Negative days are rejected. The supplied command and helper affect only the default table. A custom storage model owns its pruning policy.

 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)
