# API reference Source: https://docs.x402go.online/api-reference/overview Base URL, authentication, and the request and response formats for the x402Go facilitator endpoints. The x402Go facilitator has three endpoints. The x402 SDKs (`HTTPFacilitatorClient`) call them for you, so most integrations never construct these requests by hand. This page is for when you need the exact formats, are debugging, or are calling the API directly. ## Base URL ```text theme={null} https://api.x402go.online ``` ## Authentication Send your API key in the `x-api-key` header on `/verify` and `/settle`. Get the key from your [x402Go dashboard](https://x402go.online/dashboard). `Authorization: Bearer YOUR_X402GO_API_KEY` is also accepted. ```http theme={null} x-api-key: YOUR_X402GO_API_KEY ``` Keep the key on your backend, never in browser or mobile code. `GET /supported` is public, and sending the key there is harmless. A request with a missing or unknown key returns `401`: ```json theme={null} { "error": "invalid_api_key" } ``` Your key is tied to your account. A payment is accepted only if its `payTo` is your own payment address. Anything else is rejected with `invalid_pay_to`. ## Choosing a network Every endpoint also works under a network prefix, for example `POST /celo/settle` or `GET /celo-sepolia/supported`. The prefix is optional because the network is also in the payment itself. If you use one, it must match the payment's network, or the request fails with `invalid_network`. A network can be written as a name or as a CAIP-2 identifier: | Network | Name (v1) | Identifier (v2) | | - | - | - | | Celo Mainnet | `celo` | `eip155:42220` | | Celo Sepolia (testnet) | `celo-sepolia` | `eip155:11142220` | ## Endpoints | Method | Endpoint | Description | | - | - | - | | `GET` | `/supported` | List the x402 versions, networks, and tokens you can use. | | `POST` | `/verify` | Check a payment against your payment requirements. No funds move. | | `POST` | `/settle` | Complete a payment on-chain. Funds are collected and split in one transaction. | ## GET /supported Returns what the facilitator accepts right now. Check it before you configure a token. ```bash theme={null} curl https://api.x402go.online/supported ``` ```json theme={null} { "kinds": [ { "x402Version": 2, "scheme": "exact", "network": "eip155:42220", "extra": { "defaultAsset": { "asset": "0xcebA9300f2b948710d2653dD7B07f33A8B32118C", "symbol": "USDC", "decimals": 6, "name": "USDC", "version": "2", "assetTransferMethod": "eip3009" }, "supportedAssets": [ { "asset": "0xcebA9300f2b948710d2653dD7B07f33A8B32118C", "symbol": "USDC", "decimals": 6, "name": "USDC", "version": "2", "assetTransferMethod": "eip3009" } ] } }, { "x402Version": 1, "scheme": "exact", "network": "celo", "extra": { "...": "..." } } ], "signers": { "eip155:42220": ["0x..."] } } ``` | Field | Meaning | | - | - | | `kinds[].x402Version`, `network` | The protocol version and network this entry covers. v2 uses identifiers like `eip155:42220`, v1 uses names like `celo`. | | `extra.supportedAssets` | The tokens you can accept on that network. | | `asset`, `decimals`, `symbol` | The token's contract address, decimals, and ticker. | | `name`, `version` | Values clients need to sign payments for this token. Copy them exactly into your server configuration. | | `assetTransferMethod` | `eip3009` or `permit2`. Use the method listed for the token. | | `signers` | The addresses that submit transactions. | Tokens appear here only when x402Go has set a fee for them. A newly added token can take about a minute to show up. v1 entries list only `eip3009` tokens, because `permit2` needs v2. ## Fees and minimum prices x402Go deducts a fee from each settled payment. The customer pays the full amount in your payment requirements, and your payout wallet receives that amount minus the applicable fee. For USD-denominated tokens, the fee is **\$0.0035 per transaction**. For cNGN settlement, the fee is **₦4.80 per transaction**. The requested amount must be greater than the token's fee. Amounts equal to or below the fee fail with `amount_below_fee`. See the [current token fees and examples](https://x402go.online/#tokens) when choosing an asset. Because payment amounts use each token's smallest unit, use the token's `decimals` value from `/supported` to convert the minimum price correctly. An unknown network returns `400`: ```json theme={null} { "success": false, "error": "unknown_network", "supported": ["celo", "celo-sepolia"] } ``` ## POST /verify Checks that a payment is valid and matches your requirements. Nothing is submitted on-chain. **Request** ```json theme={null} { "x402Version": 2, "paymentPayload": { "x402Version": 2, "accepted": { "scheme": "exact", "network": "eip155:42220", "asset": "0xcebA9300f2b948710d2653dD7B07f33A8B32118C", "amount": "10000", "payTo": "0xYourPaymentAddress", "maxTimeoutSeconds": 60, "extra": { "name": "USDC", "version": "2" } }, "payload": { "signature": "0x...", "authorization": { "from": "0xPayer", "to": "0xYourPaymentAddress", "value": "10000", "validAfter": "0", "validBefore": "1792061802", "nonce": "0x..." } } }, "paymentRequirements": { "scheme": "exact", "network": "eip155:42220", "asset": "0xcebA9300f2b948710d2653dD7B07f33A8B32118C", "amount": "10000", "payTo": "0xYourPaymentAddress", "maxTimeoutSeconds": 60, "extra": { "name": "USDC", "version": "2" } } } ``` `paymentRequirements` must match `paymentPayload.accepted`. Amounts are in the token's smallest unit. **Response** ```json theme={null} { "isValid": true, "payer": "0xPayer" } ``` ```json theme={null} { "isValid": false, "invalidReason": "amount_below_fee", "payer": "0xPayer" } ``` An invalid payment still returns `200`. Check `isValid`. > [accordion] Permit2 payments (v2 only) > > Tokens whose `assetTransferMethod` is `permit2` use a different `payload`. The payer must have approved Permit2 on the token beforehand, or verification fails with `permit2_allowance_required`. > > ```json theme={null} > "payload": { > "signature": "0x...", > "permit2Authorization": { > "from": "0xPayer", > "permitted": { "token": "0xToken", "amount": "100000000" }, > "spender": "0x402085c248EeA27D92E8b30b2C58ed07f9E20001", > "nonce": "...", > "deadline": "...", > "witness": { "to": "0xYourPaymentAddress", "validAfter": "0" } > } > } > ``` > > Set `extra.assetTransferMethod` to `"permit2"` in both `accepted` and `paymentRequirements`. > [accordion] x402 v1 format > > v1 puts `scheme` and `network` on the payload, and requirements use `maxAmountRequired` instead of `amount`. v1 supports `eip3009` tokens only. > > ```json theme={null} > { > "x402Version": 1, > "paymentPayload": { > "x402Version": 1, > "scheme": "exact", > "network": "celo", > "payload": { "signature": "0x...", "authorization": { "...": "..." } } > }, > "paymentRequirements": { > "scheme": "exact", > "network": "celo", > "maxAmountRequired": "10000", > "resource": "https://api.example.com/premium", > "description": "Premium content", > "mimeType": "application/json", > "payTo": "0xYourPaymentAddress", > "maxTimeoutSeconds": 60, > "asset": "0xcebA9300f2b948710d2653dD7B07f33A8B32118C", > "extra": { "name": "USDC", "version": "2" } > } > } > ``` ## POST /settle Completes the payment on-chain. The request body is the same as `/verify`. x402Go checks the payment again before it submits anything, because things can change between the two calls. **Response** ```json theme={null} { "success": true, "transaction": "0xTransactionHash", "network": "eip155:42220", "payer": "0xPayer" } ``` ```json theme={null} { "success": false, "errorReason": "authorization_used", "transaction": "", "network": "eip155:42220", "payer": "0xPayer" } ``` How settlement behaves: * **One transaction.** The payment is collected and split between your payout wallet and the fee in a single transaction. Your first payment on a network also creates your payment address on-chain, so it takes a little longer. * **Timeouts.** Settlement can wait up to about a minute for confirmation. Set your HTTP timeout above 60 seconds, for example 90. * **Retries are safe for successful payments.** Sending the same payment again returns the original result. A failed attempt can be retried. * **If the response has a `transaction` but `success` is `false`,** the transaction may still land. Look the hash up on Celoscan before you retry or refuse the request. ## Status codes | Code | Meaning | | - | - | | `200` | The request was processed. Check `isValid` or `success`, because invalid or failed payments also return `200`. | | `400` | The body couldn't be read, with `invalid_payload`, or the network is unknown on `/supported`. | | `401` | The API key is missing or invalid. | | `500` | Unexpected error, with `unexpected_verify_error` or `unexpected_settle_error`. Safe to retry. | ## Error reasons `invalidReason` (from `/verify`) and `errorReason` (from `/settle`) use the same values. | Reason | What to do | | - | - | | `invalid_payload` | The request body is malformed. | | `invalid_network` | The network isn't supported, or the URL prefix and the payment disagree. | | `invalid_payment_requirements` | `paymentRequirements` doesn't match what the payer signed. Send the same requirements you served. | | `invalid_pay_to` | `payTo` isn't your payment address. Copy it again from the dashboard. | | `unsupported_scheme` | Only `exact` is supported. | | `unsupported_asset` | The token isn't listed by `/supported` for that network. | | `unsupported_transfer_method` | `assetTransferMethod` doesn't match the token's method in `/supported`. | | `token_not_supported` | x402Go hasn't set up fees for this token. | | `amount_below_fee` | The price must be higher than the fee. Raise it. | | `invalid_exact_evm_payload_authorization_value` | The signed amount doesn't equal the required amount. | | `invalid_exact_evm_payload_recipient_mismatch` | The payment names a different recipient than `payTo`. | | `invalid_exact_evm_payload_authorization_valid_before` | The authorization expires too soon or has expired. | | `invalid_exact_evm_payload_authorization_valid_after` | The authorization isn't valid yet. | | `invalid_exact_evm_payload_signature` | The signature is wrong. Check that `name` and `version` match `/supported`. | | `unsupported_signature_format` | EIP-3009 payments need a standard 65-byte signature. | | `authorization_used` | This payment was already used. The payer needs to sign a new one. | | `insufficient_funds` | The payer doesn't hold enough of the token. | | `invalid_permit2_spender` | The Permit2 spender isn't the x402 Permit2 contract. | | `permit2_token_mismatch` | The Permit2 token doesn't match the requirements. | | `permit2_deadline_expired` | The Permit2 payment has expired. | | `permit2_nonce_used` | This Permit2 payment was already used. | | `permit2_allowance_required` | The payer must approve Permit2 on the token first. | | `simulation_failed` | The transaction would fail on-chain. Check the other reasons and retry with a new payment. | | `invalid_transaction_state` | The transaction didn't complete as expected. Check the hash on Celoscan. | | `unexpected_verify_error`, `unexpected_settle_error` | Something went wrong on our side. Retry. | Each response may also include an `invalidMessage` or `errorMessage` with more detail. # Celo Sepolia sandbox Source: https://docs.x402go.online/guides/celo-sepolia Test your x402Go integration end to end on Celo Sepolia with free testnet USDC before you go live. Celo Sepolia is a test network, so you can run a complete payment, from request to settlement, without spending real money. This guide takes you from an empty wallet to a settled test payment. ## Network settings | Setting | Value | | - | - | | Network | `eip155:11142220` | | Facilitator | `https://api.x402go.online` | | API key | From your [x402Go dashboard](https://x402go.online/dashboard) | | Payment address (`payTo`) | From your dashboard | | Token | USDC (`0x01C5C0122039549AD1493B8220cABEdD739BC44E`) | The token's details, as returned by `/supported`: ```json theme={null} { "asset": "0x01C5C0122039549AD1493B8220cABEdD739BC44E", "symbol": "USDC", "decimals": 6, "name": "USDC", "version": "2", "assetTransferMethod": "eip3009" } ``` ## 1. Check the token is supported ```bash theme={null} curl https://api.x402go.online/supported ``` Find the `eip155:11142220` entry with `x402Version: 2`, and confirm the USDC address appears in its `supportedAssets`. ## 2. Run a paid endpoint Follow the [Quickstart](/quickstart) to run the example server. Use these values in its `.env`: ```dotenv theme={null} FACILITATOR_URL=https://api.x402go.online FACILITATOR_API_KEY=your_api_key PAY_TO=your_payment_address NETWORK=eip155:11142220 ASSET=0x01C5C0122039549AD1493B8220cABEdD739BC44E ASSET_NAME=USDC ASSET_VERSION=2 AMOUNT=10000 METHOD=eip3009 ``` `AMOUNT` is in the token's smallest unit. USDC has 6 decimals, so `10000` is 0.01 USDC. The price must also be higher than the x402Go fee. For USD-denominated tokens, x402Go charges \$0.0035 per transaction, including on Celo Sepolia. Choose an amount greater than the fee; otherwise verification returns `amount_below_fee`. Start the server and check that an unpaid request is refused: ```bash theme={null} npx tsx server.ts curl -i http://localhost:3000/paid ``` You should get `402 Payment Required` with the payment request in the response. ## 3. Create and fund a test wallet Make a new wallet just for testing. Never use a wallet that holds real funds. ```ts theme={null} // wallet.ts import { generatePrivateKey, privateKeyToAccount } from 'viem/accounts'; const key = generatePrivateKey(); console.log(`EVM_PRIVATE_KEY=${key}`); console.log(`Address: ${privateKeyToAccount(key).address}`); ``` ```bash theme={null} npx tsx wallet.ts ``` Then get free testnet USDC from the [Circle faucet](https://faucet.circle.com/): choose Celo Sepolia and USDC, and enter the address printed above. You don't need CELO in this wallet. The customer only signs the payment, and x402Go pays the network fee. ## 4. Run the client In a separate folder: ```bash theme={null} npm install @x402/fetch @x402/core @x402/evm viem dotenv npm install -D typescript tsx @types/node ``` Create `.env` with the key from the previous step: ```dotenv theme={null} EVM_PRIVATE_KEY=0xyour_test_wallet_key # SERVER_URL=http://localhost:3000/paid ``` Create `client.ts`: ```ts theme={null} import 'dotenv/config'; import { privateKeyToAccount } from 'viem/accounts'; import { x402Client } from '@x402/core/client'; import { ExactEvmScheme } from '@x402/evm/exact/client'; import { wrapFetchWithPayment, x402HTTPClient } from '@x402/fetch'; const NETWORK = 'eip155:11142220'; const USDC = '0x01C5C0122039549AD1493B8220cABEdD739BC44E'; async function main() { const key = process.env.EVM_PRIVATE_KEY; if (!key) throw new Error('Missing environment variable: EVM_PRIVATE_KEY'); const signer = privateKeyToAccount(key as `0x${string}`); const client = x402Client.fromConfig({ schemes: [{ network: 'eip155:*', client: new ExactEvmScheme(signer) }], spendControls: { // Opt in to this token, capped at 1 USDC per payment (6 decimals). allowedAssets: [{ network: NETWORK, asset: USDC, maxAmountPerPayment: '1000000' }], }, }); const fetchWithPayment = wrapFetchWithPayment(fetch, client); const httpClient = new x402HTTPClient(client); const url = process.env.SERVER_URL ?? 'http://localhost:3000/paid'; console.log(`Paying ${url} from ${signer.address}`); const response = await fetchWithPayment(url, { method: 'GET' }); const result = await httpClient.processResponse(response); console.log('Status:', response.status); console.log('Body:', result.body); if (result.paymentStatus === 'settled') { console.log('Payment settled:', result.header); } else { console.error('Payment not settled:', result.paymentStatus, result.header); process.exitCode = 1; } } main().catch((error) => { console.error(error); process.exit(1); }); ``` ```bash theme={null} npx tsx client.ts ``` A successful run prints status `200`, the paid response, and a settlement receipt that includes the transaction hash. > [!NOTE] > > The `spendControls` block is required. By default the x402 client only pays tokens it already recognizes, with a \$1 cap per payment, and it refuses anything else with a "rejected by spendControls" error. The `asset` value must match your server's `ASSET`. The cap is a safety limit for your wallet, so set it as low as you like. ## 5. Verify settlement After a paid request: * Check the transaction hash on [Celo Sepolia Celoscan](https://sepolia.celoscan.io/). * Check your payout wallet. It should have received the payment minus x402Go's fee. ## Troubleshooting | Problem | Likely cause | | - | - | | `rejected by spendControls` | The client is missing the `allowedAssets` entry, or its `asset` doesn't match the server's `ASSET`. | | `insufficient_funds` | The test wallet has no USDC. Use the faucet. | | `invalid_pay_to` | `PAY_TO` isn't your payment address. Copy it again from the dashboard. | | `amount_below_fee` | `AMOUNT` isn't higher than the fee for the token. | | `invalid_exact_evm_payload_signature` | `ASSET_NAME` or `ASSET_VERSION` on the server doesn't match `/supported`. | | `401` from the facilitator | The API key is missing or wrong. | ## Before mainnet Move to mainnet only after a test payment succeeds end to end: 1. Check `GET /supported` for the mainnet network (`eip155:42220`) and the token you want. 2. Update the server's `NETWORK`, `ASSET`, `ASSET_NAME`, `ASSET_VERSION`, `AMOUNT`, and `METHOD`. 3. Update the client's network and token in `allowedAssets`, with a cap you're comfortable with. 4. Confirm your payout wallet in the dashboard, then make one small real payment. # Express Source: https://docs.x402go.online/guides/express Charge for Express endpoints with x402 and let x402Go verify, settle, and pay you. Add the official x402 middleware to your Express app and point it at x402Go. Requests to your paid routes then get a payment request, and your handler runs once the customer has paid. This guide shows the Express-specific setup. For credentials, choosing a token, and going live, see the [Quickstart](/quickstart). ## Install ```bash theme={null} npm install express dotenv @x402/express @x402/core @x402/evm ``` ## Environment variables Get your **API key** and **payment address** from the [x402Go dashboard](https://x402go.online/dashboard). Get the token values from `GET /supported`. ```bash theme={null} curl -s https://api.x402go.online/supported ``` | Variable | Value | | - | - | | `FACILITATOR_API_KEY` | Your x402Go API key. Keep it on your server. | | `PAY_TO` | Your x402Go payment address. | | `NETWORK` | The network, for example `eip155:11142220` for Celo Sepolia or `eip155:42220` for Celo mainnet. | | `ASSET` | The token's contract address. | | `ASSET_NAME` | The token's `name` from `/supported`. | | `ASSET_VERSION` | The token's `version` from `/supported`. | | `METHOD` | Optional. Set to `permit2` if the token's `assetTransferMethod` is `permit2`. Omit it otherwise. | ## Add the middleware ```ts theme={null} import 'dotenv/config'; import express from 'express'; import { HTTPFacilitatorClient } from '@x402/core/server'; import { paymentMiddleware, x402ResourceServer } from '@x402/express'; import { ExactEvmScheme } from '@x402/evm/exact/server'; const required = (name: string) => { const value = process.env[name]; if (!value) throw new Error(`Missing environment variable: ${name}`); return value; }; const apiKey = required('FACILITATOR_API_KEY'); const payTo = required('PAY_TO'); const network = required('NETWORK') as `${string}:${string}`; const facilitator = new HTTPFacilitatorClient({ url: process.env.FACILITATOR_URL ?? 'https://api.x402go.online', createAuthHeaders: async () => { const headers = { 'x-api-key': apiKey }; return { verify: headers, settle: headers, supported: headers }; }, }); const resourceServer = new x402ResourceServer(facilitator).register(network, new ExactEvmScheme()); // Amounts are in the token's smallest unit (10000 = 0.01 for a 6-decimal token). const price = (amount: string) => ({ amount, asset: required('ASSET'), extra: { name: required('ASSET_NAME'), version: required('ASSET_VERSION'), ...(process.env.METHOD === 'permit2' ? { assetTransferMethod: 'permit2' } : {}), }, }); const app = express(); app.use( paymentMiddleware( { 'GET /premium': { accepts: [{ scheme: 'exact', network, payTo, price: price('10000') }], description: 'Premium content', mimeType: 'application/json', }, 'GET /reports': { accepts: [{ scheme: 'exact', network, payTo, price: price('50000') }], description: 'Detailed reports', mimeType: 'application/json', }, }, resourceServer, ), ); app.get('/premium', (_req, res) => { res.json({ content: 'This resource requires payment.' }); }); app.get('/reports', (_req, res) => { res.json({ report: 'Your paid report.' }); }); // Routes not listed in the middleware config stay free. app.get('/health', (_req, res) => { res.json({ ok: true }); }); app.listen(3000); ``` Register the middleware before the routes it protects. Each key in the config (`'GET /premium'`) is a route that requires payment, and you can give each route its own price. ## Accept more than one token List several entries in `accepts`. Each uses its own token's `asset`, `name`, and `version` from `/supported`, and the customer's app pays with whichever token it holds: ```ts theme={null} accepts: [ { scheme: 'exact', network, payTo, price: { amount: '10000', asset: USDC.asset, extra: { name: USDC.name, version: USDC.version } } }, { scheme: 'exact', network, payTo, price: { amount: '10000', asset: USDT.asset, extra: { name: USDT.name, version: USDT.version } } }, ], ``` Set `amount` per token. Tokens can have different decimals, so the same number is not always the same price. Every price must also be higher than the x402Go fee for that token. For reference, the fee is \$0.0035 per transaction for USD-denominated tokens and ₦4.80 per transaction for cNGN settlement. See the [fee examples and current token fees](https://x402go.online/#tokens). ## Test it ```bash theme={null} npx tsx server.ts curl -i http://localhost:3000/premium ``` An unpaid request returns `402 Payment Required` with the payment request in the response. To complete a payment, use an x402 client. The [Celo Sepolia sandbox](/guides/celo-sepolia) has a working example with test tokens. ## Before you deploy * Keep `FACILITATOR_API_KEY` on the server only. Never expose it to browsers or commit it to source control. * Use the **payment address** you got from the dashboard as `PAY_TO`, not your payout wallet. Payments to any other address are rejected. * The server fails to start if a required variable is missing. This is intentional, so a misconfigured deployment doesn't serve content for free or accept payments it can't settle. # Hono Source: https://docs.x402go.online/guides/hono Charge for Hono endpoints with x402 and let x402Go verify, settle, and pay you. Add the official x402 middleware to your Hono app and point it at x402Go. Requests to your paid routes get a payment request, and your handler runs once the customer has paid. This guide shows the Hono-specific setup. For credentials, choosing a token, and going live, see the [Quickstart](/quickstart). ## Install ```bash theme={null} npm install hono @hono/node-server @x402/hono @x402/core @x402/evm dotenv npm install -D typescript tsx @types/node ``` Install matching versions of the `@x402/*` packages. If you see type errors, check the SDK's installation guide for the versions it expects. ## Environment variables Get your API key and payment address from the [x402Go dashboard](https://x402go.online/dashboard). Get the token values from `GET /supported`. ```bash theme={null} curl -s https://api.x402go.online/supported ``` | Variable | Value | | - | - | | `FACILITATOR_API_KEY` | Your x402Go API key. Keep it on your server. | | `PAY_TO` | Your x402Go payment address. | | `NETWORK` | The network, for example `eip155:11142220` for Celo Sepolia or `eip155:42220` for Celo mainnet. | | `ASSET` | The token's contract address. | | `ASSET_NAME` | The token's `name` from `/supported`. | | `ASSET_VERSION` | The token's `version` from `/supported`. | | `METHOD` | Optional. Set to `permit2` if the token's `assetTransferMethod` is `permit2`. Omit it otherwise. | ## Add the middleware Create `server.ts`: ```ts theme={null} import 'dotenv/config'; import { Hono } from 'hono'; import { serve } from '@hono/node-server'; import { HTTPFacilitatorClient } from '@x402/core/server'; import { paymentMiddleware, x402ResourceServer } from '@x402/hono'; import { ExactEvmScheme } from '@x402/evm/exact/server'; const required = (name: string) => { const value = process.env[name]; if (!value) throw new Error(`Missing environment variable: ${name}`); return value; }; const apiKey = required('FACILITATOR_API_KEY'); const payTo = required('PAY_TO'); const network = required('NETWORK') as `${string}:${string}`; const facilitator = new HTTPFacilitatorClient({ url: process.env.FACILITATOR_URL ?? 'https://api.x402go.online', createAuthHeaders: async () => { const headers = { 'x-api-key': apiKey }; return { verify: headers, settle: headers, supported: headers }; }, }); const resourceServer = new x402ResourceServer(facilitator).register(network, new ExactEvmScheme()); // Amounts are in the token's smallest unit (10000 = 0.01 for a 6-decimal token). const price = (amount: string) => ({ amount, asset: required('ASSET'), extra: { name: required('ASSET_NAME'), version: required('ASSET_VERSION'), ...(process.env.METHOD === 'permit2' ? { assetTransferMethod: 'permit2' } : {}), }, }); const app = new Hono(); app.use( paymentMiddleware( { 'GET /premium': { accepts: [{ scheme: 'exact', network, payTo, price: price('10000') }], description: 'Premium content', mimeType: 'application/json', }, 'GET /reports': { accepts: [{ scheme: 'exact', network, payTo, price: price('50000') }], description: 'Detailed reports', mimeType: 'application/json', }, }, resourceServer, ), ); app.get('/premium', (c) => c.json({ content: 'This resource requires payment.' })); app.get('/reports', (c) => c.json({ report: 'Your paid report.' })); // Routes not listed in the middleware config stay free. app.get('/health', (c) => c.json({ ok: true })); const port = Number(process.env.PORT) || 3000; serve({ fetch: app.fetch, port }, () => { console.log(`Listening on http://localhost:${port}`); }); ``` Register the middleware before the routes it protects. Each key in the config (`'GET /premium'`) is a route that requires payment, and you can give each route its own price. This example runs on Node. On another runtime such as Bun or Cloudflare Workers, replace the `serve` call with `export default app` and read your variables from that runtime's environment. ## Accept more than one token Add more entries to `accepts`, one per token. Each token needs its own `asset`, `name`, and `version` from `/supported`. See [Express](/guides/express#accept-more-than-one-token) for an example. The same code works in Hono. Every configured amount must be greater than the token's fee. See the [fee examples and current token fees](https://x402go.online/#tokens). ## Test it ```bash theme={null} npx tsx server.ts curl -i http://localhost:3000/premium ``` An unpaid request returns `402 Payment Required` with the payment request in the response. To complete a payment, use an x402 client. The [Celo Sepolia sandbox](/guides/celo-sepolia) has a working example with test tokens. ## Before you deploy * Keep `FACILITATOR_API_KEY` on the server only. Never expose it to browsers or commit it to source control. * Use your **payment address** as `PAY_TO`, not your payout wallet. Payments to any other address are rejected. * The server fails to start if a required variable is missing. This is intentional, so a misconfigured deployment doesn't serve content for free or accept payments it can't settle. # How it works Source: https://docs.x402go.online/guides/how-it-works Understand the x402 payment lifecycle and how x402Go routes settled payments. With [x402](https://www.x402.org/), your API can ask for payment as part of an ordinary web request. Customers, whether apps or AI agents, pay automatically in stablecoins. There are no accounts, checkout pages, or invoices. x402 uses HTTP responses to communicate payment requirements. A client requests a protected resource, receives a payment challenge when payment is required, creates a payment payload, and retries the request. The resource server uses a facilitator to verify and settle the payment. ## What happens when someone pays **1. A customer asks for your content** A customer's app or AI agent requests one of your paid endpoints, like any other API request. **2. Your server asks for payment** Your server replies that payment is required. The reply includes the price, the currency, and the address to pay. **3. The customer pays** The customer's app approves the payment automatically and sends the request again, this time with the payment attached. **4. x402Go checks the payment** Your server asks x402Go to confirm the payment is valid and matches your price. No money moves yet. **5. x402Go completes the payment** Once the check passes, x402Go completes the payment. Your earnings go straight to your wallet, and x402Go's small fee is taken from the same payment. **6. Your server delivers the content** When the payment is complete, your server sends the customer what they asked for. If a payment can't be completed, your server doesn't deliver the content. ## Where the money goes x402Go uses three things, and each has its own job: * **API key:** a secret that identifies your server to x402Go. Keep it private. * **Payment address:** where your customers send their payments. Your server gives it to them in step 2. It is the same on every network x402Go supports, and it is set up automatically with your first payment on each network, so that payment may take a little longer. * **Payout wallet:** your own wallet. Every payment is sent here when it completes. x402Go never holds your money. Each payment is split the moment it completes, with your earnings going to your payout wallet and the fee going to x402Go. There is no balance to withdraw. The fee is **\$0.0035 per transaction** for USD-denominated tokens and **₦4.80 per transaction** for cNGN settlement. Your configured price must be greater than the applicable fee. See the [fee examples and current token fees](https://x402go.online/#tokens). Set your payout wallet in the dashboard and check it carefully before you accept real payments. ## Next steps Ready to try it? Follow the [Quickstart](/quickstart). # Next.js Source: https://docs.x402go.online/guides/nextjs Charge for Next.js App Router endpoints with x402 and let x402Go verify, settle, and pay you. Add the official x402 package to your Next.js app and point it at x402Go. Requests to your paid routes get a payment request, and your handler runs once the customer has paid. If your handler fails, the customer isn't charged. This guide shows the Next.js-specific setup. For credentials, choosing a token, and going live, see the [Quickstart](/quickstart). ## Install In an existing Next.js App Router project: ```bash theme={null} npm install @x402/next @x402/core @x402/evm ``` Install matching versions of the `@x402/*` packages. If you see type errors, check the SDK's installation guide for the versions it expects. ## Environment variables Add these to `.env.local`. Next.js loads the file automatically. Get your API key and payment address from the [x402Go dashboard](https://x402go.online/dashboard), and the token values from `GET /supported`. ```bash theme={null} curl -s https://api.x402go.online/supported -H "x-api-key: $FACILITATOR_API_KEY" ``` | Variable | Value | | - | - | | `FACILITATOR_API_KEY` | Your x402Go API key. | | `PAY_TO` | Your x402Go payment address. | | `NETWORK` | The network, for example `eip155:11142220` for Celo Sepolia or `eip155:42220` for Celo mainnet. | | `ASSET` | The token's contract address. | | `ASSET_NAME` | The token's `name` from `/supported`. | | `ASSET_VERSION` | The token's `version` from `/supported`. | | `METHOD` | Optional. Set to `permit2` if the token's `assetTransferMethod` is `permit2`. Omit it otherwise. | > [!WARNING] > > Never add the `NEXT_PUBLIC_` prefix to these variables. Next.js sends prefixed variables to the browser, which would expose your API key. ## Set up x402 once Create `lib/x402.ts`. Your routes share this setup. ```ts theme={null} // lib/x402.ts import { HTTPFacilitatorClient, x402ResourceServer } from '@x402/core/server'; import { ExactEvmScheme } from '@x402/evm/exact/server'; const required = (name: string) => { const value = process.env[name]; if (!value) throw new Error(`Missing environment variable: ${name}`); return value; }; const apiKey = required('FACILITATOR_API_KEY'); export const payTo = required('PAY_TO'); export const network = required('NETWORK') as `${string}:${string}`; const facilitator = new HTTPFacilitatorClient({ url: process.env.FACILITATOR_URL ?? 'https://api.x402go.online', createAuthHeaders: async () => { const headers = { 'x-api-key': apiKey }; return { verify: headers, settle: headers, supported: headers }; }, }); export const server = new x402ResourceServer(facilitator).register(network, new ExactEvmScheme()); // Amounts are in the token's smallest unit (10000 = 0.01 for a 6-decimal token). export const price = (amount: string) => ({ amount, asset: required('ASSET'), extra: { name: required('ASSET_NAME'), version: required('ASSET_VERSION'), ...(process.env.METHOD === 'permit2' ? { assetTransferMethod: 'permit2' } : {}), }, }); ``` ## Protect an API route Wrap the route's handler with `withX402`: ```ts theme={null} // app/api/premium/route.ts import { NextRequest, NextResponse } from 'next/server'; import { withX402 } from '@x402/next'; import { network, payTo, price, server } from '../../../lib/x402'; const handler = async (_req: NextRequest) => NextResponse.json({ content: 'This resource requires payment.' }); export const GET = withX402( handler, { '/api/premium': { accepts: [{ scheme: 'exact', network, payTo, price: price('10000') }], description: 'Premium content', mimeType: 'application/json', }, }, server, ); ``` The key (`'/api/premium'`) must match the route's URL path exactly as it is served, including any `basePath` you've configured. **If it doesn't match, the route runs without payment protection.** Always test an unpaid request, as shown below. Routes you don't wrap stay free. ## Protect pages or many routes at once To protect pages, or several routes with one configuration, use `paymentProxy` instead. Create `proxy.ts` in your project root (`middleware.ts`, exporting `middleware`, on Next.js 15 and earlier): ```ts theme={null} // proxy.ts import { paymentProxy } from '@x402/next'; import { network, payTo, price, server } from './lib/x402'; export const proxy = paymentProxy( { '/protected': { accepts: [{ scheme: 'exact', network, payTo, price: price('10000') }], description: 'Premium page', mimeType: 'text/html', }, }, server, ); export const config = { matcher: ['/protected/:path*'], }; ``` The `matcher` must cover every route in the config. A protected route missing from the matcher isn't checked. ## Accept more than one token Add more entries to `accepts`, one per token. Each token needs its own `asset`, `name`, and `version` from `/supported`. See [Express](/guides/express#accept-more-than-one-token) for an example. The same configuration works in Next.js. Every configured amount must be greater than the token's fee. See the [fee examples and current token fees](https://x402go.online/#tokens). ## Test it ```bash theme={null} npm run dev curl -i http://localhost:3000/api/premium ``` An unpaid request must return `402 Payment Required` with the payment request in the response. If you get your content instead, the route isn't protected. Check that the path in your config matches the URL. To complete a payment, use an x402 client. The [Celo Sepolia sandbox](/guides/celo-sepolia) has a working example with test tokens. ## Before you deploy * Keep `FACILITATOR_API_KEY` in server-side environment variables only, never `NEXT_PUBLIC_`. * Use your **payment address** as `PAY_TO`, not your payout wallet. Payments to any other address are rejected. * Set all variables in your hosting provider, including for the build step. Next.js loads your route files during `next build`, so a missing variable fails the build. This is intentional, so a misconfigured # Security and contracts Source: https://docs.x402go.online/guides/security How to keep your API key safe, how payments are routed, and the verified contract addresses behind x402Go. ## API key security Your x402Go API key lets your server call the facilitator. Treat it like a password. * Send it only from your server, in the `x-api-key` header. * Never put it in browser code, mobile apps, public examples, or client-side environment variables (such as `NEXT_PUBLIC_` variables). * Store it in a secret manager or in server environment variables. * Rotate it right away if it may have been exposed. * Don't log request headers or payment payloads. ## Payment address and payout wallet Three values are easy to confuse. Each has a single job: | Value | What it is | Where it goes | | - | - | - | | **API key** | A secret that identifies your server to x402Go. | The `x-api-key` header on your server's requests. | | **Payment address** | The address your customers pay. It is created for you by the x402Go contracts. | `payTo` in your x402 payment requirements. | | **Payout wallet** | Your own wallet, where your earnings end up. | Set in the x402Go dashboard. Never use it as `payTo`. | When a payment settles, the contracts split it in the same transaction. Your earnings go to your payout wallet and the fee goes to x402Go. The contracts never hold your funds. Set and check your payout wallet before you accept payments. The fee is **\$0.0035 per transaction** for USD-denominated tokens and **₦4.80 per transaction** for cNGN settlement. The payment amount must be greater than the applicable fee, or settlement is rejected. See the [current token fees](https://x402go.online/#tokens). ## How settlement is protected x402 checks every payment twice: first it verifies the payment, then it settles it. * Only deliver your content after settlement succeeds. * Use the official x402 middleware, which does this for you. Don't write custom code that ignores a failed verification or settlement. * Each token uses one of two transfer methods (`eip3009` or `permit2`). Use only the method that `GET /supported` lists for your network and token. ## Contracts x402Go uses two contracts: * **Payment relayer factory.** Creates each merchant's payment address and handles the fee and payout split. * **Payment relayer implementation.** The shared code that every payment address runs. > [!WARNING] > > Never send funds to the factory or the implementation. Customers pay your own payment address, which is the `payTo` value from your dashboard. ### Celo Mainnet | Contract | Address | | - | - | | Operator | [`0x402001B3fbf1462939657eb7f64EE3743eAdf35E`](https://celoscan.io/address/0x402001B3fbf1462939657eb7f64EE3743eAdf35E) | | Payment relayer factory | [`0xdfBB7b9F9449024A36E34539f94e1ca14f404ef6`](https://celoscan.io/address/0xdfBB7b9F9449024A36E34539f94e1ca14f404ef6) | | Payment relayer implementation | [`0x2A081D94C3bA4183bBFd907A39Ad1597DD9261a1`](https://celoscan.io/address/0x2A081D94C3bA4183bBFd907A39Ad1597DD9261a1) | Explorer: [Celoscan](https://celoscan.io/) ### Celo Sepolia (testnet) | Contract | Address | | - | - | | Operator | [`0x402001B3fbf1462939657eb7f64EE3743eAdf35E`](https://sepolia.celoscan.io/address/0x402001B3fbf1462939657eb7f64EE3743eAdf35E) | | Payment relayer factory | [`0xdfBB7b9F9449024A36E34539f94e1ca14f404ef6`](https://sepolia.celoscan.io/address/0xdfBB7b9F9449024A36E34539f94e1ca14f404ef6) | | Payment relayer implementation | [`0x2A081D94C3bA4183bBFd907A39Ad1597DD9261a1`](https://sepolia.celoscan.io/address/0x2A081D94C3bA4183bBFd907A39Ad1597DD9261a1) | Explorer: [Celo Sepolia Celoscan](https://sepolia.celoscan.io/) The addresses are identical on both networks, and so is your own payment address. You can read the contracts' verified source code on the **Contract** tab of each Celoscan page. ## Check your payment address on-chain You can confirm that your `payTo` came from the x402Go factory: 1. Open the factory on [Celoscan](https://celoscan.io/address/0xdfBB7b9F9449024A36E34539f94e1ca14f404ef6) (or the [testnet page](https://sepolia.celoscan.io/address/0xdfBB7b9F9449024A36E34539f94e1ca14f404ef6)). 2. Go to **Contract**, then **Read Contract**. 3. Open `vaultOf` and enter the wallet address you use to sign in to the dashboard. 4. Compare the result with the payment address in your dashboard and your server's `PAY_TO`. They must match exactly. Your payment address is calculated in advance. It has no code on-chain until your first payment settles on that network, so an empty page on Celoscan before then is expected. ## Operational checklist * [ ] Your API key stays on your server and is rotated if exposed. * [ ] `payTo` matches the payment address in your dashboard, and `vaultOf` returns the same address. * [ ] Your payout wallet is set and checked. * [ ] Your network and token are listed by `GET /supported`. * [ ] Unpaid requests get a `402 Payment Required` response. * [ ] Failed verification or settlement never unlocks your content. * [ ] You've made one small real payment and checked it on Celoscan. # x402Go Source: https://docs.x402go.online/index Accept stablecoin payments on your API with x402. x402Go is a pay-as-you-go [x402](https://www.x402.org/) facilitator on Celo. Which means you do not need to get facilitator credits or think about fees. Every payment pays the fees for itself. x402Go verifies every payment, pays for and settles it on-chain, and sends the rest directly to your configured payout address. We never hold your funds. Each settled payment has a fixed token fee. Your price must be higher than the applicable fee, and your payout receives the payment amount minus that fee. See the [fee examples and current token fees](https://x402go.online/#tokens). > [card] [Quickstart](/quickstart) > > Protect your first endpoint in a few minutes. > [card] [API reference](/api-reference/overview) > > Request and response formats for `/supported`, `/verify`, and `/settle`. > [card] [Celo Sepolia sandbox](/guides/celo-sepolia) > > Test your integration with testnet tokens before you go live. > [card] [How it works](/guides/how-it-works) > > How verification, settlement, and payouts fit together. ## Before you start 1. Sign in to the [x402Go dashboard](https://x402go.online/dashboard) with your wallet. 2. Set your **payout wallet**. This is where your earnings are sent. 3. Create an **API key**. It is shown only once, so copy it right away and store it like a password. 4. Copy your **payment address** from the dashboard. 5. Set the payment address as `payTo` in your x402 payment configuration. There is nothing to deploy. Your payment address is the same on every supported network, and it is set up automatically when your first payment settles on each one. > [!WARNING] > > Keep these three apart: > > * **API key:** a secret that authenticates your server's requests to the facilitator. > * **Payment address:** the `payTo` in your payment requirements. Clients pay this address. > * **Payout wallet:** your own wallet, where settled payments end up. > > Never use your payout wallet as `payTo`. The facilitator rejects requests whose `payTo` is not your payment address. ## Facilitator Base URL: ```text theme={null} https://api.x402go.online ``` | Endpoint | Purpose | | - | - | | `GET /supported` | List the x402 versions, networks, and tokens the facilitator accepts. | | `POST /verify` | Check a payment against your payment requirements. No funds move. | | `POST /settle` | Submit the payment on-chain. Funds are collected and split in a single transaction. | `/verify` and `/settle` require your API key in the `x-api-key` header. Keep it on your server and never expose it to clients. See the [API reference](/api-reference/overview) for details. ## Supported networks and assets x402Go is live on Celo mainnet with USDC, USDT, USAT, and cNGN. Use Celo Sepolia for testing. Call `GET /supported` for the current list. ## Choose your integration * [Express](/guides/express) with `@x402/express` * [Hono](/guides/hono) with `@x402/hono` * [Next.js App Router](/guides/nextjs) with `@x402/next` * [Celo Sepolia testnet](/guides/celo-sepolia) # Quickstart Source: https://docs.x402go.online/quickstart Protect an Express endpoint with x402 and get paid in stablecoins through x402Go. In this guide you'll add x402 payments to an Express endpoint, with x402Go verifying and settling each payment. When you finish, an unpaid request to `/paid` returns `402 Payment Required`, and a paid request returns your response and sends the funds to your payout wallet. ## 1. Get your credentials In the [x402Go dashboard](https://x402go.online/dashboard), set up three things: 1. **Payout wallet**: your own wallet, where settled payments end up. You set it in the dashboard and never use it in code. 2. **API key**: authenticates your server's requests to the facilitator. It is shown only once, so copy it right away. 3. **Payment address**: the address clients pay. It goes in `payTo`. Get this from the [API Keys Section](https://x402go.online/dashboard/api-keys) if the dashboard. > [!WARNING] > > Keep the API key on your server. Never put it in browser code or commit it to source control. ## 2. Install dependencies ```bash theme={null} npm install express dotenv @x402/express @x402/core @x402/evm npm install -D typescript tsx @types/express @types/node ``` Install matching versions of the `@x402/*` packages. If you hit type errors, check the SDK's installation guide for the versions it expects. ## 3. Configure environment variables Find the token you want to accept in the facilitator's supported list: ```bash theme={null} curl -s https://api.x402go.online/supported ``` Copy its `asset`, `name`, `version`, and `assetTransferMethod` from the `supportedAssets` list for your network. Then create `.env`. This example uses USDC on Celo Sepolia: ```dotenv theme={null} FACILITATOR_URL=https://api.x402go.online FACILITATOR_API_KEY=your_api_key PAY_TO=your_payment_address NETWORK=eip155:11142220 ASSET=0x01C5C0122039549AD1493B8220cABEdD739BC44E ASSET_NAME=USDC ASSET_VERSION=2 AMOUNT=10000 METHOD=eip3009 ``` > [!NOTE] > > `AMOUNT` is in the token's smallest unit, not a decimal amount. USDC has 6 decimals, so `10000` is 0.01 USDC. The price must also be higher than x402Go's [fee](https://x402go.online/#tokens) for that token, or payments are rejected. `ASSET_NAME` and `ASSET_VERSION` must match what `/supported` returns. Clients use them to sign the payment, and a mismatch fails with an invalid signature error. ## 4. Understand fees and minimum prices x402Go charges a fixed fee per transaction. The customer pays the amount you configure, and you receive that amount minus the fee. | Customer pays | You receive | Fee | | - | - | - | | \$0.01 | \$0.0065 | \$0.0035 | | \$0.10 | \$0.0965 | \$0.0035 | | \$1.00 | \$0.9965 | \$0.0035 | | \$100.00 | \$99.9965 | \$0.0035 | For USD-denominated tokens, the fee is \*\*$0.0035 per transaction**. For cNGN settlement, the fee is **₦4.80 per transaction**. Your configured price must be greater than the applicable fee, so the minimum price is any amount above $0.0035 for USD-denominated tokens or above ₦4.80 for cNGN. A price equal to or below the fee is rejected with `amount_below_fee`. See the [current token fees](https://x402go.online/#tokens) before choosing a token. ## 5. Add payment middleware Create `server.ts`: ```ts theme={null} import 'dotenv/config'; import express from 'express'; import { HTTPFacilitatorClient } from '@x402/core/server'; import { paymentMiddleware, x402ResourceServer } from '@x402/express'; import { ExactEvmScheme } from '@x402/evm/exact/server'; const required = (name: string) => { const value = process.env[name]; if (!value) throw new Error(`Missing environment variable: ${name}`); return value; }; const facilitatorUrl = required('FACILITATOR_URL').replace(/\/$/, ''); const apiKey = required('FACILITATOR_API_KEY'); const payTo = required('PAY_TO'); const network = required('NETWORK') as `${string}:${string}`; const asset = required('ASSET'); const assetName = required('ASSET_NAME'); const assetVersion = required('ASSET_VERSION'); const amount = process.env.AMOUNT ?? '10000'; const method = process.env.METHOD ?? 'eip3009'; const facilitator = new HTTPFacilitatorClient({ url: facilitatorUrl, createAuthHeaders: async () => { const headers = { 'x-api-key': apiKey }; return { verify: headers, settle: headers, supported: headers }; }, }); const resourceServer = new x402ResourceServer(facilitator).register(network, new ExactEvmScheme()); const app = express(); app.use( paymentMiddleware( { 'GET /paid': { accepts: [ { scheme: 'exact', network, payTo, price: { amount, asset, extra: { name: assetName, version: assetVersion, ...(method === 'permit2' ? { assetTransferMethod: 'permit2' } : {}), }, }, }, ], description: 'Paid example endpoint', mimeType: 'application/json', }, }, resourceServer, ), ); app.get('/paid', (_req, res) => { res.json({ ok: true, message: 'Payment accepted' }); }); app.listen(3000, () => { console.log('Listening on http://localhost:3000'); }); ``` ## 6. Run and test ```bash theme={null} npx tsx server.ts ``` An unpaid request should return `402 Payment Required` with the x402 payment challenge: ```bash theme={null} curl -i http://localhost:3000/paid ``` To complete a payment, use an x402 client. It reads the challenge, signs the payment, and retries the request. Get Testnet USDC from [Circle Faucet](https://faucet.circle.com/). The [Celo Sepolia sandbox](/guides/celo-sepolia) guide has a complete client example. ## 7. Go live Before you accept real payments: 1. Check `GET /supported` for the mainnet network and the token you want to accept. 2. Update `NETWORK`, `ASSET`, `ASSET_NAME`, `ASSET_VERSION`, `AMOUNT`, and `METHOD` in your environment. Use `eip155:42220` for Celo mainnet. 3. Confirm your payout wallet in the dashboard. 4. Make one small real payment, then check the transaction on a block explorer and the payout in your dashboard. > [!NOTE] > > If the token's `assetTransferMethod` is `permit2` (cNGN, for example), set `METHOD=permit2`. Payers must also approve Permit2 on that token once before their first payment, otherwise payments fail with `permit2_allowance_required`. ## Troubleshooting When a payment is rejected, `/verify` returns `isValid: false` with an `invalidReason`. | Reason | Likely cause | | - | - | | `invalid_pay_to` | `PAY_TO` is not your payment address. Copy it again from the dashboard. | | `unsupported_asset` | The token is not in `/supported` for that network. | | `unsupported_transfer_method` | `METHOD` doesn't match the token's `assetTransferMethod`. | | `amount_below_fee` | `AMOUNT` is not higher than the facilitator's fee for the token. | | `invalid_exact_evm_payload_signature` | `ASSET_NAME` or `ASSET_VERSION` doesn't match `/supported`. | A `401` response means the API key is missing or wrong.