Skip to content
Sign in
Menu

Make your first paid API request

An end-to-end tutorial: from choosing an API to receiving its answer and a payment receipt.

On this page

Prerequisites

  • Node.js 22 or newer, and the packages @solana/kit, @solana-program/token and @solana-program/compute-budget.
  • A Solana keypair your code can load, with a USDC token account on the quote's network holding at least the API's price.
  • A Solana RPC URL for the same network, used only to fetch a recent blockhash.

1. Select an API

Pick an API in the directory and copy its gateway URL, for example https://gateway.example.com/v1/weather-forecasts.

2. Inspect its endpoint

Read the description and methods to decide which path to call, for example /forecast?city=Lisbon. See Understand API endpoints.

3. Understand its price

The directory shows the price per call, which is what you'll be quoted. Decide the most you're willing to pay per call. In code, keep that as an integer in base units: 50000n is 0.05 USDC.

4. Construct the request

Append the path to the gateway URL: https://gateway.example.com/v1/weather-forecasts/forecast?city=Lisbon. Set Content-Type if you send a body.

5. Send the request

HTTPIllustrative values
GET /v1/weather-forecasts/forecast?city=Lisbon HTTP/1.1
Host: gateway.example.com
Accept: application/json

6. Handle HTTP 402

HTTPIllustrative values
HTTP/1.1 402 Payment Required
Content-Type: application/json
Cache-Control: no-store
PAYMENT-REQUIRED: eyJ4NDAyVmVyc2lvbiI6Mi…

{ "error": "payment_required", "quoteId": "q_3f9c2a7b8e1d4c6a9b0e2f4d6c8a1b3e" }

This is the normal first answer. Nothing has been charged.

7. Read the payment requirements

Base64-decode the PAYMENT-REQUIRED header to get JSON:

JSONDecoded PAYMENT-REQUIREDIllustrative values
{
  "x402Version": 2,
  "resource": {
    "url": "https://gateway.example.com/v1/weather-forecasts/forecast?city=Lisbon",
    "description": "Paid API weather-forecasts",
    "mimeType": "application/json"
  },
  "accepts": [
    {
      "scheme": "exact",
      "network": "solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1",
      "amount": "13000",
      "asset": "<USDC mint for the network>",
      "payTo": "<the API's vault address>",
      "maxTimeoutSeconds": 60,
      "extra": {
        "feePayer": "<NODRA fee payer address>",
        "memo": "q_3f9c2a7b8e1d4c6a9b0e2f4d6c8a1b3e",
        "successPolicy": { "mode": "non_empty_2xx" },
        "priceBreakdown": { "providerPrice": "10000", "platformFee": "3000" }
      }
    }
  ]
}

Before paying, check that network and asset are the ones you hold, and that amount is within your limit. The quote expires in 60 seconds. Understand an HTTP 402 response explains each field.

8. Prepare the payment authorization

Build a version 0 Solana transaction with:

  • Fee payer: extra.feePayer. Don't sign for it; NODRA does when it settles.
  • A compute unit limit of at most 400,000 and a compute unit price of at most 50,000 microlamports.
  • One TransferChecked of exactly amount, with 6 decimals, from your USDC token account to the associated token account of payTo for asset, with your wallet as the authority.
  • A Memo instruction whose text is extra.memo, the quote id.

Sign it with your wallet only, then serialize it as base64. The Payment lifecycle page lists every rule NODRA checks.

9. Submit the authorization

Send the same request again with a PAYMENT-SIGNATURE header: base64-encoded JSON holding the version, the quote's resource, the requirement you accepted, and the transaction.

JSONPAYMENT-SIGNATURE, before base64Illustrative values
{
  "x402Version": 2,
  "resource": { "url": "https://gateway.example.com/v1/weather-forecasts/forecast?city=Lisbon", "description": "Paid API weather-forecasts", "mimeType": "application/json" },
  "accepted": { "scheme": "exact", "network": "…", "amount": "13000", "…": "the requirement, unchanged" },
  "payload": { "transaction": "<base64 signed transaction>" }
}

10. Receive the response and receipt

HTTPIllustrative values
HTTP/1.1 200 OK
Content-Type: application/json
Cache-Control: no-store
PAYMENT-RESPONSE: eyJzdWNjZXNzIjp0cnVlLC…

{ "city": "Lisbon", "forecast": "…" }
JSONDecoded PAYMENT-RESPONSEIllustrative values
{
  "success": true,
  "transaction": "<Solana transaction signature>",
  "network": "solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1",
  "payer": "<the paying wallet>"
}

success: true means the payment is confirmed on Solana. If the receipt says success: false with errorReason: "settlement_pending", you have the answer and the payment is still being confirmed. See Understand payment receipts.

