Integrate
Webhooks
How webhooks work#
- You register an HTTPS endpoint and choose the events it receives.
- When an event happens, CortexPay queues a delivery in the same database transaction, so an event is never sent for something that did not happen.
- Each delivery is signed with the endpoint's secret. Your endpoint verifies the signature and answers with any 2xx status.
Register an endpoint#
Register endpoints in Developer Console → Webhooks or with POST /api/webhooks/register and { url, events, description?, applicationId? }. With an API key you need webhooks:write. A workspace can have 10 endpoints.
const BASE_URL = "https://cortexpay.vercel.app";
const res = await fetch(`${BASE_URL}/api/webhooks/register`, {
method: "POST",
headers: {
Authorization: `Bearer ${process.env.CORTEXPAY_API_KEY}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
url: "https://example.com/webhooks/cortexpay",
events: [
"payment.settled",
"payment.rejected",
"approval.requested"
],
description: "Payments service"
}),
});
const data = await res.json();
if (!res.ok) throw new Error(`${data.error.code}: ${data.error.message}`);
console.log(data.secret // shown once: store it now);- The URL must be
https://and resolve to a public address. Private, loopback and link-local addresses are refused when you register and again at every delivery, and redirects are not followed. - The signing secret starts with
whsec_and is returned once. CortexPay stores it encrypted and shows only its last four characters afterwards.POST /api/webhooks/:id/rotate-secretreplaces it immediately and returns the new one once. POST /api/webhooks/:id/testsends a signedwebhook.testdelivery straight away, so you can check your endpoint. Endpoints cannot subscribe to it.
Delivery format#
Every delivery is a POST with a JSON body:
{
"id": "0b7e5c2a-4d1f-4e8a-9c3b-2a1d0e9f8c7b",
"type": "payment.settled",
"created_at": "2026-12-02T14:03:11.204Z",
"data": {
"payment_id": "9b2e4d10-5c3a-4f7e-8d21-6a0b1c2d3e4f",
"request_id": "c41a7e2b-0d9f-4b6a-a3c5-1e2f3a4b5c6d",
"amount": "250000",
"asset": "USDC",
"network": "hyperevm",
"reference": "0x5e1d…",
"block_number": "18342071"
}
}| Header | Value |
|---|---|
Content-Type | application/json |
CortexPay-Event | The event type, the same as type in the body. |
CortexPay-Delivery | The event id, the same as id in the body. It does not change between retries. |
CortexPay-Signature | t=<unix seconds>,v1=<hex HMAC-SHA256(secret, "<t>.<raw body>")> |
User-Agent | CortexPay-Webhooks/1.0 |
Amounts are strings of integer base units. Deliveries can arrive out of order and more than once: use id to skip events you have already handled.
Verify the signature#
- Read the raw request body as bytes or text. Do not parse and re-serialise the JSON first.
- Split the
CortexPay-Signatureheader intotand one or morev1values. - Reject the delivery if
tis more than 5 minutes away from your clock. - Compute HMAC-SHA256 of
<t>.<raw body>with your secret and compare it with eachv1in constant time.
import { createHmac, timingSafeEqual } from "node:crypto";
/** Verify a CortexPay delivery. Pass the raw request body, exactly as received. */
export function verifyCortexPayWebhook(rawBody: string, header: string | null, secret: string, toleranceSec = 300): boolean {
if (!header) return false;
let t = NaN;
const signatures: string[] = [];
for (const part of header.split(",")) {
const [k, v] = part.trim().split("=", 2);
if (k === "t") t = Number(v);
if (k === "v1" && v) signatures.push(v);
}
if (!Number.isInteger(t) || signatures.length === 0) return false;
if (Math.abs(Math.floor(Date.now() / 1000) - t) > toleranceSec) return false; // replayed or stale
const expected = createHmac("sha256", secret).update(`${t}.${rawBody}`).digest();
return signatures.some((s) => {
const got = Buffer.from(s, "hex");
return got.length === expected.length && timingSafeEqual(got, expected);
});
}
// Next.js route handler (app/api/cortexpay/route.ts)
export async function POST(req: Request) {
const raw = await req.text(); // never re-serialise the JSON before verifying
const ok = verifyCortexPayWebhook(raw, req.headers.get("CortexPay-Signature"), process.env.CORTEXPAY_WEBHOOK_SECRET!);
if (!ok) return new Response("invalid signature", { status: 400 });
const event = JSON.parse(raw) as { id: string; type: string; created_at: string; data: Record<string, unknown> };
// event.id is the same on every retry: skip ids you have already processed.
console.log(event.type, event.data);
return new Response(null, { status: 204 });
}The TypeScript SDK exports the same check as verifyWebhook; see the SDK.
Retries#
Any 2xx response counts as delivered. Anything else, including a redirect or no answer within 10 seconds, is retried after 30 s, 2 min, 10 min, 1 h, 6 h. After the sixth failed attempt the delivery is marked dead and the workspace is notified.
Delivery history
GET /api/webhooks/deliveries?webhookId=&status= lists recent attempts with their HTTP status; the Developer Console shows the same history per endpoint.
Event types#
| Type | When |
|---|---|
payment.authorized | All ten policy checks passed (or an owner approved) and CortexPay signed the payment authorization. authorized_by is "policy" for automatic authorizations and "owner" when an owner approved the request. |
payment.settled | The payment settled. In the sandbox this is a simulated ledger settlement; on a live network it is verified on chain. Sandbox deliveries carry simulated: true and no block_number. Live deliveries carry request_id and block_number. |
payment.rejected | The policy engine refused a payment. reason_code names the first failing check. |
payment.failed | An authorized payment did not complete: the service refused or failed after payment, settlement could not be verified, or the authorization expired unused. http_status is null when the failure did not come from the service response (settlement checks, expiry). |
approval.requested | A payment needs an owner's decision before it can be authorized. |
approval.decided | An approval request was approved, rejected, or expired without a decision. decision is "approved", "rejected" or "expired". |
service.delivered | The paid service answered successfully after payment. |
agent.created | An agent was registered in the workspace. account_address is the wallet the agent pays from: the workspace owner's wallet in a live workspace, a sandbox address in the sandbox, or null when the agent has no account. |
agent.paused | An agent was paused. Payments it had authorized but not yet settled were cancelled where CortexPay can still stop them. reason is null when none was given. still_settleable counts payments already signed and sent on-chain, which cannot be recalled and may settle until settleable_until (null when there are none); they keep counting against the budget. |
agent.resumed | A paused agent was resumed. |
agent.revoked | An agent was permanently revoked: permissions removed, accounts frozen (the owner can still withdraw), unsettled authorizations and pending approvals cancelled, its own services taken offline. reason is null when none was given. still_settleable and settleable_until mean the same as in agent.paused. |
policy.updated | An agent's spending policy changed. previous_policy_id is null when the agent had no policy before. |
budget.threshold | An agent's spend crossed its daily budget threshold. |
GET /api/webhooks/events returns this list with an example payload for every type, without authentication.
Endpoints#
- GET
/api/webhooks/eventsEvent types with example payloads, signature format and retry schedule.
Public
- GET
/api/webhooksEndpoints with 7-day delivery stats.
Key: webhooks:write
- POST
/api/webhooks/registerRegister { url, events[], description?, applicationId? }. Returns the whsec_ secret once.
Key: webhooks:write · session owner/admin · 20/min
- GET
/api/webhooks/:idOne endpoint.
Key: webhooks:write
- PATCH
/api/webhooks/:id{ url?, events?, description?, status?, applicationId? }.
Key: webhooks:write · session owner/admin · 60/min
- DELETE
/api/webhooks/:idRemove the endpoint and its delivery history.
Key: webhooks:write · session owner/admin
- POST
/api/webhooks/:id/testQueue and immediately attempt a signed webhook.test delivery.
Key: webhooks:write · session owner/admin · 10/min
- POST
/api/webhooks/:id/rotate-secretReplace the signing secret now; the new whsec_ is returned once.
Key: webhooks:write · session owner/admin · 10/min
- GET
/api/webhooks/deliveriesRecent deliveries (?webhookId=&status=&limit=), with status codes.
Key: webhooks:write