Accept a Payment
Protect an Express route with a $0.01 USDC payment on Solana. A request without payment receives an x402 challenge. A paid request receives the report and a settlement receipt.
- The client requests the resource.
- The API returns HTTP 402 and its payment requirements.
- The client authorizes payment and retries with its proof.
- The API asks the facilitator to verify and settle the payment.
- The facilitator returns the settlement result.
- After successful settlement, the API returns the resource and receipt.
Install
Use Node.js 20 or newer and a Solana address that you control for payouts. This server only needs the public address.
Create the Route
Save this as server.mjs. The price comes from the server configuration on every request, including requests that already carry a payment header.
The server verifies and settles before delivering the report. Pass the seller's requirement explicitly to both calls so the amount, recipient, asset, and network remain tied to your offer.
Start and Check
In another terminal:
Expect 402 Payment Required, a PAYMENT-REQUIRED header, and an accepts entry with amount 10000. This check requests a price and spends nothing. If requirements cannot be loaded, the server returns 503; check access to the facilitator's /supported endpoint.
Use the Node buyer example against this URL to make a paid request. A successful response has status 200, the report, and a PAYMENT-RESPONSE header containing the settlement result.
Serve Your Own Result
Replace the sample report with your service's output. Validate inputs before taking payment. For work that can fail after settlement, persist the payment transaction and result under a stable operation ID so a retry can recover the existing purchase.
Set RESOURCE_URL to the public HTTPS URL when deploying. Browser callers also need CORS configured to allow PAYMENT-SIGNATURE and expose PAYMENT-REQUIRED and PAYMENT-RESPONSE.
For metered use across requests, continue with Tabs for Sellers.