Webhooks
Get notified when an analysis finishes, verify the signature, then fetch the result.
A webhook tells your system when an analysis has finished, so you do not have to poll. When an
analysis succeeds, fails or is canceled, AirCredit sends an analysis.succeeded, analysis.failed
or analysis.canceled event. The event goes to the webhook URL of the analysis's integration and
mode.
The event does not contain the result. It has the analysis ID, your external_id if you set one,
the analysis status, the mode, and the api_version that determines the event's format:
{"id":"evt_example","type":"analysis.succeeded","api_version":"v1","mode":"live","timestamp":"2026-10-09T10:00:00Z","data":{"analysis_id":"ana_example","external_id":"loan-451","status":"succeeded"}}
Verify the signature, then fetch the result with GET /v1/analyses/{id} and an API key of the same
mode. The analysis may have been deleted or expired by then.
Set up a webhook
Each integration has one webhook URL for test events and one for live events. Set them under Partner API in the AirCredit account settings. If a mode has no URL, AirCredit sends no events for that mode.
Test events go only to the test URL. Either URL can be any valid URL, and both can be the same. Point the test URL at a separate receiver to keep test events out of your production system.
Each webhook is pinned to an API version, and its events use that version's format (Webhook versions).
The URL must:
- use HTTPS on the default port 443
- name a public domain, not an IP address
- contain no user name, password or
#fragment - resolve only to public internet addresses
AirCredit checks the resolved addresses again on every connection. A later DNS change therefore cannot redirect deliveries into a private network.
When you add a webhook, the settings show its signing secret once. It starts with whsec_. Store it
in your receiver before you close the dialog. Changing the URL later keeps the secret. Removing the
webhook stops all deliveries, including those waiting for a retry.
You manage webhooks in the settings only. The API has no operations to register, list, inspect or redeliver them.
Verify the signature
AirCredit signs every delivery as described in
Standard Webhooks.
The SDKs verify a delivery with verifyWebhook in TypeScript and verify_webhook in Python and
Rust. Pass it the signing secret, the request headers and the raw body, exactly as received. It
returns the typed event, or fails if the signature does not match or the timestamp is more than five
minutes off in either direction.
This example verifies a delivery and reads the analysis of a succeeded event. Your web framework passes it the headers and the raw body. To keep the example short, it reads the analysis right away. In production, queue that work as Process deliveries reliably describes.
// Verifies webhook deliveries and fetches the analysis each one reports on.
import {
createServer,
type IncomingMessage,
type ServerResponse,
} from "node:http";
import { Client, verifyWebhook } from "@aircredit/sdk/partner/v1";
const client = Client.fromEnv();
const secret = process.env.AIRCREDIT_WEBHOOK_SECRET ?? "";
async function handleWebhook(
request: IncomingMessage,
response: ServerResponse,
) {
// Verify the signature over the exact bytes received, before parsing anything.
const rawBody = Buffer.concat(await request.toArray());
let event;
try {
event = verifyWebhook(secret, request.headers, rawBody);
} catch {
response.writeHead(400).end();
return;
}
// Acknowledge at once, then read the analysis. Deduplicate by the event ID.
response.writeHead(204).end();
console.log(`event ${event.id}`);
if (event.type === "analysis.succeeded") {
const analysis = await client.getAnalysis(event.data.analysis_id);
console.log(`analysis ${analysis.id} is ${analysis.status}`);
}
}
createServer(
(request, response) => void handleWebhook(request, response),
).listen(3000);Without the SDK
The signature is an HMAC-SHA256 of webhook-id.webhook-timestamp.raw_body. This string joins the
values of the webhook-id and webhook-timestamp headers and the raw request body with dots. To
verify it:
- Take the raw body bytes exactly as received, before you parse the JSON.
- Decode the standard Base64 part of the secret that follows
whsec_. Use the decoded bytes as the key. The secret string with its prefix is not the key. - Compare your result with the signatures in
webhook-signature. The header holds one or more space-separated entries of the formv1,<standard Base64>. - Check that
webhook-timestampis recent. Use this header, not thetimestampin the body. The header is new for each delivery attempt and is covered by the signature. The body is the same on every attempt, and itstimestampis the time of the event.
The samples below do all of this without a library, as a template for any other language. They reject a timestamp that is more than five minutes off in either direction. They also reject malformed encodings and compare digests in constant time. Pass them the secret, the three header values and the raw body.
TypeScript for Node.js
import { createHmac, timingSafeEqual } from "node:crypto";
// A delivery whose timestamp differs from the verifier's clock by more than this is rejected.
const REPLAY_WINDOW_SECONDS = 300;
// The public prefix of every signing secret; the Base64 key material follows it.
const SECRET_PREFIX = "whsec_";
/**
* Returns whether one webhook delivery is authentic for `secret`.
*
* `headers` carries the delivery's `id`, `timestamp` and `signature` values, and `rawBody` must be
* the exact bytes received.
* A delivery whose timestamp lies outside the replay window around `nowSeconds` is rejected.
* During a secret rotation the header carries one `v1` entry per secret that still signs, and the
* delivery verifies when any entry matches `secret`.
*/
export function verifyWebhook(
secret: string,
headers: { id: string; timestamp: string; signature: string },
rawBody: Uint8Array,
nowSeconds = Math.floor(Date.now() / 1000)
): boolean {
// Check the delivery attempt time before doing cryptographic work.
if (!headers.id || !/^(0|[1-9][0-9]*)$/.test(headers.timestamp)) return false;
const timestamp = Number(headers.timestamp);
// Number() rounds integers beyond Number.MAX_SAFE_INTEGER, so such timestamps are refused rather
// than compared approximately.
if (!Number.isSafeInteger(timestamp) || Math.abs(nowSeconds - timestamp) > REPLAY_WINDOW_SECONDS)
return false;
// Decode canonical standard Base64 rather than treating the public prefix as key material.
const encodedKey = secret.startsWith(SECRET_PREFIX) ? secret.slice(SECRET_PREFIX.length) : "";
const key = Buffer.from(encodedKey, "base64");
if (key.length === 0 || key.toString("base64") !== encodedKey) return false;
const expected = createHmac("sha256", key)
.update(`${headers.id}.${headers.timestamp}.`)
.update(rawBody)
.digest();
// Rotation may supply several signatures; accept any matching supported version.
return headers.signature.split(" ").some(entry => {
const [version, encoded, extra] = entry.split(",");
if (version !== "v1" || !encoded || extra !== undefined) return false;
const actual = Buffer.from(encoded, "base64");
return (
actual.length === expected.length &&
actual.toString("base64") === encoded &&
timingSafeEqual(actual, expected)
);
});
}
Python
import base64
import binascii
import hashlib
import hmac
import re
import time
# A delivery whose timestamp differs from the verifier's clock by more than this is
# rejected.
REPLAY_WINDOW_SECONDS = 300
# The TypeScript verifier refuses timestamps above JavaScript's MAX_SAFE_INTEGER.
# Refusing them here too keeps both verifiers accepting the same timestamps.
MAX_SAFE_TIMESTAMP = 9007199254740991
# The public prefix of every signing secret; the Base64 key material follows it.
SECRET_PREFIX = "whsec_"
def verify_webhook(secret, headers, raw_body, now_seconds=None):
"""Return whether one webhook delivery is authentic for `secret`.
`headers` carries the delivery's `id`, `timestamp` and `signature` values, and
`raw_body` must be the exact bytes received.
A delivery whose timestamp lies outside the replay window around `now_seconds`,
which defaults to the current time, is rejected.
During a secret rotation the header carries one `v1` entry per secret that still
signs, and the delivery verifies when any entry matches `secret`.
"""
# Check the delivery attempt time independently of the event time in the body.
if now_seconds is None:
now_seconds = int(time.time())
timestamp = headers["timestamp"]
# Bound the digits before int(), which raises on thousands of them.
# Sixteen digits hold 2^53 - 1.
if not headers["id"] or not re.fullmatch(r"0|[1-9][0-9]{0,15}", timestamp):
return False
parsed_timestamp = int(timestamp)
if (
parsed_timestamp > MAX_SAFE_TIMESTAMP
or abs(now_seconds - parsed_timestamp) > REPLAY_WINDOW_SECONDS
):
return False
# Decode canonical standard Base64 before computing the MAC over exact bytes.
if not secret.startswith(SECRET_PREFIX):
return False
encoded_key = secret[len(SECRET_PREFIX) :]
try:
key = base64.b64decode(encoded_key, validate=True)
except (binascii.Error, ValueError):
return False
if not key or base64.b64encode(key).decode("ascii") != encoded_key:
return False
signed = f"{headers['id']}.{timestamp}.".encode() + raw_body
expected = hmac.new(key, signed, hashlib.sha256).digest()
# Skip unsupported or malformed entries while checking every rotation candidate.
for entry in headers["signature"].split(" "):
parts = entry.split(",")
if len(parts) != 2 or parts[0] != "v1":
continue
try:
actual = base64.b64decode(parts[1], validate=True)
except (binascii.Error, ValueError):
continue
if base64.b64encode(actual).decode("ascii") != parts[1]:
continue
if hmac.compare_digest(actual, expected):
return True
return False
Process deliveries reliably
The same event can arrive more than once. Deduplicate events by their event ID. After you verify a delivery:
- Parse the JSON.
- In durable storage, record the event ID and queue the processing in one atomic step. If the ID is already recorded, acknowledge the delivery without processing it again.
- Respond with
2xxonly after that step has been stored. - Fetch the analysis in the queued job, not while you answer the delivery.
Keep your server clock synchronized, because the timestamp check depends on it. Never fetch a URL taken from a request you have not verified.
Retries
AirCredit waits up to 30 seconds for your response. It retries a delivery after a transport failure
or an HTTP 408, 429 or 5xx response. There are up to six retries, after waits of 1 minute, 5
minutes, 30 minutes, 2 hours, 12 hours and 24 hours. If the seventh attempt also fails, AirCredit
gives up. To get another attempt after a temporary problem, respond with 408, 429 or 5xx.
Any other response outside 2xx is a permanent failure, and AirCredit does not retry it. A 410
also stops all deliveries to the webhook, and the settings then show delivery as stopped. To resume,
save the URL again, even unchanged. A 410 in response to an attempt sent before you saved the URL
does not stop delivery.
Rotate the signing secret
To replace the secret, click Rotate secret beside the webhook under Partner API. The new secret is shown once. For the next 24 hours, the previous secret also keeps signing, so each delivery carries both signatures. Accept a delivery if any signature matches a secret you trust. Switch your receiver to the new secret before the 24 hours are over.
A second rotation ends the previous secret's overlap at once. If a secret leaks, rotate twice in a row to revoke it immediately. Then configure your receiver with the newest secret.