Skip to main content
This walkthrough assumes you already enabled Coinbase x402 for your workspace facilitator. If you have not, follow the <Link href="https://docs.cdp.coinbase.com/x402/quickstart-for-sellers">Coinbase seller quickstart</Link> first so invoices can be settled.

1. Install dependencies

npm install @coinbase/cdp-sdk dotenv x402-fetch

2. Export facilitator credentials

Save your Coinbase keys as environment variables so the SDK can discover them automatically:
export CDP_API_KEY_ID=your-api-key-id
export CDP_API_KEY_SECRET=your-api-key-secret
export CDP_WALLET_SECRET=your-wallet-secret

3. Instantiate the wallet and funded account

import { CdpClient } from '@coinbase/cdp-sdk';
import { wrapFetchWithPayment } from 'x402-fetch';
import dotenv from 'dotenv';

dotenv.config();

const cdp = new CdpClient();
const account = await cdp.evm.createAccount(); // Base Sepolia wallet

const fetchWithPayment = wrapFetchWithPayment(fetch, account);
Fund the new wallet on Base Sepolia (or the chain you plan to use) so it can replay 402 invoices.

4. Call Horizon with automatic invoice replay

const baseUrl = process.env.HORIZON_BASE_URL ?? 'https://api.horizon.new/v1';

const jobResponse = await fetchWithPayment(`${baseUrl}/generate/text`, {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({
    prompt: 'Write a welcome note for new Horizon users.',
    metadata: { campaign: 'launch-campaign' },
    webhookUrl: 'https://example.com/webhooks/horizon',
  }),
});

const job = await jobResponse.json();
console.log(job.content, job.jobId);
The fetchWithPayment helper automatically:
  1. Performs the initial request.
  2. Detects a 402 Payment Required challenge.
  3. Signs the invoice with the Coinbase wallet.
  4. Replays the request with X-PAYMENT.

5. Poll job status (optional)

const status = await fetchWithPayment(`${baseUrl}/jobs/${job.jobId}`).then((res) => res.json());

if (status.state === 'succeeded') {
  console.log(status.result);
}

Next steps

  • Swap Base Sepolia for your production chain when you are ready to process live traffic.
  • Combine this wallet flow with the endpoint examples in /examples to orchestrate discovery, generation, and extraction pipelines end to end.