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.
Prerequisites
Section titled “Prerequisites”Before you start, you need:
- A webhook registration and its
secret. Register your URL withPOST /api/v3/webhooksas described in Manage Webhooks. If you did not store thesecret, fetch it again withGET /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.
How GrailPay delivers an event
Section titled “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 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
Section titled “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:
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.
'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.
Route::post('/grailpay/webhooks', App\Http\Controllers\GrailPayWebhookController::class);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); }}post "/grailpay/webhooks", to: "grailpay_webhooks#create"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 endendimport 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);import hashlibimport hmacimport jsonimport 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 "", 200Step 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
syncqueue driver runs the job inside the request, which delays your response. Use a driver that runs jobs on a worker. - Rails: the default
asyncadapter 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
Section titled “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:
- Record each
event_uuidyou process, in a table with a unique index on that column. - When a delivery arrives, try to record its
event_uuidbefore you act on it. - 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.
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); } }); }}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 endendimport { 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 });import os
from celery import Celeryfrom sqlalchemy import create_engine, text
celery = Celery("grailpay", broker=os.environ["CELERY_BROKER_URL"])engine = create_engine(os.environ["DATABASE_URL"])
@celery.taskdef 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)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.
Step 5: Route on the event name
Section titled “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.
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, };}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. endendasync 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; }}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. passThe 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.
Verify your endpoint
Section titled “Verify your endpoint”Test signature handling locally first, then confirm real deliveries in the sandbox.
-
Start your application and its queue worker, with
GRAILPAY_WEBHOOK_SECRETset to your sandbox registration’ssecret. -
Send a correctly signed test delivery. The command signs a sample body with your secret the same way GrailPay does. Set
WEBHOOK_URLto 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/webhooksRails http://localhost:3000/grailpay/webhooksExpress http://localhost:3000/grailpay/webhooksFlask http://localhost:5000/grailpay/webhooksSigned 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 theevent_uuid. -
Send the same delivery again. Your handler returns
200, and the job skips the event because itsevent_uuidis already recorded. -
Send the same body with a wrong signature, such as
--header 'Signature: invalid'. Your handler returns401and does not process the event. -
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. -
Fetch your registration with
GET /api/v3/webhooks/{uuid}. A healthy endpoint showsis_activeastrueandfailed_counteras0.
Troubleshooting
Section titled “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. |
| 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. |
Questions?
Section titled “Questions?”If you run into any issues, contact support@grailpay.com.
Maintained by EkLine

