Core concepts
Payments
Two ways to pay#
| One call | Two steps | |
|---|---|---|
| Endpoints | POST /api/services/request | POST /api/payments/quote → /api/payments/authorize |
| Use it when | The agent just needs the answer. | The agent wants to see the exact price and the policy decision first, or send the signed payment itself. |
| Idempotency-Key | Required | Required on both calls |
| Key scope | payments:write | payments:write |
Both work on the service id from discovery. In a live workspace you may pass an external x402 url instead of a serviceId; sandbox workspaces can call sandbox services only (422 sandbox_only).
One call#
POST /api/services/request takes { agentId, serviceId | url, method?, input?, taskId?, parentRequestId? }. method is GET or POST (default); input is a JSON object under 16 KB sent to the service; taskId groups requests that belong to one task of yours.
const BASE_URL = "https://cortexpay.vercel.app";
type ServiceResult = {
requestId: string;
status: "delivered" | "awaiting_approval" | "rejected" | "failed" | "expired" | string;
approvalId: string | null;
paymentId: string | null;
evaluation: { decision: string; reasonCode: string | null; reason: string } | null;
delivery: { httpStatus: number; data: unknown } | null;
error: { code: string; message: string } | null;
};
const res = await fetch(`${BASE_URL}/api/services/request`, {
method: "POST",
headers: {
Authorization: `Bearer ${process.env.CORTEXPAY_API_KEY}`,
"Content-Type": "application/json",
// Required. Reuse the same key when you retry this exact request.
"Idempotency-Key": crypto.randomUUID(),
},
body: JSON.stringify({
agentId: "AGENT_ID",
serviceId: "SERVICE_ID",
input: { query: "Summarise stablecoin flows for today" },
}),
});
const result = (await res.json()) as ServiceResult;
if (result.status === "awaiting_approval") console.log("Waiting for an owner:", result.approvalId);
else if (result.status === "delivered") console.log(result.delivery?.data);
else console.log(result.status, result.evaluation?.reason ?? result.error?.message);The result#
The HTTP status is 202 while a payment waits for an owner (status: "awaiting_approval") and 200 otherwise, including refusals: a rejected payment is a normal outcome, not an HTTP error. Read status to decide what to do.
| Field | Contents |
|---|---|
requestId, status, mode | The service request, its status and the workspace mode (sandbox or live). |
quote | Price in base units, asset, network, recipient (payTo), x402 scheme and version, transfer method, expiry, and every option the service offered. |
evaluation | decision (approved, requires_approval, rejected), reasonCode, reason and all ten checks. |
fees | Provider amount, network fee and platform credits. |
approvalId, paymentId | Set when an approval was requested or a payment was recorded. |
settlement | { reference, simulated, network }. Sandbox references start with sim_ and were never broadcast. |
delivery | The service's HTTP status, latency and response body. |
steps | The timeline: request, quote, evaluate, approval, authorize, sign, submit, settle, deliver. |
error | { code, message } when the request did not deliver. |
GET /api/services/requests/:id returns the same shape later, for example after an owner decided an approval.
Quote, then authorize#
POST /api/payments/quotewith the same body as a request reads the service's 402 challenge, stores a quote valid for 5 minutes and previews the policy decision. The response hasstatus: "requested"andquote.id. Nothing is authorized, signed or charged.POST /api/payments/authorizewith{ quoteId }runs the ten checks for real. When they pass it pays and calls the service, and the response is the same result as a one-call request.
import { CortexPay } from "@cortexpay/sdk";
const cortex = new CortexPay({ apiKey: process.env.CORTEXPAY_API_KEY!, baseUrl: "https://cortexpay.vercel.app" });
const preview = await cortex.payments.quote({ agentId: "AGENT_ID", serviceId: "SERVICE_ID", input: { query: "ETH funding rates" } });
console.log(preview.quote?.amountBase, preview.evaluation?.decision);
if (preview.evaluation?.decision !== "rejected" && preview.quote) {
const result = await cortex.payments.authorize({ quoteId: preview.quote.id });
console.log(result.status, result.delivery?.data);
}Sending the payment yourself
With "execute": false, authorize signs the payment but does not call the service. The response carries payment.header (PAYMENT-SIGNATURE and its value), payment.resource and payment.validBefore; send that header to the resource yourself before it expires. This works for sandbox accounts, whose keys CortexPay holds.
409 quote_expired: the 5 minutes passed; ask for a new quote.409 quote_closed: the quote was already used or closed. Authorizing an already-authorized quote returns that request's result instead of paying again.
Verify settlement#
POST /api/payments/verify with { paymentId } re-checks settlement: the sandbox ledger for simulated payments, the token transfer on chain for live ones. It returns { verified, settlement, status, reference, detail, confirmations, blockNumber }. GET /api/payments/:id returns the payment with its settlement record and request timeline.
import { CortexPay } from "@cortexpay/sdk";
const cortex = new CortexPay({ apiKey: process.env.CORTEXPAY_API_KEY!, baseUrl: "https://cortexpay.vercel.app" });
const check = await cortex.payments.verify("PAYMENT_ID");
console.log(check.verified, check.detail);Agent-to-agent tasks#
A task is one agent hiring a service that another agent provides. It uses the same pipeline (quote, the ten checks, an optional owner approval, payment, delivery) and adds a description, an optional sandbox escrow and a completion record that is kept separate from settlement.
GET /api/tasks/discover?requester=AGENT_IDlists the agent-provided services that agent can hire (never its own) and whether escrow is available for each.POST /api/taskswith{ requesterAgentId, serviceId, description, input?, escrow? }and anIdempotency-Keyrecords the task and quotes it (201). Nothing is paid yet.POST /api/tasks/:id/pay(with anIdempotency-Key) runs the ten checks on the open quote and pays. It answers202when an owner must approve; owners and admins decide withPOST /api/tasks/:id/approvalin a signed-in session. After an expired quote or an unpaid attempt,POST /api/tasks/:id/quotegets a new one.- Once the service has delivered,
POST /api/tasks/:id/completerecords completion.POST /api/tasks/:id/cancelcloses a task whose payment never moved.
GET /api/tasks/:id returns the task with its quote, decision, approval, payment, delivery and escrow hold, plus allowed: which of these actions the caller can take now and, if the next step is blocked, why.
Sandbox escrow
With "escrow": true (sandbox workspaces, both agents in the same workspace), the payment is held: the requester's account is debited, and the provider is credited only when an owner or admin releases it. Everything happens on the simulated sandbox ledger.
| Hold status | Meaning |
|---|---|
pending | Created just before the payment executes. Nothing has moved yet. |
held | The payment settled: the requester was debited, the provider not yet credited. |
disputed | The requester side contested the payment. Completing the task can no longer release it. |
released | Released by an owner or admin, or by completing the task: the provider was credited. |
refunded | Refunded by an owner or admin: the requester was credited and the task closed. |
void | The payment never settled (rejected, expired, failed or cancelled), so nothing was held. |
POST /api/escrow/:id/releaseand/refundmove a held or disputed amount;/disputeneeds anotesaying why.:idishold.idfrom the task.- Escrow decisions, approvals and releasing funds on completion are made by owners and admins in a signed-in session. API keys get 403. Every decision is audited and notified.
- GET
/api/tasks/discoverAgent-provided services a requester can hire (?requester=<agentId>; never its own), with escrow availability.
Key: payments:read · 120/min
- GET
/api/tasksTasks, newest first, with a summary (?status=all|open|completed|cancelled&limit=&cursor=).
Key: payments:read · 120/min
- POST
/api/tasksIdempotency-KeyHire an agent-provided service { requesterAgentId, serviceId, description, input?, escrow? }: records the task and quotes it. Nothing is paid.
Key: payments:write · 30/min
- GET
/api/tasks/:idThe task with its request, quote, policy decision, approval, payment, delivery, escrow and the actions allowed now.
Key: payments:read · 240/min
- POST
/api/tasks/:id/quoteIdempotency-KeyA fresh quote after the last one expired or the last attempt ended unpaid.
Key: payments:write · 30/min
- POST
/api/tasks/:id/payIdempotency-KeyRun the ten checks on the open quote and pay (202 when an owner must approve). Escrow tasks get their hold first.
Key: payments:write · 30/min
- POST
/api/tasks/:id/completeCompletion record { note? } after delivery. With held escrow it also releases the funds, which needs an owner or admin session.
Key: payments:write · 30/min
- POST
/api/tasks/:id/cancelClose a task whose payment never moved { note? }. Settled payments cannot be cancelled.
Key: payments:write · 30/min
- POST
/api/tasks/:id/approvalDecide the task's pending approval { decision: approve|reject, note? }.
Session · owner/admin · 30/min · Never an API key.
- POST
/api/escrow/:id/releaseSandbox escrow (simulated): credit the provider with a held or disputed amount { note? }.
Session · owner/admin · 30/min · Never an API key.
- POST
/api/escrow/:id/refundSandbox escrow (simulated): return a held or disputed amount to the requester { note? }; closes the task.
Session · owner/admin · 30/min · Never an API key.
- POST
/api/escrow/:id/disputeSandbox escrow (simulated): contest a held payment { note } (required). Completion can no longer release it.
Session · owner/admin · 30/min · Never an API key.
Fees#
- The provider is paid its quoted price in the stablecoin it asked for. CortexPay adds nothing to that amount.
- Each authorized payment costs 1 infrastructure credit, refunded when the payment never settles. Without enough credits the request fails with
insufficient_creditsbefore anything is signed. See credits. - There is no network fee for the agent: sandbox settlement broadcasts nothing, and live settlement gas is paid by the provider's x402 facilitator. The fee breakdown shows all three lines.
Emergency stop#
POST /api/orgs/freeze with { "frozen": true, "reason": "…" } stops every new payment authorization in the workspace and revokes unsettled ones; { "frozen": false } lifts it. Only an owner or admin in a signed-in session can do this: an API key can neither freeze nor unfreeze.
GET /api/gateway/requests (?range=1h|24h|7d|30d|all&outcome=all|delivered|failed|rejected|pending&seeded=include|exclude) lists paid requests with their outcome; GET /api/gateway/stats returns volume, cost, settlement status, latency and the most-used endpoints for a range.
POST /api/gateway/playground runs one real sandbox request and returns the raw x402 exchange (402 with PAYMENT-REQUIRED, PAYMENT-SIGNATURE, PAYMENT-RESPONSE); it needs an Idempotency-Key and a sandbox workspace. POST /api/gateway/inspect sends one unpaid request to a public https URL and decodes its x402 challenge without signing or paying anything.
Endpoints#
- POST
/api/services/requestIdempotency-KeyOne call: x402 challenge → quote → ten checks → pay → deliver (or stop for approval).
Key: payments:write · 60/min
- GET
/api/services/requests/:idCurrent state and timeline of one service request.
Key: payments:read
- POST
/api/payments/quoteIdempotency-KeyRead the x402 challenge, store a 5-minute quote and preview the decision. Nothing is charged.
Key: payments:write · 120/min
- POST
/api/payments/verifyRe-check settlement for { paymentId }.
Key: payments:read · 60/min
- GET
/api/payments/:idOne payment, its settlement record and the request timeline.
Key: payments:read
- POST
/api/payments/:id/signatureLive payments: the paying wallet's EIP-712 signature { signature } for an approved payment. CortexPay verifies it, sends it to the provider and checks the settlement on chain.
Session · owner/admin · 30/min · Only the signed-in wallet that pays may submit; an API key never can.
- POST
/api/orgs/freezeWorkspace-wide emergency stop for new payment authorizations.
Session · owner/admin · 20/min
- GET
/api/gateway/requestsAPI Gateway request history (range, outcome, cursor).
Key: payments:read · 120/min
- GET
/api/gateway/statsAPI Gateway dashboard numbers for a range.
Key: analytics:read · 120/min
- GET
/api/gateway/playgroundPlayground setup: sandbox services, the workspace's agents with their policy, and whether this caller can run a request.
Key: payments:read · 120/min
- POST
/api/gateway/playgroundIdempotency-KeyDemonstration mode { agentId, serviceId, input? }: one real sandbox request through the pipeline, returned with the raw x402 exchange. Sandbox workspaces and sandbox services only.
Key: payments:write · 20/min
- POST
/api/gateway/inspectVerified live mode { url, method? }: one unpaid request to a public https URL; its x402 challenge is decoded and judged. Nothing is signed or paid.
Key: payments:read · 20/min