Build pay-per-request APIs with x402 by linking price, payment verification, idempotent execution, delivery evidence, and merchant reconciliation.
Meta Description: Build pay-per-request APIs with x402 by linking price, payment verification, idempotent execution, delivery evidence, and merchant reconciliation.
Slug: pay-per-request-apis-x402
A merchant can monetize a machine-to-machine service with x402 by attaching a payment requirement to an HTTP resource, verifying the buyer's payment, and releasing the response only after the requirement is satisfied. That mechanism is necessary, but it is not the whole product.
A production pay-per-request API also needs an enforceable definition of the request being sold. The merchant must bind one price to one input, one payment intent, one execution decision, one delivery record, and one remedy if delivery fails. Without that binding, a paid endpoint can collect funds yet remain impossible to operate reliably.
The useful mental model is therefore not “put a paywall in front of an API.” It is “treat every billable call as a compact order.” HTTP 402 is the admission step. The request ledger is what makes the service recoverable, auditable, and economically measurable.
Start by defining the billable request
“One API call” sounds precise until the service has variable inputs, retries, partial results, or downstream dependencies. Before choosing middleware, define the commercial unit.
For a data-enrichment endpoint, the unit might be one accepted company domain that returns a validated company profile. For image generation, it might be one completed generation at a stated resolution. For an MCP tool, it might be one successful tool invocation within declared input limits. These units are not interchangeable with raw HTTP requests: a malformed request, health check, polling request, or delivery retry should not automatically become another sale.
A billable request contract should establish at least:
Contract element | What the merchant must decide |
|---|---|
Product identity | Which endpoint, tool, model, dataset, or operation is being sold? |
Accepted input | Which fields, sizes, formats, and validation rules apply? |
Deliverable | What response or entitlement counts as delivery? |
Price authority | Which server-generated quote controls the amount, asset, recipient, and expiry? |
Validity window | How long may the buyer use the quoted terms? |
Execution limit | Does one payment authorize one execution, one delivered result, or a bounded session? |
Failure remedy | Will the merchant retry, issue credit, refund, or send the case for review? |
Evidence | Which records prove authorization, payment, execution, and delivery? |
This contract prevents a common category error. Payment answers whether the buyer satisfied the stated consideration. It does not answer whether the submitted input was valid, whether the service executed, whether the result met the stated format, or whether the client received it.
Per-request access works best when the unit is independently useful and can be priced before execution. It is less suitable when work has an unknown upper cost, needs prolonged negotiation, or produces a subjective outcome that cannot be described in machine-readable acceptance terms. In those cases, prepaid credits, staged authorization, or a subscription may produce a cleaner commercial contract.
The 402 exchange is admission, not fulfillment
The official x402 seller documentation describes the protocol-level pattern: a resource server protects an HTTP route, returns payment requirements when a request lacks valid payment, and processes a retried request carrying a payment payload. The seller may use a facilitator or implement the relevant verification and settlement functions itself.
The actors have distinct responsibilities:
The machine client requests the resource.
The resource server returns
402 Payment Requiredwith acceptable payment terms.The client checks those terms against its wallet balance and spending policy.
The client authorizes a payment and retries with the required payment data.
The resource server or facilitator verifies that the payment matches the quoted terms.
Settlement is submitted or confirmed according to the selected scheme and network.
The merchant application decides whether to execute and deliver the service.
The last step belongs to the merchant. An x402 facilitator can reduce the burden of chain-specific verification and settlement, but it does not run the merchant's model, validate a dataset, generate a report, or prove that a response reached the buyer. The x402 facilitator model is part of the payment path, not a substitute for service fulfillment.
That boundary matters because the two systems can fail independently. Payment may verify even if compute fails. Compute may finish after the client connection closes. Settlement records may arrive after response delivery. A production API does not collapse those conditions into a single boolean named paid.
Give every paid call a request ledger
The minimum durable object for a pay-per-request service is a correlation record. It can live in an order table, request ledger, or event stream, but it must connect the commercial and technical histories of one logical purchase.
Ledger field | Purpose |
|---|---|
| Stable merchant identifier for the logical purchase |
| Buyer- or merchant-scoped key used to resume rather than duplicate work |
| Detects reuse of the key with materially different input |
| Preserves price, asset, recipient, network, and expiry offered to the buyer |
| Connects verification and settlement evidence to the request |
| Separates required, submitted, verified, settled, rejected, and expired states |
| Separates queued, running, succeeded, failed, and cancelled work |
| Separates ready, returned, acknowledged, and delivery-unknown outcomes |
| Identifies the exact response or artifact produced |
| Records retry, credit, refund, or manual review |
timestamps | Makes latency, expiry, and incident reconstruction measurable |
These fields should not all be controlled by the same actor. The resource server owns request validation and service execution. The payment verifier owns payment evidence. The settlement network owns transaction finality under its rules. The merchant's order system owns the correlation between them. The client may supply an idempotency key, but the merchant must scope and enforce it.
The ledger also defines the fulfillment gate. A service handler should run only when the merchant has trusted evidence that the exact requirement was satisfied: the intended recipient, amount, asset, network, quote, expiry, and request binding must match. A transaction hash by itself is not enough because it does not state that the transaction satisfied this order under the merchant's rules.
A $0.02 enrichment call, end to end
Consider a hypothetical endpoint that charges $0.02 for a company-enrichment result. The number is illustrative, not a recommendation.
The client sends:
The server validates the syntax before requesting payment. If the domain is invalid, it returns a client error without creating a payable order. For a valid input, it creates request_id=req_731, hashes the normalized input, and issues a short-lived requirement for the accepted asset and recipient. The unpaid response contains enough machine-readable information for the client to decide whether the purchase is permitted.
The agent evaluates the quote. Its policy might allow enrichment services from approved providers up to $0.05 per call and $2.00 per research task. If approved, the agent prepares payment and retries the same logical request with the same idempotency key.
The server verifies the submitted payment against req_731, rather than merely checking for any transfer to the merchant wallet. After verification, it atomically changes the request from payment_required to payment_verified and reserves the right to execute once. The enrichment worker then runs.
If execution succeeds, the merchant stores the response or a durable result reference, computes a digest, and marks the execution successful. It returns the result and records delivery as returned. If the connection closes before the client receives the body, the result remains retrievable with the same idempotency key. A retry returns the stored result; it does not create another charge or rerun the enrichment job.
Later, the merchant reconciles the payment reference and settlement record with the request ledger. The operational question is no longer “Did this wallet transfer?” It is “For every paid request, is there exactly one valid delivery or an open remedy?”
That invariant is more useful than a payment count because it catches both revenue leakage and customer harm.
Retries must resume state, not restart commerce
Machine clients retry aggressively because networks time out and upstream tools fail. Retry behavior must therefore be part of the paid contract, not an afterthought.
An idempotency key identifies one logical purchase. When a request repeats with the same key and same normalized input, the merchant should return the current state or the stored result. If the key appears with different input, the request should be rejected. Otherwise, a buyer could accidentally or deliberately attach a paid authorization to a different job.
Payment replay protection and service idempotency are separate controls. Replay protection prevents the same payment proof from authorizing multiple purchases. Service idempotency prevents one authorized purchase from running the paid work multiple times. A system needs both.
Four retry cases deserve explicit tests:
The client never received the 402 response. No payment was authorized; the logical request can be resumed or requoted.
The client paid, but the paid retry timed out before verification returned. The merchant should inspect payment state using the same request identifier, not demand immediate repayment.
Payment verified and work completed, but the response timed out. Return the stored result or a result locator on retry.
Payment verified, but work is still running. Return an unambiguous pending state or asynchronous retrieval path instead of starting another execution.
Quotes also need expiry behavior. If a quote expires before authorization, the merchant can issue new terms. If payment is submitted near expiry, the verifier and merchant need a deterministic rule for which timestamp and state control acceptance. Ambiguity at this boundary creates support cases that are difficult to resolve from a chain transaction alone.
Paid does not mean delivered
A confirmed payment followed by failed service execution is not a protocol paradox. It is a merchant fulfillment failure, and the commercial policy should already say what happens.
The correct remedy depends on the product and failure class:
Automatic retry fits transient internal failures when repeat execution is safe and the result remains useful.
Service credit can fit a continuing merchant relationship, but it is less useful for accountless buyers that may never return.
Refund may be appropriate when no deliverable was produced and the payment rail supports a controlled return flow.
Manual review is necessary when execution partly completed, the output is disputed, or transaction evidence conflicts with application records.
The merchant should distinguish system failure from product dissatisfaction. If the contract promises a syntactically valid search result and one was delivered, the buyer's disagreement with its business value is not the same as a timeout before any result existed. Machine-readable terms should state the delivery standard clearly enough for an agent to assess this distinction before paying.
There is also a reverse ambiguity: the service may return a result, but the client may claim it never arrived. Keeping a result digest, request timestamps, response status, and retrievable artifact can support investigation. It cannot prove that every downstream client used the result, but it provides stronger evidence than a payment record alone.
Refund and retry operations must themselves be idempotent. An incident handler should not be able to issue two refunds because a webhook was delivered twice, nor should an automated recovery process both refund and later release the original result without recording that policy outcome.
Price the request, not just the endpoint
Per-request pricing exposes usage directly, but fine granularity does not guarantee good economics. The merchant needs a contribution-margin model for the billable unit.
For the hypothetical enrichment call:
Suppose a request sells for $0.02; data and compute cost $0.011, infrastructure and expected retry cost total $0.003, and payment plus operational overhead averages $0.002. The illustrative contribution margin is $0.004, or 20% of revenue. A small change in upstream data cost or failure rate could erase it. The merchant should measure the inputs before treating the headline price as viable.
This is where alternatives matter:
Model | Strong fit | Tradeoff |
|---|---|---|
Per-request payment | Independent, irregular, machine-triggered purchases | Payment and reconciliation overhead touches every unit |
Prepaid credits | High-frequency use within one platform | Requires account or balance management and locks funds in advance |
Subscription | Predictable recurring demand | Poor fit for agents needing occasional access or provider choice |
Batched settlement | Very small, frequent calls with an established relationship | Adds credit, aggregation, or delayed-settlement risk |
Per-request economics are strongest when the buyer values immediate, account-light access; the unit has a knowable marginal cost; and the price comfortably exceeds execution and failure overhead. If calls are extremely cheap and frequent, batching or credits may be more efficient. If usage is stable, a subscription may reduce transaction and accounting work. x402 expands the available model; it does not make every endpoint a sensible micropayment business.
Choose the GOAT surface after the contract is defined
GOAT Flow is a commerce product with Checkout, QuickPay, API Payments, and merchant operations. x402 is the broader HTTP payment protocol used by relevant surfaces. Merchants should keep that product/protocol distinction clear when selecting an implementation.
There are three useful categories for the API case:
Generic x402 resource-server integration. This is appropriate when a merchant wants direct control over route middleware, verification or facilitator selection, service execution, and its own order ledger. The merchant still owns idempotency, delivery, remedies, and accounting.
GOAT Flow authenticated merchant order path. This fits an application that wants to create and track merchant-side payment requirements and connect them to order and reconciliation records. According to the current GOAT Flow merchant guide, public merchant onboarding uses DIRECT transfers to the configured receiving address. Server-side credentials and trusted status checks belong in the backend; browser success alone should not authorize fulfillment.
GOAT Flow's current paid API route profile. This fits fixed-price protected endpoints that use the documented challenge, direct-transfer verification, and signed Payment-Receipt path. Merchant middleware verifies the receipt before granting access. This profile is described in GOAT documentation alongside API Payments, but it should not be presented as a universal x402 or generic MPP wire format.
The selection rule is operational:
Choose route-level protection when the paid resource is a stable endpoint and the application can fulfill immediately after trusted receipt verification.
Choose an order-oriented path when the service needs a durable merchant order, asynchronous execution, broader status handling, or reconciliation across multiple events.
Keep a custom x402 integration when protocol portability and control justify owning more of the merchant system.
In all cases, the live environment is authoritative for enabled networks, assets, recipients, limits, fees, capabilities, and receipt policies. Repository types, test fixtures, or cached manifests do not prove that a capability is enabled for a public merchant deployment.
Launch when the ledger closes
A pay-per-request API is ready when success and failure paths produce a complete, reconcilable history. Before launch, test these acceptance criteria:
Invalid input is rejected before the buyer is asked to pay.
The payment requirement is bound to the intended route, input or order, amount, asset, recipient, network, and expiry.
Agent spending policy can reject the quote before authorization.
Trusted verification occurs before service execution or delivery.
The same idempotency key and input cannot create duplicate charges or duplicate work.
The same payment proof cannot authorize another logical purchase.
A completed result can be retrieved after a client timeout without repaying.
A paid execution failure enters exactly one documented remedy path.
Refund, credit, retry, and webhook handlers are idempotent.
Every payment record reconciles to one delivered result or one unresolved exception.
Runtime configuration is checked rather than inferred from documentation examples.
Metrics expose payment conversion, verification latency, execution latency, delivery failures, retries, refunds, and contribution margin.
The decisive metric is not simply the number of paid calls. It is the percentage of paid requests that close with one verified delivery or an explicit remedy, at a positive contribution margin.
Once that contract and ledger are in place, x402 can do what it is well suited to do: let a machine discover a price at the HTTP boundary, authorize payment programmatically, and access a resource without forcing every purchase through a conventional subscription checkout. The merchant remains responsible for turning that authorization into a dependable product.
For merchants ready to evaluate order records, API payment routes, and connected commerce operations, explore GOAT Flow against the launch criteria above.
Frequently Asked Questions
Does x402 replace API keys for a paid endpoint?
Not necessarily. x402 proves that a payment requirement was satisfied. An API key or signed identity credential may still be needed for authorization, customer-specific limits, persistent history, privileged data, or regulatory controls.
Does every x402 API need a facilitator?
No. A resource server can implement verification and settlement functions itself. A facilitator is an optional service boundary that can reduce chain-specific integration work, but the merchant still owns execution, delivery, and remedies.
Should a merchant charge again when an agent retries?
Not when the retry represents the same logical purchase. The merchant should use an idempotency key, confirm that the input matches, and return the existing state or stored result. A genuinely new request may require a new payment.
What should happen if payment succeeds but the API fails?
The merchant should follow a predefined policy: retry safely, provide a useful credit, refund, or escalate for review. Payment verification alone does not establish that the service was delivered.
Are pay-per-request APIs always cheaper than subscriptions?
No. They can reduce commitment for irregular buyers, but payment, settlement, retries, and reconciliation add per-unit overhead. High-frequency or predictable use may be more economical through credits, batching, or subscriptions.
Is GOAT Flow the same as x402?
No. x402 is a broader HTTP payment protocol. GOAT Flow is a commerce product that uses x402 in relevant order and API payment surfaces and adds merchant-facing records and operations.



