Webhooks
A webhook endpoint lets your backend act when something happens in Flint: an order is paid, a refund settles, a subscription renews. Flint sends a signed HTTPS POST to a URL you register and keeps retrying until your server answers with a 2xx. Use the webhook, not the buyer's browser redirect, to trigger fulfillment and other side effects, because a buyer can close the tab before your success page loads.
A production handler:
- verifies every delivery with Flint's public keys, with no shared secret to store
- records each event once, even though Flint can deliver it more than once
- answers within 10 seconds and does the real work in a background job
- reads current state from the API instead of trusting arrival order
New endpoints sign deliveries with a JWT you verify against Flint's public JWKS. If you'd rather verify a shared secret in the Standard Webhooks format, opt into HMAC and follow Verify an HMAC delivery instead of Step 4.
How delivery works#
- Flint sends POST the event, signed for attempt 1 to Your endpoint
- Your endpoint returns 500, or no answer within 10 seconds to Flint
- Flint sends retry: same webhook_event_id, new signature to Your endpoint
- Your endpoint sends verify, store the event ID, enqueue a job to Your endpoint
- Your endpoint returns 200 to Flint
- Your endpoint sends the job to Your worker
- Your worker sends GET the resource to Flint
- Flint returns its current state to Your worker
- Success is any
2xxwithin 10 seconds. A different status, a redirect, a timeout, or a connection failure is a failed attempt. Flint never follows redirects. - Failed deliveries retry. Up to 9 attempts in total, the last one at least 71 hours after the first. Each attempt is signed again with a fresh timestamp.
- Delivery is at least once. The same event can arrive more than once, always with the same
webhook_event_id. - Order isn't guaranteed. Each event and each retry is delivered independently, so a newer event can arrive before an older one.
Webhook delivery is the full contract: every header and envelope field, the retry schedule, and retention.
What you need#
- A test API key (
flint_test_...) from the dashboard's API keys page, or one minted through the API setup flow. - A web server you can add a route to. The examples use Node with Express, Flask, and Go's standard library. JWT verification examples cover the Flint Node and PHP SDKs, plus Node, Python, and Go without a Flint SDK.
- For local development, a tunnel such as ngrok or cloudflared. Flint delivers only to HTTPS URLs that resolve to a public address. Sandbox endpoints may point at a host that isn't live yet; live endpoints must resolve when you register or change them. HTTPS,
localhost, and private IP checks still apply in sandboxes, and Flint checks DNS before every delivery.
The event envelope#
Every merchant delivery has the same JSON envelope. Only data.object changes with the event type.
{
"webhook_event_id": "whev_1kmn0aExample",
"event_type": "order.paid",
"event_source": "merchant",
"payload_version": 2,
"api_version": "2026-09-07",
"mode": "test",
"sandbox_id": "test_1kmn0aExample",
"merchant_id": "mer_1kmn0aExample",
"created_at": "2026-07-03T14:53:30Z",
"test": false,
"request": {
"id": "req_01KWM6CHDJB2VSB573FNFWX0PN",
"idempotency_key": "checkout-confirm-1kmn0a-001"
},
"data": {
"object": {
"order_id": "ord_1kmn0aExample",
"status": "open",
"payment_status": "paid",
"pricing_amounts": {
"total_money": {"amount": 2500, "currency": "USD"}
},
"payment_intent_ids": ["pi_1kmn0aExample"]
}
}
}
A handler needs three fields:
webhook_event_idis your deduplication key. It's the same on every retry and resend of the event, and it's also sent as thewebhook-idheader.event_typesays what happened, as<resource_type>.<event>. Route on it. Every type is in the event catalog.data.objectis the resource the event is about, as itsGETreturns it, minus the few caller-specific fields the catalog lists under Fields webhooks leave out. The part ofevent_typebefore the dot names the resource:order.paidcarries an order.
Every envelope has a required top-level event_source: merchant for merchant endpoints, partner_app for your app's own lifecycle events, or installed_merchants for resource events from merchants that installed your app. Use it to distinguish the envelope shapes.
mode is test or live. test is true only on synthetic events from the test-events endpoint; real sandbox events carry "mode": "test" and "test": false. request names the API request that caused the event, or is null when none did. Event body describes every field, including the partner app envelope.
New event types and new resource fields ship over time. Ignore fields you don't recognize, and answer 2xx to event types you don't handle so Flint doesn't retry them.
Step 1: write a minimal handler#
Start with a route that keeps the raw request body and answers quickly. Verification in Step 4 needs the exact bytes Flint sent.
import express from "express";
const app = express();
// Raw body on this route only: verification needs the exact bytes.
app.post("/webhooks/flint", express.raw({ type: "application/json" }), (req, res) => {
console.log("received", req.headers["webhook-id"]);
res.sendStatus(200);
});
app.listen(3000);
from flask import Flask, request
app = Flask(__name__)
@app.post("/webhooks/flint")
def flint_webhook():
raw_body = request.get_data() # exact bytes, before any JSON parsing
print("received", request.headers.get("webhook-id"), len(raw_body), "bytes")
return "", 200
package main
import (
"io"
"log"
"net/http"
)
func main() {
http.HandleFunc("/webhooks/flint", func(w http.ResponseWriter, r *http.Request) {
rawBody, err := io.ReadAll(r.Body) // exact bytes, needed for verification
if err != nil {
w.WriteHeader(http.StatusBadRequest)
return
}
log.Println("received", r.Header.Get("webhook-id"), len(rawBody), "bytes")
w.WriteHeader(http.StatusOK)
})
log.Fatal(http.ListenAndServe(":3000", nil))
}
Warning: Keep the raw body
Global body-parsing middleware, such as express.json(), parses the body before your route runs, and re-serialized JSON never matches the signed bytes. Register a raw-body parser on the webhook route only. If your framework applies CSRF protection or session authentication to every POST, exempt this route: Flint can't send your CSRF token or cookies.
Step 2: expose it over public HTTPS#
In production, the endpoint is a route on your own domain. In development, put a tunnel in front of your local server and register the tunnel's URL.
ngrok http 3000
Copy the https:// forwarding URL it prints and append your route, such as /webhooks/flint.
cloudflared tunnel --url http://localhost:3000
Copy the https:// URL it prints and append your route, such as /webhooks/flint.
Free tunnel URLs change when the tunnel restarts. Update the registered endpoint's url with PATCH /v1/webhook-endpoints/{webhook_endpoint_id} instead of registering a new endpoint each time.
The Flint CLI can also forward sandbox events without a tunnel: flint listen --forward-to http://localhost:3000/webhooks/flint. Flint signs each forwarded request as a JWT, as it does in production. With a full-access sandbox API key, the CLI creates a sandbox endpoint for the listener on first use and prints its whep_... ID; set it as FLINT_WEBHOOK_ENDPOINT_ID and verify with the code from Step 4. Forward webhooks to localhost covers the listener endpoint. With a restricted credential, register a sandbox endpoint with event types it can read and pass its ID with --webhook-endpoint-id, or prepare a signed sandbox delivery for it.
Prepare a signed sandbox delivery#
To exercise your receiver's JWT verifier on localhost, request the exact delivery bytes and headers for one of your sandbox webhook endpoints:
curl https://api.withflintpay.com/v1/webhook-endpoints/whep_YOUR_ENDPOINT/sign-delivery \
-H "Authorization: Bearer $FLINT_SANDBOX_API_KEY" \
-H 'Content-Type: application/json' \
-d '{"webhook_event_id":"whev_YOUR_EVENT"}'
The endpoint and event must belong to your merchant and the same sandbox. The endpoint must be active, subscribe to the event type, and enable jwt in signing_methods. Your credential needs webhooks.write and permission to read the resource in the event. Live-mode credentials are refused. Global partner endpoints and delivery rate callbacks aren't supported.
The response's data contains webhook_endpoint_id, webhook_event_id, body, headers, and expires_at. body is a string containing the exact JSON delivery bytes, rendered at the endpoint's API version. Send those bytes to your local receiver with the returned headers. Do not parse and reserialize body: verification binds the JWT to its exact bytes. Headers include Authorization, Flint-Webhook-Endpoint-Id, webhook-id, and webhook-timestamp, plus webhook-signature when the endpoint also enables HMAC. Keep the issuer, public JWKS, and endpoint audience checks from Step 4 unchanged.
This request prepares a delivery without sending it or creating a delivery or attempt record. Each request rechecks access and issues a fresh JWT that expires after 300 seconds. Repeating a request can produce another valid JWT for the same event; deduplicate by webhook-id. A token already issued remains valid until expiry even if the endpoint changes. After expiry, request a new signed delivery while the event payload is retained.
Each endpoint can sign one delivery every 200 ms and 10,000 per UTC day, shared across your credentials. Signing requests have their own API limits. Flint can wait up to 200 ms for the next signing slot. If another request takes that slot, Flint returns 429 RATE_LIMIT_EXCEEDED with Retry-After-Ms for the remaining delay and a whole-second Retry-After fallback. The daily quota returns 409 LIMIT_REACHED with reason webhook_listener_signatures_daily, limit: 10000, and resets_at at the next UTC midnight. It sends no Retry-After. Signing returns 503 SERVICE_UNAVAILABLE if its shared quota or signing service is unavailable. Responses use Cache-Control: no-store. Keep the returned body and headers out of logs and saved fixtures containing private data.
Step 3: register the endpoint#
Register the URL and the events it should receive. Use your tunnel URL while developing.
curl -X POST https://api.withflintpay.com/v1/webhook-endpoints \
-H "Content-Type: application/json" \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Idempotency-Key: webhook-endpoint-001" \
-d '{
"url": "https://example.com/webhooks/flint",
"enabled_events": [
"order.paid",
"refund.succeeded",
"refund.partially_succeeded",
"refund.failed"
],
"description": "Fulfillment and refund sync"
}'
{
"data": {
"webhook_endpoint_id": "whep_1kmn0aExample",
"url": "https://example.com/webhooks/flint",
"signing_methods": ["jwt"],
"enabled_events": [
"order.paid",
"refund.succeeded",
"refund.partially_succeeded",
"refund.failed"
],
"description": "Fulfillment and refund sync",
"api_version": "2026-09-07",
"event_sources": ["merchant"],
"status": "active",
"version": 1,
"created_at": "2026-07-03T14:53:12Z",
"updated_at": "2026-07-03T14:53:12Z"
}
}
Save webhook_endpoint_id. It's the audience your verifier expects in Step 4, and it stays the same when you change the URL.
A merchant endpoint belongs to the environment of the key that created it and receives only that environment's events. A sandbox key creates a sandbox endpoint; register your production endpoint with a live key, as Going live describes. New endpoints are active. Send "status": "inactive" to create one that receives nothing until you activate it.
Partner-source endpoints#
Endpoints with event_sources containing partner_app or installed_merchants are global configuration for the app named by partner_app_id. Create and manage them with the app owner's live-mode credential and webhooks.write, or an authorized Dashboard session. This also applies when installed_merchant_modes is only ["test"].
A test-mode credential gets 403 FORBIDDEN with reason live_mode_required when it tries to create, change, or delete a partner-source endpoint, rotate its secret, send a test event, resend a delivery, or create a delivery from an event. Reusing an Idempotency-Key doesn't bypass this check.
Sandbox reads omit these endpoints, their events, and their deliveries. Filtering a list to partner sources returns an empty collection; reading one of these records by ID, or using its ID as a list filter, returns 404 RESOURCE_NOT_FOUND. Use live context to read or manage the configuration. Merchant sandbox endpoints keep their own environment and work with sandbox credentials. Receive partner webhooks shows both partner sources and their event filters.
Choose which events to receive#
enabled_events is required and can't be empty. List the event types your handler acts on, and add more later with a PATCH. ["*"] subscribes to every event type, including types added later. It's handy while exploring, but your handler then receives events it doesn't need. * must be the only entry, and other patterns such as order.* aren't supported.
A restricted API key needs webhooks.write and permission to read the resource in each subscribed event. For example, customer.created requires customers.read or customers.write. The same rules apply when you change subscriptions, redirect deliveries, or activate an endpoint. A wildcard requires permission to read every event resource. If a scope is missing, Flint returns 403 INSUFFICIENT_SCOPE and names the event and the required scope.
Use current event names. A name from an event's previous_names returns 400 INVALID_REQUEST, and Previous names explains how stored subscriptions map across renames. GET /v1/webhook-event-types lists all 305 current types with their resource_type, kind, previous_names, and the event_sources that can receive each, 100 per page; follow next_page_token until a response arrives without one.
Several events fire around one successful payment. Pick one as your fulfillment trigger, so a single payment can't fulfill twice:
Choosing the right event maps refunds, disputes, invoices, payouts, and other jobs to their events. For account verification, merchant.readiness_updated is a prompt to read GET /v1/merchant, not a record of the change; After the owner exits covers the polling it speeds up. Sandbox accounts send it too, so you can rehearse that loop before going live.
Choose a signing method#
signing_methods defaults to ["jwt"].
signing_methods | What each delivery carries | What you store |
|---|---|---|
["jwt"] (default) | Authorization: Bearer <JWT>, signed by Flint's private key | Your endpoint ID. No secret is issued, stored, or returned. |
["hmac"] | A Standard Webhooks webhook-signature header | The whsec_... secret, returned once in the create response |
["jwt", "hmac"] | Both | Both. Use this while you migrate an endpoint. |
Only a create request that includes hmac returns secret; store it in your secret manager right away, because no later read returns it. With jwt enabled, the URL can't contain a username or password.
Choose an API version#
api_version controls the shape of data.object. Omit it on create to pin the API version that request is served at: its Flint-Version header, or your merchant's default version when the header is absent. Send "default" explicitly to follow the merchant default at each attempt, or send a supported date, such as "2026-09-07", to pin a different version. Later API requests and changes to the merchant default don't move a dated endpoint pin. A delivery never uses a version newer than the one its event was recorded at. Upgrade with two endpoints covers moving a handler to a new version safely.
Step 4: verify the signature#
Anyone who finds your endpoint URL can send it requests, so verify every delivery before you act on it. A JWT delivery carries these headers:
Authorization: Bearer <Flint-signed JWT>
Flint-Webhook-Endpoint-Id: whep_1kmn0aExample
webhook-id: whev_1kmn0aExample
webhook-timestamp: 1783090410
The JWT is signed with ES256, has typ flint-webhook+jwt, and names its signing key in kid. Flint publishes the public keys at https://api.withflintpay.com/.well-known/jwks.json. Its claims are:
| Claim | Value |
|---|---|
iss | https://api.withflintpay.com, for live and test mode alike |
aud | Your webhook_endpoint_id |
iat | When this attempt was signed, in Unix seconds. Also sent as webhook-timestamp. |
exp | iat + 300: a token is valid for five minutes |
jti | This attempt's ID (watt_...), different on every retry |
body_sha256 | SHA-256 of the raw request body, base64url encoded without padding |
Set the endpoint IDs to the ones you registered, never to a value taken from the request. The issuer and JWKS URL are fixed configuration; never fetch a key URL named in a token. The Flint Node and PHP SDKs verify the token for you; without a Flint SDK, choose the example for your language below.
With @flintpay/node, pass the raw body, the request headers, and your endpoint IDs. A delivery that fails any check throws an SdkError:
const { event, known } = await flint.verifyWebhookAsync(rawBody, headers, {
endpointIds: ["whep_1kmn0aExample"],
});
With a bearer token and endpointIds, the SDK verifies the JWT and never falls back to HMAC. The synchronous verifyWebhook checks HMAC only.
With flintpay/flint, pass the raw body, the request headers, and your endpoint IDs. A delivery that fails any check throws an SdkError:
$verified = $flint->verifyWebhookDelivery(
file_get_contents('php://input'),
getallheaders(),
['endpoint_ids' => ['whep_1kmn0aExample']],
);
$event = $verified['event'];
Under PHP-FPM, pass a PSR-16 cache as 'cache', or enable APCu, so workers share Flint's keys. Verify a webhook shows the full handler.
Install jose (npm install jose) and add this verifier:
import { createHash, timingSafeEqual } from "node:crypto";
import { createLocalJWKSet, jwtVerify } from "jose";
const issuer = "https://api.withflintpay.com";
const jwksUrl = `${issuer}/.well-known/jwks.json`;
const endpointIds = ["whep_1kmn0aExample"];
// One key cache per process, shared by every request and endpoint.
let keys;
let expiresAt = 0;
let lastFetchAt = -Infinity;
let fetching;
async function refreshKeys() {
if (!fetching) {
lastFetchAt = Date.now();
fetching = (async () => {
const response = await fetch(jwksUrl, {
redirect: "error",
signal: AbortSignal.timeout(3000),
});
if (!response.ok) throw new Error("Cannot fetch Flint JWKS");
const cacheControl = response.headers.get("cache-control") ?? "";
const maxAge = /(?:^|,)\s*max-age=(\d+)/i.exec(cacheControl);
const ageHeader = Number(response.headers.get("age") ?? 0);
const age = Number.isFinite(ageHeader) ? Math.max(0, ageHeader) : 0;
const seconds = /(?:^|,)\s*(?:no-cache|no-store)(?:,|$)/i.test(cacheControl)
? 0
: Math.max(0, Math.min(Number(maxAge?.[1] ?? 0), 86400) - age);
keys = createLocalJWKSet(await response.json());
expiresAt = Date.now() + seconds * 1000;
})().finally(() => { fetching = undefined; });
}
await fetching;
}
async function resolveKey(header, token) {
if (header.alg !== "ES256" || header.typ !== "flint-webhook+jwt" ||
typeof header.kid !== "string" || !header.kid) {
throw new Error("Invalid webhook JWT header");
}
if (!keys || Date.now() >= expiresAt) await refreshKeys();
try {
return await keys(header, token);
} catch (error) {
// An unknown key ID can force at most one refresh per minute.
if (error.code !== "ERR_JWKS_NO_MATCHING_KEY" ||
Date.now() - lastFetchAt < 60000) throw error;
await refreshKeys();
return keys(header, token);
}
}
export async function verifyFlintWebhook(rawBody, headers) {
const authorization = headers.authorization;
if (typeof authorization !== "string" ||
!/^Bearer [A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/.test(authorization)) {
throw new Error("Missing webhook bearer token");
}
const { payload } = await jwtVerify(authorization.slice(7), resolveKey, {
algorithms: ["ES256"],
typ: "flint-webhook+jwt",
issuer,
audience: endpointIds,
requiredClaims: ["iss", "aud", "iat", "exp", "jti", "body_sha256"],
clockTolerance: 60,
});
const now = Math.floor(Date.now() / 1000);
if (!Number.isSafeInteger(payload.iat) || !Number.isSafeInteger(payload.exp) ||
payload.iat > now + 60 || payload.exp <= payload.iat ||
payload.exp - payload.iat > 300 ||
typeof payload.aud !== "string" || !endpointIds.includes(payload.aud) ||
typeof payload.jti !== "string" || !payload.jti.startsWith("watt_") ||
headers["flint-webhook-endpoint-id"] !== payload.aud ||
headers["webhook-timestamp"] !== String(payload.iat)) {
throw new Error("Invalid webhook claims");
}
if (typeof payload.body_sha256 !== "string" ||
!/^[A-Za-z0-9_-]{43}$/.test(payload.body_sha256)) {
throw new Error("Invalid webhook body hash");
}
const actual = Buffer.from(payload.body_sha256, "ascii");
const expected = Buffer.from(createHash("sha256").update(rawBody).digest("base64url"), "ascii");
if (!timingSafeEqual(actual, expected)) throw new Error("Webhook body mismatch");
// Parse only after the signature, claims, and body hash pass.
const event = JSON.parse(rawBody.toString("utf8"));
if (typeof event.webhook_event_id !== "string" ||
!event.webhook_event_id.startsWith("whev_") ||
event.webhook_event_id !== headers["webhook-id"]) {
throw new Error("Invalid webhook event ID");
}
return event;
}
Install PyJWT with cryptography using pip install 'PyJWT[crypto]'. Pass your configured endpoint ID and the parsed JWKS from your server's cache. Load the cache from Flint's fixed JWKS URL using the caching rules below.
import base64
import hashlib
import hmac
import re
import jwt
ISSUER = "https://api.withflintpay.com"
class UnknownFlintSigningKey(ValueError):
pass
def verify_flint_jwt(raw_body, authorization, endpoint_id, jwks):
match = re.fullmatch(r"Bearer ([\w-]+\.[\w-]+\.[\w-]+)", authorization or "", re.ASCII)
if not match:
raise ValueError("Missing webhook bearer token")
token = match[1]
header = jwt.get_unverified_header(token)
kid = header.get("kid")
if (set(header) != {"alg", "kid", "typ"} or header["alg"] != "ES256"
or header["typ"] != "flint-webhook+jwt" or not isinstance(kid, str) or not kid):
raise ValueError("Invalid webhook JWT header")
keys = [key for key in jwks["keys"] if key.get("kid") == kid]
if not keys:
raise UnknownFlintSigningKey("Unknown webhook signing key")
if len(keys) != 1:
raise ValueError("Ambiguous webhook signing key")
key = keys[0]
if (key.get("kty") != "EC" or key.get("crv") != "P-256"
or key.get("alg", "ES256") != "ES256" or key.get("use", "sig") != "sig"):
raise ValueError("Invalid webhook signing key")
claims = jwt.decode(
token, jwt.PyJWK.from_dict(key, algorithm="ES256").key,
algorithms=["ES256"], issuer=ISSUER, audience=endpoint_id, leeway=60,
options={
"require": ["iss", "aud", "iat", "exp", "jti", "body_sha256"],
},
)
issued, expires = claims["iat"], claims["exp"]
if (not endpoint_id or claims["aud"] != endpoint_id
or type(issued) is not int or type(expires) is not int or issued <= 0
or not 0 < expires - issued <= 300 or "sub" in claims
or not isinstance(claims["jti"], str) or not claims["jti"].startswith("watt_")):
raise ValueError("Invalid webhook claims")
expected = base64.urlsafe_b64encode(hashlib.sha256(raw_body).digest()).rstrip(b"=")
actual = claims["body_sha256"]
if not isinstance(actual, str) or not actual.isascii() or not hmac.compare_digest(actual.encode(), expected):
raise ValueError("Webhook body mismatch")
return claims
Install go-jose using go get github.com/go-jose/go-jose/v4. Pass your configured endpoint ID and the decoded jose.JSONWebKeySet from your server's cache. Load the cache from Flint's fixed JWKS URL using the caching rules below. If the JWKS contains other key types, filter its entries to EC P-256 before decoding the key set.
package webhook
import (
"crypto/ecdsa"
"crypto/elliptic"
"crypto/sha256"
"crypto/subtle"
"encoding/base64"
"encoding/json"
"errors"
"strings"
"time"
jose "github.com/go-jose/go-jose/v4"
)
const issuer = "https://api.withflintpay.com"
var errUnknownFlintSigningKey = errors.New("unknown webhook signing key")
type webhookClaims struct {
Issuer string `json:"iss"`
Audience string `json:"aud"`
IssuedAt int64 `json:"iat"`
ExpiresAt int64 `json:"exp"`
ID string `json:"jti"`
BodySHA256 string `json:"body_sha256"`
Subject json.RawMessage `json:"sub"`
}
func verifyFlintJWT(rawBody []byte, authorization, endpointID string, jwks jose.JSONWebKeySet) (webhookClaims, error) {
var claims webhookClaims
token, ok := strings.CutPrefix(authorization, "Bearer ")
if !ok || token == "" || strings.ContainsAny(token, " \t\r\n") {
return claims, errors.New("missing webhook bearer token")
}
signed, err := jose.ParseSignedCompact(token, []jose.SignatureAlgorithm{jose.ES256})
if err != nil {
return claims, err
}
header := signed.Signatures[0].Protected
if header.ExtraHeaders["typ"] != "flint-webhook+jwt" || header.KeyID == "" {
return claims, errors.New("invalid webhook JWT header")
}
keys := jwks.Key(header.KeyID)
if len(keys) == 0 {
return claims, errUnknownFlintSigningKey
}
if len(keys) != 1 {
return claims, errors.New("ambiguous webhook signing key")
}
key, ok := keys[0].Key.(*ecdsa.PublicKey)
if !ok || key.Curve != elliptic.P256() ||
(keys[0].Algorithm != "" && keys[0].Algorithm != "ES256") ||
(keys[0].Use != "" && keys[0].Use != "sig") {
return claims, errors.New("invalid webhook signing key")
}
payload, err := signed.Verify(key)
if err != nil {
return claims, err
}
if err := json.Unmarshal(payload, &claims); err != nil {
return claims, err
}
now := time.Now().Unix()
if claims.Issuer != issuer || endpointID == "" || claims.Audience != endpointID ||
claims.IssuedAt <= 0 || claims.IssuedAt > now+60 || claims.ExpiresAt <= now-60 ||
claims.ExpiresAt <= claims.IssuedAt || claims.ExpiresAt-claims.IssuedAt > 300 ||
!strings.HasPrefix(claims.ID, "watt_") || claims.Subject != nil {
return webhookClaims{}, errors.New("invalid webhook claims")
}
digest := sha256.Sum256(rawBody)
expected := base64.RawURLEncoding.EncodeToString(digest[:])
if subtle.ConstantTimeCompare([]byte(claims.BodySHA256), []byte(expected)) != 1 {
return webhookClaims{}, errors.New("webhook body mismatch")
}
return claims, nil
}
On UnknownFlintSigningKey in Python or errUnknownFlintSigningKey in Go, refresh the cache if the rate limit below allows it, then verify again.
The Python and Go functions return verified claims. In your handler, check that Flint-Webhook-Endpoint-Id equals the verified aud and that webhook-timestamp equals the verified iat in Unix seconds. Parse the verified body as JSON, check that its webhook_event_id starts with whev_ and matches webhook-id, then deduplicate and process the event. Reject the delivery if verification raises an exception, returns an error, or any of these checks fails.
Apply these rules in your receiver:
- Check the token, then the body. Require
ES256, thetyp, the exact issuer, and one of your endpoint IDs as the audience. Then comparebody_sha256with a hash of the raw body in constant time, and parse JSON only after that. Run every check yourself, even behind a gateway that already verifies JWT signatures, because a gateway doesn't comparebody_sha256with the body. - Bound the clock. Allow at most 60 seconds of skew, reject an
iatin the future, and reject a token whose lifetime exceeds 300 seconds. Keep your server's clock synced with NTP. Retries are signed fresh, so a retry never fails this check. - Cache keys, but not forever. Honor the JWKS
Cache-Controlheader, cache keys for no more than 24 hours, share concurrent fetches, and refetch at most once a minute when a token names an unknownkid. Never pin onekid: keys rotate. If several workers share one cache, apply the once-a-minute limit across all of them. - Fail closed. If the keys can't be loaded or any check fails, answer with a non-
2xxstatus. Flint retries the delivery. On an endpoint with both methods, don't fall back to HMAC when the JWT fails. - Treat headers as hints.
Flint-Webhook-Endpoint-Idhelps route a request when one URL serves several endpoints, but only the verifiedaudproves which endpoint it belongs to. Don't log bearer tokens or echo them back.
Step 5: send a test event#
Prove that delivery, verification, and routing work before you wire up real payments. The test-events endpoint builds an event of the type you name and delivers it to the endpoint right away:
curl -X POST https://api.withflintpay.com/v1/webhook-endpoints/whep_1kmn0aExample/test-events \
-H "Content-Type: application/json" \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Idempotency-Key: webhook-test-order-paid-1" \
-d '{"event_type": "order.paid"}'
{
"data": {
"webhook_event_id": "whev_1kmn0aExample",
"webhook_delivery_id": "wdel_1kmn0aExample",
"webhook_delivery_attempt_id": "watt_1kmn0aExample",
"attempt_number": 1,
"attempt_status": "delivered",
"delivery_status": "delivered",
"delivery_trigger": "test_event",
"status_code": 200,
"duration_milliseconds": 326,
"started_at": "2026-07-03T14:53:30Z",
"completed_at": "2026-07-03T14:53:30Z"
}
}
Your endpoint receives a signed delivery with "test": true and no originating request:
{
"webhook_event_id": "whev_1kmn0aExample",
"event_type": "order.paid",
"event_source": "merchant",
"payload_version": 2,
"api_version": "2026-09-07",
"mode": "test",
"sandbox_id": "test_1kmn0aExample",
"merchant_id": "mer_1kmn0aExample",
"created_at": "2026-07-03T14:53:30Z",
"test": true,
"request": null,
"data": {
"object": {
"order_id": "ord_01KEZF7C00JBKMARG3P06Z224B",
"status": "open",
"payment_status": "paid",
"pricing_amounts": {
"total_money": {"amount": 5000, "currency": "USD"}
}
}
}
}
For the CLI-managed listener endpoint, the response contains webhook_event_id and delivery_method: "listener_stream". Flint publishes the synthetic event to the webhook event stream without making an HTTP attempt. A listener can forward it to your app if the endpoint subscribes to the event type. The response confirms publication, even when no listener is connected.
What to know about test events:
- The object is an example.
data.objectis the example resource from the event catalog, shown abbreviated above. It has the real shape, but its IDs don't exist in your account, so a handler that reads the resource back gets a404. Branch ontestbefore touching state you care about, and use real sandbox activity, such as a test card payment or a refund, to test your business logic. - One attempt for HTTP endpoints. If
attempt_statusisfailed, the response includes your server'sstatus_code,error_category, and a response excerpt. Inspect delivery attempts explains them. - Any type the endpoint's sources can receive. A merchant endpoint can test any merchant event type, subscribed or not. A partner app endpoint can test the types whose catalog
event_sourcesinclude one of its own.
Step 6: deduplicate and process asynchronously#
Retries and resends deliver the same event more than once. Record each webhook_event_id once, in the same transaction as the job that processes it, and answer 2xx only after that write succeeds. Use the verified body's webhook_event_id, never the JWT's jti: every attempt has a new token and attempt ID.
app.post("/webhooks/flint", express.raw({ type: "application/json" }), async (req, res) => {
let event;
try {
// With the Node SDK, use (await flint.verifyWebhookAsync(req.body, req.headers, { endpointIds })).event.
event = await verifyFlintWebhook(req.body, req.headers);
} catch {
return res.sendStatus(400);
}
try {
// Implement with your database and job queue. In one transaction, insert
// webhook_event_id under a unique constraint and enqueue a job. On a
// duplicate ID, insert nothing. An outbox table can bridge a separate queue.
await saveEventAndEnqueueOnce(event.webhook_event_id, event);
return res.sendStatus(200);
} catch {
return res.sendStatus(500); // Nothing durable yet, so Flint retries.
}
});
Check the dispute state before you fulfill. Dispute events can arrive before order.paid, and the order you read already carries dispute_status. Apply the access rules to it before fulfillOnce runs.
Then do the work in the job, and read current state before an irreversible side effect:
async function processEvent(event) {
if (event.test) return; // example objects don't exist in your account
switch (event.event_type) {
case "order.paid": {
const orderId = event.data.object.order_id;
const response = await fetch(`https://api.withflintpay.com/v1/orders/${orderId}`, {
headers: { Authorization: `Bearer ${process.env.FLINT_API_KEY}` },
});
if (!response.ok) throw new Error(`GET order failed: ${response.status}`);
const { data: order } = await response.json();
if (order.payment_status === "paid") await fulfillOnce(order);
return;
}
default:
return; // types you don't handle are acknowledged and ignored
}
}
- Answer within 10 seconds. Run fulfillment, emails, and third-party calls in the job, not in the request.
- Make jobs idempotent too. Queues can run a job twice, so key side effects such as
fulfillOnceon the order or event ID. - Don't split the write. Marking an event processed separately from enqueueing its job means a crash between the two either repeats or loses the work.
- Acknowledge what you ignore. Answer
2xxto event types you don't handle. An error response makes Flint retry them for about three days and leaves failed deliveries in the history you monitor.
Retries and ordering#
A delivery that fails retries on a backoff schedule: after 30 seconds, 2 minutes, 10 minutes, 1 hour, 4 hours, 12 hours, 24 hours, and 30 hours. Each delay is a minimum: Flint adds 0 to 20% at random, and a retry can start several seconds later still, longer when Flint is busy. While retries remain, the delivery is pending with a next_retry_at. After the ninth failed attempt it's failed, and automatic delivery stops. You can still resend it while its payload is retained, which is 14 days. Retry schedule and Retention have the details.
Flint runs one automatic attempt at a time per endpoint. If every request takes the full 10 seconds to time out, that endpoint gets about six attempts per minute at most. During an outage or recovery, deliveries can wait past next_retry_at while earlier attempts to the same endpoint finish. After a failed attempt finishes, the next backoff delay begins.
Because each event and each retry is delivered independently, a retry of an older event can arrive after a newer event. Treat a webhook as a signal that something changed, not as the change itself:
data.objectis a snapshot from when the event was recorded, and a retry can deliver it days later.- Some event types are notifications, such as
invoice.overdue, that prompt you to fetch the resource. Snapshot and notification events lists them. - Don't order events by comparing timestamps. When your logic depends on current state, fetch the resource and act on what the API returns. Delivery order shows an interleaved sequence.
Monitor, debug, and resend#
Flint records every delivery and what your server answered. When an event doesn't arrive or your handler rejects it, start with these records. The dashboard shows the same history under Developers > Webhooks, with attempt details, test events, and resends.
Each event has one delivery for each endpoint that receives it. The delivery's status says where it stands:
status on webhook deliveryGet alerted when deliveries fail#
When a live-mode delivery fails its fifth automatic attempt, about an hour after the first, the dashboard shows a Webhook deliveries are failing notice for the endpoint and emails it to everyone on your team who can manage webhooks. Flint keeps retrying while automatic attempts remain. You get one notice per incident: later failures on the same endpoint don't email again until a delivery to it succeeds, which resolves the notice. Sandbox endpoints and test events don't raise it. To page your own on-call, or to watch sandbox endpoints, alert on GET /v1/webhook-events?delivery_status=failed.
List recent events and deliveries#
GET /v1/webhook-events lists events, newest first:
curl "https://api.withflintpay.com/v1/webhook-events?webhook_endpoint_id=whep_1kmn0aExample" \
-H "Authorization: Bearer YOUR_API_KEY"
{
"data": [
{
"webhook_event_id": "whev_1kmn0aExample",
"event_source": "merchant",
"event_type": "order.paid",
"payload_version": 2,
"api_version": "2026-09-07",
"mode": "test",
"sandbox_id": "test_1kmn0aExample",
"merchant_id": "mer_1kmn0aExample",
"request": {
"id": "req_01KWM6CHDJB2VSB573FNFWX0PN"
},
"test": false,
"resource_type": "order",
"resource_id": "ord_1kmn0aExample",
"api_request_log_id": "rlog_1kmn0aExample",
"created_at": "2026-07-03T14:59:52Z"
}
]
}
An event has no single delivery status, because each endpoint gets its own delivery. Filter the list with:
webhook_endpoint_id: events with a delivery to that endpoint.delivery_status: events with at least one delivery in that status. Send several values, such asdelivery_status=pending,failed, to match any of them.event_type,resource_type,resource_id,request_id, andcreated_after(inclusive) orcreated_before(exclusive).event_typetakes current names and also matches events recorded under a previous name.test=truereturns only synthetic test events;test=falseexcludes them. Omittestto return every event. The same filter works onGET /v1/webhook-events/stream.
List items never include data. Fetch one event with GET /v1/webhook-events/{webhook_event_id} to get the delivered data and the originating request.idempotency_key. Both appear only when your key can read the resource the event is about and the payload is still retained, for 14 days. After that, the event loses data and payload_version and can't be delivered again, but its record stays until it's deleted after 90 days. data uses the older of your request's API version and the version the event was recorded at, and the event's api_version names it.
GET /v1/webhook-deliveries lists the deliveries themselves, newest first, across all your endpoints, including deliveries of test events. Filter by webhook_event_id, webhook_endpoint_id, status, created_after, and created_before. An unknown or invisible webhook_event_id or webhook_endpoint_id returns an empty page. A deleted endpoint's retained deliveries still match its ID. Malformed IDs return 400 INVALID_REQUEST with an INVALID_VALUE detail. This lists one endpoint's failed deliveries:
curl "https://api.withflintpay.com/v1/webhook-deliveries?webhook_endpoint_id=whep_1kmn0aExample&status=failed" \
-H "Authorization: Bearer YOUR_API_KEY"
{
"data": [
{
"webhook_delivery_id": "wdel_1kmn0aExample",
"webhook_event_id": "whev_1kmn0aExample",
"webhook_endpoint_id": "whep_1kmn0aExample",
"status": "failed",
"automatic_attempt_count": 9,
"max_attempts": 9,
"last_response_code": 404,
"error_category": "webhook_http_4xx",
"error_summary": "The webhook endpoint rejected the delivery.",
"retryable": false,
"recommended_action": "Inspect the endpoint response body and signature verification logic, then resend after fixing the handler.",
"created_at": "2026-07-03T14:59:52Z",
"updated_at": "2026-07-06T15:02:10Z"
}
]
}
After a failed attempt, a delivery describes its most recent failure with error_category, error_summary, retryable, and recommended_action. When retryable is false, sending again won't help until you change your endpoint. Branch your code on error_category; the other two strings are for people. A delivered or suppressed delivery has no failure fields.
Inspect delivery attempts#
Each attempt has a status: pending while scheduled or in flight, delivered when your endpoint answers 2xx, or failed when it returns another status, times out, or can't be reached. These are webhook values in the extensible message_attempt_status vocabulary; handle an unknown value without failing to read the record.
Each attempt records what your server answered, which is usually the whole diagnosis:
curl https://api.withflintpay.com/v1/webhook-deliveries/wdel_1kmn0aExample/attempts \
-H "Authorization: Bearer YOUR_API_KEY"
{
"data": [
{
"webhook_delivery_attempt_id": "watt_1kmn0aExample",
"webhook_delivery_id": "wdel_1kmn0aExample",
"webhook_event_id": "whev_1kmn0aExample",
"attempt_number": 1,
"delivery_trigger": "automatic_delivery",
"status": "failed",
"status_code": 500,
"error_category": "webhook_http_5xx",
"error_summary": "The webhook endpoint returned a server error.",
"retryable": true,
"recommended_action": "Inspect the endpoint logs for this delivery, fix the handler, then resend the webhook event.",
"response_headers": {
"content-type": "text/plain; charset=UTF-8",
"x-request-id": "3f6c2a1e"
},
"response_body_excerpt": "Internal Server Error",
"response_content_type": "text/plain; charset=UTF-8",
"started_at": "2026-07-03T14:59:52Z",
"completed_at": "2026-07-03T14:59:52Z",
"duration_milliseconds": 326
}
]
}
When your server answered, the attempt has its status_code, its response_headers keyed by lowercase name, and the first 4 KB of the body in response_body_excerpt. Flint replaces sensitive values with [REDACTED] and removes the headers and excerpt after 14 days. The response fields appear only when your key can read the resource the event is about.
| What you see | Likely cause | Fix |
|---|---|---|
webhook_http_4xx, status 400 | Your verifier rejected the delivery, usually because middleware parsed the body first | Verify the raw bytes (Step 1), and check that the audience and issuer, or the HMAC secret, belong to this endpoint. |
webhook_http_4xx, status 401 or 403 | Auth or CSRF middleware answered before your handler ran | Exempt the webhook route. |
webhook_http_4xx, status 404 | The registered URL doesn't match a deployed route | Compare the endpoint's url with your router. |
webhook_http_5xx | Your handler threw; the excerpt usually shows the error | Fix the handler, then resend. |
webhook_timeout | No answer within 10 seconds | Answer after enqueueing, not after processing (Step 6). |
webhook_redirect | Your server redirected: a trailing slash, http to https, or www | Register the exact final URL. |
webhook_dns or webhook_connection | The hostname doesn't resolve, or nothing is listening. Tunnels expire. | Restart the server or tunnel and update the URL. |
webhook_tls | The certificate is invalid, expired, or self-signed | Serve a valid certificate. |
webhook_blocked_target | The URL resolves to a private or local address | Use a public HTTPS URL. |
webhook_payload_render | Flint couldn't prepare the payload; your endpoint isn't at fault | Nothing to change. Flint retries; contact support if it keeps failing. |
Failure categories lists every value with its retryable setting, and Suppression reasons lists every suppression_reason.
Resend a delivery#
After you fix your handler, resend the delivery. Resend works in any delivery status, including pending while Flint is still retrying. It sends the event to the delivery's endpoint now and returns that attempt:
curl -X POST https://api.withflintpay.com/v1/webhook-deliveries/wdel_1kmn0aExample/resend \
-H "Content-Type: application/json" \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Idempotency-Key: resend-wdel_1kmn0aExample-1" \
-d '{"reason_message": "handler fixed, redelivering"}'
{
"data": {
"webhook_event_id": "whev_1kmn0aExample",
"webhook_delivery_id": "wdel_1kmn0aExample",
"webhook_delivery_attempt_id": "watt_1kmn0aExample",
"attempt_number": 2,
"attempt_status": "delivered",
"delivery_status": "delivered",
"delivery_trigger": "manual_resend",
"reason_message": "handler fixed, redelivering",
"status_code": 200,
"duration_milliseconds": 341
}
}
A resend carries a fresh signature and the same webhook_event_id, so your deduplication skips an event you already processed. To process it again, clear your record of that event ID first.
A resend never uses up or moves the automatic schedule:
- If your endpoint answers
2xx, the delivery becomesdeliveredand its remaining retries are canceled. - If the attempt fails on a
pendingdelivery, it stayspendingwith the samenext_retry_at. Onlylast_response_codeand the failure fields change. - The attempt takes the next
attempt_numberwith themanual_resendtrigger, and doesn't count towardautomatic_attempt_countormax_attempts.
Recover after an outage or a disabled endpoint#
After an outage or a period with the endpoint deactivated, an event is in one of two states: it has a delivery that didn't succeed, or it has no delivery to this endpoint at all. Fix the handler, set the endpoint's status back to active if you deactivated it, and then recover each state.
Before you script a recovery:
- Retention. Only events whose payload is still retained, for 14 days, can be delivered. Listed events without
payload_versionare past that point. Skip them and read current state from the API. - Eligibility. The endpoint must be active and must subscribe to the event's type now. When the endpoint was created doesn't matter, so you can also backfill a new endpoint, as in Upgrade with two endpoints.
- One delivery per event and endpoint. If a delivery already exists,
ALREADY_EXISTSnames it incurrent_resource. Resend it if it isn'tdelivered. Replaying a request with the sameIdempotency-Keyreturns the first response. - Order. Recovery deliveries aren't ordered against live deliveries and retries. Create them oldest first, and fetch current state when order matters.
- Rate. Create and resend use the
writerate limit: 20 requests a second and 600 a minute per key, so 3,000 events take about five minutes. On a429, wait forRetry-Afterand retry with the sameIdempotency-Key. - Duplicates. Recovered deliveries carry the original
webhook_event_id, so your deduplication handles events your handler already processed. - Partner apps. When none of an app's active endpoints matched an event, Flint didn't record the event for the app, so there's nothing to deliver.
Recovery replays history. To bring your records up to date regardless of which events you missed, read the current resources instead.
Catch up from the event stream#
After an outage, GET /v1/webhook-events/stream reads every event recorded since a known event, in recorded order and with data, without one GET per event. The stream reference lists every frame and limit. This is the recovery path for events that never had a delivery, and it works the same whether or not the endpoint was active.
Pick a cursor: the webhook_event_id of an event you know arrived before the outage. Store the last few IDs you processed, and start from the earliest one that predates the outage. Events after the cursor stream in recorded order, and your deduplication on webhook_event_id absorbs any overlap. Send the same Flint-Version as the endpoint's api_version to get the shape that endpoint receives:
curl -N "https://api.withflintpay.com/v1/webhook-events/stream?event_type=order.paid,refund.created" \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Last-Event-ID: whev_1kmn0aExample" \
-H "Flint-Version: 2026-09-07"
Handle each frame by its event:
webhook.event: Deduplicate onwebhook_event_id, then process the event through the same job path your handler uses: record the ID and enqueue the job in one transaction, as in Step 6. If the endpoint itself should receive the event,POST /v1/webhook-deliveriesas in Recover after an outage or a disabled endpoint instead.withheld: Your key can't read the event's payload, andreasonsays why. Formissing_resource_scope, grant the key a scope fromrequired_scopes; for any reason, you can fetch the resource named byresource_typeandresource_idwith a key that can read it.gapwithpayload_expired: The event's payload is past the 14-day retention. Read the resource's current state instead.gapwithcursor_unavailable: The cursor is older than 90 days or belongs to another environment, or the sandbox was reset, so the stream restarted from the newest event and skipped everything between. Read current state to bring your records up to date.
Keep the id of the last frame you handled. When Flint closes the stream, reconnect from resume_cursor after a backpressure disconnect, which Flint sends after 1,000 events in one read. After a ttl disconnect, which comes 30 minutes in, or after a dropped connection, reconnect from the last id. You're caught up once the stream goes quiet except for heartbeats.
The stream needs an API key with webhooks.read and the read scope of each resource whose payload you want. A partner app can stream an installed merchant's events with a partner app token that names the merchant in Flint-Merchant-Id; see Catch up on missed installed-merchant events. It carries merchant events only, creates no deliveries, and doesn't retry, so production processing stays on an endpoint. An environment can have five streams open at once, apart from each partner app install's own five. A sixth returns 409 LIMIT_REACHED with reason webhook_event_streams: close another stream or wait for one to end, then connect again.
Change which events an endpoint receives#
PATCH /v1/webhook-endpoints/{webhook_endpoint_id} replaces enabled_events as a whole, so a list built from a stale read could drop a type a teammate just added. Every endpoint has a version that increases with each change to it. A PATCH that sends enabled_events, event_sources, installed_merchant_modes, or signing_methods must include the version you read as expected_version. To add refund.created to the endpoint from Step 3:
curl -X PATCH https://api.withflintpay.com/v1/webhook-endpoints/whep_1kmn0aExample \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-H "Idempotency-Key: webhook-events-add-refund-created-v1" \
-d '{
"expected_version": 1,
"enabled_events": [
"order.paid",
"refund.created",
"refund.succeeded",
"refund.partially_succeeded",
"refund.failed"
]
}'
The response is the endpoint with the new list and version 2. A change to only url, description, status, or api_version doesn't need expected_version, but accepts it. Deliveries don't change an endpoint's version, so a busy endpoint doesn't conflict with your edits.
Pause or delete an endpoint#
Deactivate an endpoint#
Set status to inactive to stop delivery right away:
curl -X PATCH https://api.withflintpay.com/v1/webhook-endpoints/whep_1kmn0aExample \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-H "Idempotency-Key: webhook-deactivate-001" \
-d '{"status": "inactive"}'
Pending deliveries become suppressed with suppression_reason endpoint_inactive in the same update, so Flint never sends them, and events that occur while the endpoint is inactive create no deliveries for it. Setting status back to active resumes delivery for new events only. To catch up, recover the missed deliveries or read current state from the API.
Delete an endpoint#
DELETE /v1/webhook-endpoints/{webhook_endpoint_id} permanently deletes the endpoint and returns it with status deleted. Its pending deliveries are suppressed with endpoint_deleted, and all signing for it ends. The endpoint can't be read afterward; its past deliveries keep its webhook_endpoint_id. Add ?expected_version= with the version you read to delete it only if nobody changed it since. To pause an endpoint you may want back, deactivate it instead.
Upgrade with two endpoints#
Flint records each event at the current API release, regardless of the version of the request that caused it. Each delivery, retry, and resend uses the older of the endpoint's api_version at that attempt and the event's recorded version. Upgrading an endpoint can change the shape of pending retries and resends. To move a handler to a new version with a rollback path:
To upgrade an endpoint in place instead, deploy a handler that accepts the target version, then PATCH the endpoint's api_version. For 72 hours afterward, the endpoint shows the version it had in api_version_previous, and api_version_rollback_expires_at says when that offer ends; send it back as api_version to roll back, or use the dashboard's Developers > Versions screen. Pending retries use the endpoint's version at the time of each attempt. Rolling back doesn't undo what your handler already did. API versions and upgrades covers the rest of an upgrade.
Verify an HMAC delivery#
An endpoint with hmac in signing_methods signs each delivery with its shared secret in the Standard Webhooks format:
webhook-id: whev_1kmn0aExample
webhook-timestamp: 1783090410
webhook-signature: v1,pZ3fLq0X8vY2mB7kT1nR4cW9sH6jD5aE...
webhook-idis the event'swebhook_event_id, the same on every retry and resend.webhook-timestampis when this attempt was signed, in Unix seconds. Retries are signed fresh.webhook-signatureholds one or more space-separatedv1,<signature>values, each a base64 HMAC-SHA256. There are two while a replaced secret still signs after a rotation. A match against any one means the delivery is authentic.
If one URL serves several endpoints, the Flint-Webhook-Endpoint-Id header names the endpoint, so you can pick its secret before verifying. Pass every secret you currently accept, which is two during a rotation:
import crypto from "node:crypto";
export function verifyFlintWebhookHMAC(rawBody, headers, secrets, toleranceSeconds = 300) {
const id = headers["webhook-id"];
const timestamp = Number(headers["webhook-timestamp"]);
const signatures = String(headers["webhook-signature"] ?? "")
.split(" ")
.filter((part) => part.startsWith("v1,"))
.map((part) => Buffer.from(part.slice(3)));
if (!id || !Number.isInteger(timestamp) || signatures.length === 0) {
throw new Error("Missing signature headers");
}
if (Math.abs(Date.now() / 1000 - timestamp) > toleranceSeconds) {
throw new Error("Timestamp outside tolerance");
}
const signedContent = Buffer.concat([Buffer.from(`${id}.${timestamp}.`), rawBody]);
const valid = secrets.some((secret) => {
const key = Buffer.from(secret.replace(/^whsec_/, ""), "base64");
const expected = Buffer.from(
crypto.createHmac("sha256", key).update(signedContent).digest("base64"),
);
return signatures.some(
(signature) =>
signature.length === expected.length && crypto.timingSafeEqual(signature, expected),
);
});
if (!valid) {
throw new Error("Signature mismatch");
}
}
import base64
import hashlib
import hmac
import time
def verify_flint_webhook(raw_body: bytes, headers, secrets: list, tolerance_seconds: int = 300) -> None:
message_id = headers.get("webhook-id", "")
timestamp = headers.get("webhook-timestamp", "")
signatures = [
part[3:] for part in headers.get("webhook-signature", "").split(" ") if part.startswith("v1,")
]
if not message_id or not timestamp.isdigit() or not signatures:
raise ValueError("Missing signature headers")
if abs(time.time() - int(timestamp)) > tolerance_seconds:
raise ValueError("Timestamp outside tolerance")
signed_content = f"{message_id}.{timestamp}.".encode() + raw_body
for secret in secrets:
key = base64.b64decode(secret.removeprefix("whsec_"))
expected = base64.b64encode(hmac.new(key, signed_content, hashlib.sha256).digest()).decode()
if any(hmac.compare_digest(expected, signature) for signature in signatures):
return
raise ValueError("Signature mismatch")
package webhooks
import (
"crypto/hmac"
"crypto/sha256"
"encoding/base64"
"errors"
"fmt"
"net/http"
"strconv"
"strings"
"time"
)
func VerifyFlintWebhook(rawBody []byte, headers http.Header, secrets []string, tolerance time.Duration) error {
id := headers.Get("webhook-id")
timestamp, err := strconv.ParseInt(headers.Get("webhook-timestamp"), 10, 64)
if id == "" || err != nil {
return errors.New("missing signature headers")
}
age := time.Since(time.Unix(timestamp, 0))
if age < 0 {
age = -age
}
if age > tolerance {
return errors.New("timestamp outside tolerance")
}
signedContent := append([]byte(fmt.Sprintf("%s.%d.", id, timestamp)), rawBody...)
for _, secret := range secrets {
key, err := base64.StdEncoding.DecodeString(strings.TrimPrefix(secret, "whsec_"))
if err != nil {
continue
}
mac := hmac.New(sha256.New, key)
mac.Write(signedContent)
expected := base64.StdEncoding.EncodeToString(mac.Sum(nil))
for _, part := range strings.Fields(headers.Get("webhook-signature")) {
if signature, ok := strings.CutPrefix(part, "v1,"); ok &&
hmac.Equal([]byte(signature), []byte(expected)) {
return nil
}
}
}
return errors.New("signature mismatch")
}
These verifiers use only your runtime's crypto library. The Flint SDKs include a verifyWebhook method that runs the same checks.
How HMAC verification works#
To implement it in another language:
Test your HMAC verifier#
These values are consistent with each other, so you can use them as a fixture before pointing Flint at your endpoint. With the secret whsec_IZuqE1Q8V+xP3VgZ5vHrJBFM1WJ6+DpvV35+yRHKKc8= and this raw body (one line, no trailing newline):
{"webhook_event_id":"whev_0testvector00000000000000","event_type":"payment_intent.succeeded","event_source":"merchant","payload_version":2,"api_version":"2026-09-07","mode":"test","merchant_id":"mer_0testvector00000000000000","created_at":"2026-07-03T14:53:30Z","test":false,"request":null,"data":{"object":{"payment_intent_id":"pi_0testvector00000000000000","status":"succeeded","amount_money":{"amount":2500,"currency":"USD"},"order_id":"ord_0testvector00000000000000"}}}
a correct verifier accepts these headers:
webhook-id: whev_0testvector00000000000000
webhook-timestamp: 1783090410
webhook-signature: v1,WBnxsylB0R3d6g/4omCZwl1e4D2qhl96yJVqzoCyzrU=
The timestamp is fixed, so turn off the tolerance check for this fixture only.
Verify with a Standard Webhooks library#
If your team already uses the Standard Webhooks libraries, they verify HMAC deliveries without any crypto code of your own. Pass the whsec_... secret unchanged; the libraries handle the prefix. Each library instance holds one secret, so during a rotation try the current secret first and the previous one if that fails.
import { Webhook } from "standardwebhooks";
const webhook = new Webhook(process.env.FLINT_WEBHOOK_SECRET);
// Throws when the signature is invalid or the timestamp is stale.
const event = webhook.verify(req.body, {
"webhook-id": req.headers["webhook-id"],
"webhook-timestamp": req.headers["webhook-timestamp"],
"webhook-signature": req.headers["webhook-signature"],
});
import os
from standardwebhooks import Webhook
webhook = Webhook(os.environ["FLINT_WEBHOOK_SECRET"])
# Raises WebhookVerificationError when invalid.
event = webhook.verify(raw_body, dict(request.headers))
import standardwebhooks "github.com/standard-webhooks/standard-webhooks/libraries/go"
wh, err := standardwebhooks.NewWebhook(os.Getenv("FLINT_WEBHOOK_SECRET"))
if err != nil {
log.Fatal(err)
}
// Returns an error when the signature is invalid or the timestamp is stale.
if err := wh.Verify(rawBody, r.Header); err != nil {
w.WriteHeader(http.StatusBadRequest)
return
}
Change signing methods#
signing_methods is always present on an endpoint, with the values jwt and hmac. A PATCH that sends it replaces the whole set and must include expected_version from your latest read; omit it to leave the methods unchanged. Existing endpoints keep the methods they have until you change them.
To move an HMAC endpoint to JWT without interrupting verification:
To add HMAC to a JWT-only endpoint, PATCH signing_methods to ["jwt", "hmac"] or ["hmac"], with its current expected_version. The response issues the first secret and returns it once. Save it securely; later updates, reads, and lists omit it. Removing hmac deletes the secret, so adding it again issues a new one. Once a secret exists, a PATCH can select ["hmac"] alone to turn JWT off. An endpoint with both methods is only as strong as the weaker check your receiver accepts, so require the JWT once you've deployed it.
Rotate your signing secret#
JWT-only endpoints have no shared secret to rotate: Flint rotates its signing keys and publishes them in the JWKS. Calling rotate-secret on a JWT-only endpoint returns 409 ACTION_NOT_ALLOWED, with reason secret_not_issued. To enable HMAC and receive its first secret, PATCH signing_methods to include hmac.
For an endpoint with hmac, rotate when a secret may have leaked, when someone with access to it leaves, or on your security policy's schedule. By default, for 24 hours after a rotation, every delivery carries signatures from both the old and new secrets, so your handler keeps verifying while you deploy.
curl -X POST https://api.withflintpay.com/v1/webhook-endpoints/whep_1kmn0aExample/rotate-secret \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Idempotency-Key: webhook-rotate-001"
The response is the endpoint. secret is the new secret, returned only here, and previous_secret_expires_at is when the replaced secret stops signing:
{
"data": {
"webhook_endpoint_id": "whep_1kmn0aExample",
"url": "https://example.com/webhooks/flint",
"secret": "whsec_8496JEjvXj6YMU2eGg1GYA+/M1pundqxxvRNasV25u4=",
"signing_methods": ["jwt", "hmac"],
"enabled_events": [
"order.paid",
"refund.succeeded",
"refund.partially_succeeded",
"refund.failed"
],
"description": "Fulfillment and refund sync",
"api_version": "2026-09-07",
"event_sources": ["merchant"],
"status": "active",
"version": 2,
"previous_secret_expires_at": "2026-07-04T15:20:00Z",
"created_at": "2026-07-03T14:53:12Z",
"updated_at": "2026-07-03T15:20:00Z"
}
}
For a slower rollout, send expire_previous_secret_at in the body: an RFC 3339 timestamp no more than 7 days from now. Rotation increases the endpoint's version; to rotate only if the endpoint hasn't changed since you read it, add expected_version, and a stale value returns 409 VERSION_CONFLICT and keeps the current secret.
If the secret leaked#
A leaked secret lets anyone sign events your handler accepts, and by default it keeps signing for 24 hours. To end it now, rotate with expire_previous_secret_at set to the current time:
curl -X POST https://api.withflintpay.com/v1/webhook-endpoints/whep_1kmn0aExample/rotate-secret \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-H "Idempotency-Key: webhook-rotate-002" \
-d "{\"expire_previous_secret_at\": \"$(date -u +%Y-%m-%dT%H:%M:%SZ)\"}"
A time at or before now ends the replaced secret at once, and the response has no previous_secret_expires_at. From the next attempt, including pending retries, deliveries carry one signature, from the new secret. Your handler rejects them until you deploy the new secret, and Flint retries those deliveries on the usual schedule, so deploy quickly. Deploy only the new secret: setting the leaked one as FLINT_WEBHOOK_PREVIOUS_SECRET would keep accepting events signed with it. Deliveries already sent aren't recalled.
If you no longer need a shared secret at all, finish the move to JWT instead, which deletes every secret.
Secret retention#
- Flint returns a secret once, in the response that creates or rotates it, and can't show it again.
- The current secret signs every delivery while
hmacis enabled, until you rotate it, removehmac, or delete the endpoint. - A replaced secret signs alongside the new one until
previous_secret_expires_at, which appears on the endpoint only during that overlap. - Rotating again during an overlap makes the current secret the previous one and ends the older one at once, so a delivery never carries more than two signatures.
Production checklist#
- The handler verifies every delivery against the raw body: the JWT and body hash with Flint's JWKS and your endpoint ID, or the HMAC signature with a bounded timestamp check.
- It records
webhook_event_idand enqueues the job in one transaction, and answers2xxwithin 10 seconds, only after that write. - Jobs are idempotent and read current state before irreversible side effects.
- Unhandled event types get a
2xx, andenabled_eventslists only what you handle. - One event triggers fulfillment, and the browser redirect never does.
- If you use HMAC, secrets live in a secret manager and you have a rotation plan.
- Someone who can manage webhooks receives Flint's failing-endpoint email after the fifth failed automatic attempt, and for sandbox endpoints or your own paging, something alerts on
GET /v1/webhook-events?delivery_status=failed. - The production endpoint is registered with a live key, and its receiver expects the live endpoint's ID as the audience. See Going live.
Next steps#
Event catalogWebhook deliveryTestingWebhooks API referenceMonitor API keys#
Subscribe to api_key.created, api_key.updated, and api_key.revoked to monitor credential changes. The payload is the API key's GET representation and never includes its secret. Test-key events go to that sandbox's endpoints, and live-key events go to live endpoints. Passing expires_at and updates to last_used_at send no event. This family is unavailable to partner apps. See API key events.