Skip to content
Select theme

Receive and verify webhook events

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, and the payload of every event is documented in Webhook Events. This guide covers the code that runs between the two: your handler.

Before you start, you need:

  • A webhook registration and its secret. Register your URL with POST /api/v3/webhooks as described in Manage Webhooks. 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 11 or later Laravel queues Laravel query builder
Rails Ruby on Rails 7.0 or later Active Job Active Record
Express Express 5 on Node.js 20 or later BullMQ with ioredis node-postgres
Flask Flask 2.0 or later on Python 3.10 or later Celery SQLAlchemy 2.0 or later

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 explains why the examples use one.

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 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.

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:

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.

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

Section titled “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.

routes/api.php (partial)
Route::post('/grailpay/webhooks', App\Http\Controllers\GrailPayWebhookController::class);
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);
}
}

Step 3: Acknowledge quickly and process afterward

Section titled “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.

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.

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.

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);
}
});
}
}

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.

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.

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,
};
}

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. For how transaction events map to the payment lifecycle, see Transaction States & Events.

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
    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, 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.

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.
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.
The same event is processed twice Deliveries are retried and the handler does not check event_uuid. Add the duplicate check from Step 4.
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.
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.

If you run into any issues, contact support@grailpay.com.

Maintained by EkLine