# Receive and verify webhook events

import { Tabs, TabItem } from '@astrojs/starlight/components';

This guide shows you how to build an endpoint that accepts GrailPay webhook deliveries safely. You verify that each
delivery came from GrailPay, acknowledge it before GrailPay's request times out, ignore duplicate deliveries, and route
each event to the code that handles it.

Registering a URL is covered in [Manage Webhooks](/docs/technical/webhooks/manage-webhooks), and the payload of every
event is documented in [Webhook Events](/docs/technical/webhooks/events/). This guide covers the code that runs between
the two: your handler.

## Prerequisites

Before you start, you need:

- A webhook registration and its `secret`. Register your URL with `POST /api/v3/webhooks` as described in
  [Manage Webhooks](/docs/technical/webhooks/manage-webhooks#registering-a-webhook). If you did not store the `secret`,
  fetch it again with `GET /api/v3/webhooks/{uuid}`.
- An endpoint that is publicly reachable over HTTPS with a valid TLS certificate. GrailPay rejects HTTP URLs in both
  sandbox and production.
- One of the stacks the examples are written for. The same steps apply in any language.

| Example | Framework | Queue | Database access |
| --- | --- | --- | --- |
| Laravel | [Laravel](https://laravel.com/) 11 or later | Laravel queues | Laravel query builder |
| Rails | [Ruby on Rails](https://rubyonrails.org/) 7.0 or later | Active Job | Active Record |
| Express | [Express](https://expressjs.com/) 5 on Node.js 20 or later | [BullMQ](https://docs.bullmq.io/) with [ioredis](https://github.com/redis/ioredis) | [node-postgres](https://node-postgres.com/) |
| Flask | [Flask](https://flask.palletsprojects.com/) 2.0 or later on Python 3.10 or later | [Celery](https://docs.celeryq.dev/) | [SQLAlchemy](https://www.sqlalchemy.org/) 2.0 or later |

:::note
The frameworks and libraries in this guide are examples only. GrailPay does not recommend or support any third-party
library named here. Use the queue and database tools your application already has.
:::

A queue is recommended, not required. GrailPay accepts deliveries at any endpoint that verifies the signature and
returns a `2xx` response in time. [Step 3](#step-3-acknowledge-quickly-and-process-afterward) explains why the examples
use one.

## How GrailPay delivers an event

Each delivery is an HTTPS `POST` to your registered URL with a JSON body and these characteristics:

| Part | What GrailPay sends or expects |
| --- | --- |
| Body | The event as JSON: the [event envelope](/docs/technical/webhooks/events/#event-envelope) with the event-specific payload under `data`. |
| `Content-Type` header | `application/json` |
| `Signature` header | The hex-encoded HMAC-SHA256 of the request body, keyed with your registration's `secret`. |
| Your response | Any `2xx` status code acknowledges the delivery. Any other status code, a connection error, or a timeout counts as a failure. |
| Response time | GrailPay waits only a few seconds for your response before it treats the attempt as failed. |
| Retries | A failed delivery is retried at increasing intervals, starting within seconds and backing off to roughly hourly attempts. |

Every registered URL receives every event. There is no per-event subscription, so your handler decides which events to
act on.

## Step 1: Store the webhook secret

Each registration has its own `secret`, returned when you register the URL. Store it where your application reads
other credentials, such as an environment variable or a secrets manager, and never commit it to source control. The
examples in this guide read it from `GRAILPAY_WEBHOOK_SECRET`:

```bash title="Environment"
export GRAILPAY_WEBHOOK_SECRET='{YOUR_WEBHOOK_SECRET}'
```

In Laravel, map the variable in `config/services.php` so the handler can read it with `config()`. The other examples
read the variable directly.

```php title="config/services.php (partial)"
'grailpay' => [
    'webhook_secret' => env('GRAILPAY_WEBHOOK_SECRET'),
],
```

If you register more than one URL, each one has a different secret. Make sure the handler behind each URL uses the
secret for that registration, and the sandbox and production endpoints use the secrets from their own environment.

## Step 2: Verify the signature on the raw body

GrailPay computes the `Signature` header over the exact bytes it sends. Compute the same HMAC over the body **as you
received it**, before you parse it. If you parse the JSON and serialize it again, spacing, key order, and character
escaping can change, and a genuine delivery fails verification.

Compare the two values with a constant-time comparison so the check does not leak timing information, and reject any
delivery that does not match with a `401`.

<Tabs syncKey="framework">
<TabItem label="Laravel">

```php title="routes/api.php (partial)"
Route::post('/grailpay/webhooks', App\Http\Controllers\GrailPayWebhookController::class);
```

```php title="app/Http/Controllers/GrailPayWebhookController.php"
namespace App\Http\Controllers;

use App\Jobs\ProcessGrailPayEvent;
use Illuminate\Http\Request;
use Illuminate\Http\Response;

class GrailPayWebhookController extends Controller
{
    public function __invoke(Request $request): Response
    {
        $secret = config('services.grailpay.webhook_secret');
        abort_if(empty($secret), 500, 'Webhook secret is not configured');

        // getContent() returns the body exactly as GrailPay sent it.
        $rawBody = $request->getContent();
        $expected = hash_hmac('sha256', $rawBody, $secret);

        // hash_equals() compares in constant time.
        if (! hash_equals($expected, (string) $request->header('Signature'))) {
            abort(401, 'Invalid signature');
        }

        // Acknowledge first, then process on a queue (see Step 3).
        ProcessGrailPayEvent::dispatch(json_decode($rawBody, true));

        return response('', 200);
    }
}
```

</TabItem>
<TabItem label="Rails">

```ruby title="config/routes.rb (partial)"
post "/grailpay/webhooks", to: "grailpay_webhooks#create"
```

```ruby title="app/controllers/grailpay_webhooks_controller.rb"
class GrailpayWebhooksController < ActionController::API
  def create
    # raw_post returns the body exactly as GrailPay sent it.
    raw_body = request.raw_post
    secret = ENV.fetch("GRAILPAY_WEBHOOK_SECRET")
    expected = OpenSSL::HMAC.hexdigest("SHA256", secret, raw_body)
    signature = request.headers["Signature"].to_s

    # secure_compare compares in constant time.
    unless ActiveSupport::SecurityUtils.secure_compare(expected, signature)
      return head :unauthorized
    end

    # Acknowledge first, then process on a queue (see Step 3).
    ProcessGrailpayEventJob.perform_later(JSON.parse(raw_body))
    head :ok
  end
end
```

</TabItem>
<TabItem label="Express">

```javascript title="server.mjs"
import crypto from 'node:crypto';
import express from 'express';
import { Queue } from 'bullmq';
import IORedis from 'ioredis';

const secret = process.env.GRAILPAY_WEBHOOK_SECRET;
if (!secret) {
  throw new Error('GRAILPAY_WEBHOOK_SECRET is not set');
}

const app = express();
const connection = new IORedis({ host: '127.0.0.1', port: 6379 });
const events = new Queue('grailpay-events', { connection });

function isValidSignature(rawBody, signature) {
  const expected = Buffer.from(crypto.createHmac('sha256', secret).update(rawBody).digest('hex'));
  const received = Buffer.from(signature ?? '');

  // timingSafeEqual() compares in constant time, and needs equal lengths.
  return expected.length === received.length && crypto.timingSafeEqual(expected, received);
}

// express.raw() keeps the body as a Buffer, exactly as GrailPay sent it.
app.post('/grailpay/webhooks', express.raw({ type: 'application/json' }), async (req, res) => {
  if (!Buffer.isBuffer(req.body) || !isValidSignature(req.body, req.get('Signature'))) {
    return res.status(401).send('Invalid signature');
  }

  // Acknowledge first, then process on a queue (see Step 3).
  await events.add('event', JSON.parse(req.body.toString('utf8')));
  res.sendStatus(200);
});

app.listen(3000);
```

</TabItem>
<TabItem label="Flask">

```python title="app.py"
import hashlib
import hmac
import json
import os

from flask import Flask, abort, request

from tasks import process_event

app = Flask(__name__)
SECRET = os.environ["GRAILPAY_WEBHOOK_SECRET"].encode()


@app.post("/grailpay/webhooks")
def grailpay_webhook():
    # get_data() returns the body exactly as GrailPay sent it.
    raw_body = request.get_data()
    expected = hmac.new(SECRET, raw_body, hashlib.sha256).hexdigest()
    signature = request.headers.get("Signature", "")

    # compare_digest() compares in constant time.
    if not hmac.compare_digest(expected.encode(), signature.encode()):
        abort(401)

    # Acknowledge first, then process on a queue (see Step 3).
    process_event.delay(json.loads(raw_body))
    return "", 200
```

</TabItem>
</Tabs>

:::caution
Make sure nothing rejects or rewrites the request before your handler reads it:

- **Laravel and Rails:** a webhook delivery carries no CSRF token, so a route with CSRF protection rejects it. In
  Laravel, routes in `routes/api.php` are not CSRF-protected, and are served under the `/api` prefix. In Rails, inherit
  from `ActionController::API` as in the example, or call `skip_forgery_protection` in a controller that inherits from
  `ActionController::Base`.
- **Express:** a JSON parser mounted for every route, such as `express.json()` with `app.use()`, replaces the raw body
  before your handler runs. Mount `express.raw()` on the webhook route, as in the example, ahead of any global parser.
:::

## Step 3: Acknowledge quickly and process afterward

Return a `2xx` response as soon as the signature checks out, then do the work. GrailPay waits only a few seconds for
your response. If your handler calls other services or writes to several tables before it responds, the attempt can time
out and GrailPay delivers the same event again later.

:::note[A queue is recommended, not required]
You can process an event inside the request, as long as you still respond within a few seconds. A queue is what keeps
that true under load. Events do not arrive at a steady rate: when an
[ACH processing window](/docs/resources/ach-processing-windows) settles, many transactions and payouts change state
at once, and each change sends an event to your endpoint. With a queue, your endpoint acknowledges every delivery
straight away and works through the burst at its own pace. Without one, a burst can slow your handler until deliveries
time out and are retried, which adds to the load.
:::

The examples hand the verified event to a queued job and respond immediately. Back the queue with a durable store in
production, so an event is not lost if your process restarts after it has acknowledged the delivery:

- **Laravel:** the `sync` queue driver runs the job inside the request, which delays your response. Use a driver that
  runs jobs on a worker.
- **Rails:** the default `async` adapter keeps jobs in memory, which loses them on a restart. Configure a persistent
  adapter.
- **Express:** BullMQ stores jobs in Redis. The example connects to a local Redis server.
- **Flask:** Celery sends jobs to the broker named in `CELERY_BROKER_URL`.

## Step 4: Ignore duplicate deliveries

GrailPay can deliver the same event more than once, for example when your `2xx` response does not arrive in time. Every
delivery of the same event carries the same `event_uuid`, so use it as an idempotency key:

1. Record each `event_uuid` you process, in a table with a unique index on that column.
2. When a delivery arrives, try to record its `event_uuid` before you act on it.
3. If it is already recorded, skip the processing.

The examples assume a `processed_webhook_events` table with a unique index on `event_uuid`. The Express and Flask
examples use PostgreSQL syntax and read the database location from `DATABASE_URL`. The `route` function they all call
is added in [Step 5](#step-5-route-on-the-event-name).

<Tabs syncKey="framework">
<TabItem label="Laravel">

```php title="app/Jobs/ProcessGrailPayEvent.php"
namespace App\Jobs;

use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Support\Facades\DB;

class ProcessGrailPayEvent implements ShouldQueue
{
    use Queueable;

    public function __construct(public array $event) {}

    public function handle(): void
    {
        DB::transaction(function () {
            // insertOrIgnore() returns 0 when the event_uuid is already recorded.
            $inserted = DB::table('processed_webhook_events')->insertOrIgnore([
                'event_uuid' => $this->event['event_uuid'],
            ]);

            if ($inserted) {
                $this->route($this->event);
            }
        });
    }
}
```

</TabItem>
<TabItem label="Rails">

```ruby title="app/jobs/process_grailpay_event_job.rb"
class ProcessGrailpayEventJob < ApplicationJob
  def perform(event)
    ProcessedWebhookEvent.transaction do
      record = ProcessedWebhookEvent.create_or_find_by!(event_uuid: event["event_uuid"])

      # previously_new_record? is false when the event_uuid was already recorded.
      route(event) if record.previously_new_record?
    end
  end
end
```

</TabItem>
<TabItem label="Express">

```javascript title="worker.mjs"
import { Worker } from 'bullmq';
import IORedis from 'ioredis';
import pg from 'pg';

const pool = new pg.Pool({ connectionString: process.env.DATABASE_URL });
// BullMQ workers need maxRetriesPerRequest set to null.
const connection = new IORedis({ host: '127.0.0.1', port: 6379, maxRetriesPerRequest: null });

async function processEvent(job) {
  const event = job.data;
  const client = await pool.connect();

  try {
    await client.query('BEGIN');

    // rowCount is 0 when the event_uuid is already recorded.
    const { rowCount } = await client.query(
      'INSERT INTO processed_webhook_events (event_uuid) VALUES ($1) ON CONFLICT DO NOTHING',
      [event.event_uuid],
    );

    if (rowCount === 1) {
      await route(event, client);
    }

    await client.query('COMMIT');
  } catch (error) {
    await client.query('ROLLBACK');
    throw error;
  } finally {
    client.release();
  }
}

new Worker('grailpay-events', processEvent, { connection });
```

</TabItem>
<TabItem label="Flask">

```python title="tasks.py"
import os

from celery import Celery
from sqlalchemy import create_engine, text

celery = Celery("grailpay", broker=os.environ["CELERY_BROKER_URL"])
engine = create_engine(os.environ["DATABASE_URL"])


@celery.task
def process_event(event):
    # engine.begin() commits on success and rolls back on an exception.
    with engine.begin() as connection:
        # rowcount is 0 when the event_uuid is already recorded.
        result = connection.execute(
            text(
                "INSERT INTO processed_webhook_events (event_uuid) "
                "VALUES (:event_uuid) ON CONFLICT DO NOTHING"
            ),
            {"event_uuid": event["event_uuid"]},
        )

        if result.rowcount == 1:
            route(event, connection)
```

</TabItem>
</Tabs>

Every example records the key in the same database transaction as the work it guards, so a failure cannot leave one
recorded without the other.

:::note
The `event_uuid` identifies one event sent to one registration. If you register more than one URL, each URL receives its
own copy of the event with a different `event_uuid`. When several URLs feed the same system, de-duplicate on the entity
in `data` and its status as well.
:::

## Step 5: Route on the event name

Every event uses the same envelope, and the `event` field names it in `group.action` form, such as
`transaction.completed` or `compliance_status.approved`. Route on that field, and acknowledge events your integration
does not handle like any other delivery. Returning an error for an event you do not need makes GrailPay retry it.

<Tabs syncKey="framework">
<TabItem label="Laravel">

```php title="app/Jobs/ProcessGrailPayEvent.php (partial)"
private function route(array $event): void
{
    match ($event['event']) {
        // The merchant or person passed verification.
        'compliance_status.approved' => $this->markApproved($event['data']['compliance_status']),
        'transaction.completed' => $this->markPaymentSettled($event['data']['transaction']),
        // The ACH return code is in $event['data']['transaction']['ach_return_code'].
        'transaction.failed' => $this->markPaymentFailed($event['data']['transaction']),
        // An event this integration does not use. Ignore it.
        default => null,
    };
}
```

</TabItem>
<TabItem label="Rails">

```ruby title="app/jobs/process_grailpay_event_job.rb (partial)"
def route(event)
  case event["event"]
  when "compliance_status.approved"
    # The merchant or person passed verification.
    mark_approved(event["data"]["compliance_status"])
  when "transaction.completed"
    mark_payment_settled(event["data"]["transaction"])
  when "transaction.failed"
    # The ACH return code is in event["data"]["transaction"]["ach_return_code"].
    mark_payment_failed(event["data"]["transaction"])
  else
    # An event this integration does not use. Ignore it.
  end
end
```

</TabItem>
<TabItem label="Express">

```javascript title="worker.mjs (partial)"
async function route(event, client) {
  switch (event.event) {
    case 'compliance_status.approved':
      // The merchant or person passed verification.
      return markApproved(event.data.compliance_status, client);
    case 'transaction.completed':
      return markPaymentSettled(event.data.transaction, client);
    case 'transaction.failed':
      // The ACH return code is in event.data.transaction.ach_return_code.
      return markPaymentFailed(event.data.transaction, client);
    default:
      // An event this integration does not use. Ignore it.
      return;
  }
}
```

</TabItem>
<TabItem label="Flask">

```python title="tasks.py (partial)"
def route(event, connection):
    match event["event"]:
        case "compliance_status.approved":
            # The merchant or person passed verification.
            mark_approved(event["data"]["compliance_status"], connection)
        case "transaction.completed":
            mark_payment_settled(event["data"]["transaction"], connection)
        case "transaction.failed":
            # The ACH return code is in event["data"]["transaction"]["ach_return_code"].
            mark_payment_failed(event["data"]["transaction"], connection)
        case _:
            # An event this integration does not use. Ignore it.
            pass
```

</TabItem>
</Tabs>

The functions each branch calls, such as `markPaymentSettled` and `mark_payment_settled`, stand in for your own code.

Two points help your routing hold up over time:

- **Do not assume delivery order.** Retries and processing delays mean a later event can arrive before an earlier one.
  Treat an event as a signal that something changed, not as the latest state. Before you overwrite a status, fetch the
  current state from the API, for example with `GET /api/v3/transactions/{uuid}`.
- **Expect new events.** Because every registration receives every event, new event names reach your endpoint as
  GrailPay adds them. A default branch that ignores unknown events keeps them from failing.

For the events in each group and their payloads, see [Webhook Events](/docs/technical/webhooks/events/#available-events).
For how transaction events map to the payment lifecycle, see
[Transaction States & Events](/docs/resources/transaction-states).

## Verify your endpoint

Test signature handling locally first, then confirm real deliveries in the sandbox.

1. Start your application and its queue worker, with `GRAILPAY_WEBHOOK_SECRET` set to your sandbox registration's
   `secret`.
2. Send a correctly signed test delivery. The command signs a sample body with your secret the same way GrailPay does.
   Set `WEBHOOK_URL` to your local handler first. With each framework's development server and the routes in this
   guide, that is:

   | Example | Local URL |
   | --- | --- |
   | Laravel | `http://localhost:8000/api/grailpay/webhooks` |
   | Rails | `http://localhost:3000/grailpay/webhooks` |
   | Express | `http://localhost:3000/grailpay/webhooks` |
   | Flask | `http://localhost:5000/grailpay/webhooks` |

   ```bash title="Signed test delivery"
   WEBHOOK_URL='http://localhost:8000/api/grailpay/webhooks'
   BODY='{"event":"transaction.created","event_uuid":"019d072d-1203-7695-842b-a15567fbb0d8","event_occurred_at":"2026-04-05 14:28:33","event_version":3,"vendor_uuid":"019e2711-5a92-735d-a7d5-669aec76b54f","data":{}}'
   SIGNATURE=$(printf '%s' "$BODY" | openssl dgst -sha256 -hmac "$GRAILPAY_WEBHOOK_SECRET" | awk '{print $NF}')

   curl -i "$WEBHOOK_URL" \
   --header 'Content-Type: application/json' \
   --header "Signature: $SIGNATURE" \
   --data "$BODY"
   ```

   Your handler returns `200`, and the job records the `event_uuid`.
3. Send the same delivery again. Your handler returns `200`, and the job skips the event because its `event_uuid` is
   already recorded.
4. Send the same body with a wrong signature, such as `--header 'Signature: invalid'`. Your handler returns `401` and
   does not process the event.
5. Deploy the handler to the HTTPS URL you registered in the sandbox, then perform an action that emits an event, such
   as [onboarding a person](/docs/technical/users/onboard-a-person), which emits `person.created`. Some events are
   delivered after a short delay, so allow a minute for the delivery to arrive.
6. Fetch your registration with `GET /api/v3/webhooks/{uuid}`. A healthy endpoint shows `is_active` as `true` and
   `failed_counter` as `0`.

## Troubleshooting

| Symptom | Likely cause | Fix |
| --- | --- | --- |
| Every delivery fails verification | The handler hashed a body it parsed and serialized again, not the bytes it received. | Hash the raw body, as shown in [Step 2](#step-2-verify-the-signature-on-the-raw-body). |
| Every delivery fails verification after a deploy | The handler uses the secret from another registration or another environment. | Fetch the registration with `GET /api/v3/webhooks/{uuid}` and compare its `secret` with the one your handler loads. |
| Deliveries fail with `419` or `422` before your handler runs | CSRF protection rejects the request. Laravel answers `419` and Rails answers `422`. | Exempt the webhook route from CSRF protection, as described in [Step 2](#step-2-verify-the-signature-on-the-raw-body). |
| The same event is processed twice | Deliveries are retried and the handler does not check `event_uuid`. | Add the duplicate check from [Step 4](#step-4-ignore-duplicate-deliveries). |
| `failed_counter` keeps rising | Your endpoint returns a non-`2xx` status, responds too slowly, or is unreachable. | Check your server logs for the failing status code, and move slow work after the response as in [Step 3](#step-3-acknowledge-quickly-and-process-afterward). |
| Deliveries stopped and `is_active` is `false` | `failed_counter` counts consecutive events whose every delivery attempt failed, and at 30 GrailPay deactivates the registration. A successful delivery resets the counter to `0`. | Fix the endpoint, then delete the registration with `DELETE /api/v3/webhooks/{uuid}` and register the URL again. The new registration has a new `secret`, so update your handler. |
| No deliveries arrive at all | The URL is not HTTPS, the certificate is invalid, or the endpoint is not publicly reachable. | Confirm the URL loads over HTTPS from outside your network with a valid certificate, and that it matches the `url` on the registration. |

## Questions?

If you run into any issues, contact [support@grailpay.com](mailto:support@grailpay.com).