Complete example

Steps 5 to 10 in TypeScript, adapted from the payment builder in NODRA's backend, which is tested against the real gateway:

TypeScriptpaid-fetch.ts
import {
  address, appendTransactionMessageInstructions, createNoopSigner,
  createSolanaRpc, createTransactionMessage, getBase64EncodedWireTransaction,
  partiallySignTransactionMessageWithSigners, pipe,
  setTransactionMessageFeePayerSigner, setTransactionMessageLifetimeUsingBlockhash,
  type Blockhash, type KeyPairSigner,
} from "@solana/kit"
import { getSetComputeUnitLimitInstruction, getSetComputeUnitPriceInstruction } from "@solana-program/compute-budget"
import { TOKEN_PROGRAM_ADDRESS, findAssociatedTokenPda, getTransferCheckedInstruction } from "@solana-program/token"

const MEMO_PROGRAM = address("MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr")
const MAX_AMOUNT = 50_000n // your own limit: 0.05 USDC per call

const b64json = (value: unknown) => Buffer.from(JSON.stringify(value)).toString("base64")
const fromB64json = (value: string) => JSON.parse(Buffer.from(value, "base64").toString("utf8"))

export async function paidFetch(url: string, wallet: KeyPairSigner, rpcUrl: string, network: string, asset: string) {
  // 1. Ask. Without a payment the gateway answers 402 with a quote.
  const first = await fetch(url)
  if (first.status !== 402) return first
  const required = fromB64json(first.headers.get("PAYMENT-REQUIRED")!)

  // 2. Check the quote against your own rules before signing anything.
  const quote = required.accepts.find((a: any) => a.scheme === "exact" && a.network === network && a.asset === asset)
  if (!quote) throw new Error("No quote for this network and asset")
  if (BigInt(quote.amount) > MAX_AMOUNT) throw new Error(`Quote of ${quote.amount} is above the limit`)

  // 3. Build the transfer: compute limit, compute price, one TransferChecked, the quote id as memo.
  const mint = address(quote.asset)
  const [source] = await findAssociatedTokenPda({ mint, owner: wallet.address, tokenProgram: TOKEN_PROGRAM_ADDRESS })
  const [destination] = await findAssociatedTokenPda({ mint, owner: address(quote.payTo), tokenProgram: TOKEN_PROGRAM_ADDRESS })
  const { value: latest } = await createSolanaRpc(rpcUrl).getLatestBlockhash({ commitment: "confirmed" }).send()

  const message = pipe(
    createTransactionMessage({ version: 0 }),
    // NODRA pays the network fee: name its fee payer, but don't sign for it.
    (m) => setTransactionMessageFeePayerSigner(createNoopSigner(address(quote.extra.feePayer)), m),
    (m) => setTransactionMessageLifetimeUsingBlockhash({ blockhash: latest.blockhash as Blockhash, lastValidBlockHeight: latest.lastValidBlockHeight }, m),
    (m) => appendTransactionMessageInstructions([
      getSetComputeUnitLimitInstruction({ units: 20_000 }),
      getSetComputeUnitPriceInstruction({ microLamports: 1 }),
      getTransferCheckedInstruction(
        { source, mint, destination, authority: wallet, amount: BigInt(quote.amount), decimals: 6 },
        { programAddress: TOKEN_PROGRAM_ADDRESS },
      ),
      { programAddress: MEMO_PROGRAM, accounts: [], data: new TextEncoder().encode(quote.extra.memo) },
    ], m),
  )
  // Your key signs as the owner of the USDC only.
  const transaction = getBase64EncodedWireTransaction(await partiallySignTransactionMessageWithSigners(message))

  // 4. Send the same request once more, with the payment.
  const paid = await fetch(url, {
    headers: {
      "PAYMENT-SIGNATURE": b64json({ x402Version: 2, resource: required.resource, accepted: quote, payload: { transaction } }),
    },
  })

  // 5. Read the receipt. Never pay again automatically, whatever the answer.
  const receipt = paid.headers.get("PAYMENT-RESPONSE")
  console.log(paid.status, receipt ? fromB64json(receipt) : "no receipt")
  return paid
}

Common mistakes

SymptomCause
400 invalid_payment_headerThe header isn't base64 JSON, or accepted.extra.memo or payload.transaction is missing.
402 again, with a reasonThe payment was rejected. The reason names the check that failed; a new quote comes with it.
402 with payment_expiredMore than 60 seconds passed between the quote and the payment.
Nothing happens with X-PAYMENTNODRA reads only PAYMENT-SIGNATURE (x402 version 2).