Usage & Consumption

Learn how to consume a PayGate-protected API as an AI Agent or developer using the x402 protocol and the official SDK.

The x402 Payment Flow

Every PayGate-protected API follows this deterministic, machine-readable flow:

  1. Your client makes a standard GET or POST request to the PayGate proxy URL — no special headers needed.
  2. PayGate responds with 402 Payment Required. The response body contains an x402 invoice with the exact price, currency (USDC), and destination wallet.
  3. Your client reads the invoice, constructs a Stellar USDC transaction, signs it with your wallet keypair.
  4. Your client retries the original request, this time attaching the signed transaction in the X-Payment header.
  5. PayGate verifies the transaction on the Stellar network, submits it, and forwards your request to the target API. The developer is paid instantly on-chain.

Option 1 — SDK (Recommended)

The easiest integration is the official @x402/fetch package. It wraps the native fetch API and handles the entire 402 negotiation automatically — your code never needs to know about wallets or Stellar transactions.

Install

npm install @x402/fetch @stellar/stellar-sdk

TypeScript / JavaScript

import { wrapFetch } from '@x402/fetch';
import { Keypair } from '@stellar/stellar-sdk';

// 1. Load your agent's Stellar keypair
const keypair = Keypair.fromSecret(process.env.AGENT_SECRET_KEY!);

// 2. Wrap the global fetch with automatic x402 payment handling
const fetch402 = wrapFetch(fetch, keypair);

// 3. Call any PayGate-protected endpoint — payment is fully automatic
const response = await fetch402(
  'https://paygate-stellar-swart.vercel.app/api/x/your-api-slug'
);
const data = await response.json();
console.log(data);

Option 2 — Manual HTTP

If you are not using JavaScript/TypeScript, you can implement the x402 protocol manually in any language that supports HTTP and the Stellar SDK.

# Step 1: Initial request (will receive 402)
GET https://paygate-stellar-swart.vercel.app/api/x/<slug>
# Response: 402 Payment Required
# Response body: { "x402Version": 1, "accepts": [{ "scheme": "exact", "network": "stellar:testnet", "maxAmountRequired": "0.001", "asset": "USDC", "payTo": "G..." }] }

# Step 2: Construct and sign the Stellar transaction, then retry
GET https://paygate-stellar-swart.vercel.app/api/x/<slug>
X-Payment: <base64-encoded-signed-stellar-transaction>
# Response: 200 OK + API data

Option 3 — Try in the Playground

No code required. Navigate to the Marketplace, select any listed API, and click “Try in Playground”. The Playground visually demonstrates the entire cryptographic payment flow — including the 402 challenge, transaction construction, and the final API response — right in your browser.

Environment Variables

For production agent deployments, store your Stellar secret key as an environment variable:

# .env
AGENT_SECRET_KEY=S...  # Your agent's Stellar secret key (starts with S)

# Never commit this to version control!