Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.swiftpay.finance/llms.txt

Use this file to discover all available pages before exploring further.

The @swiftpayfi/api-client is a zero-dependency TypeScript SDK for the SwiftPay REST API. It’s designed for Node.js 18+, Cloudflare Workers, Vercel Edge Functions, and other JavaScript runtimes.

Features

  • Zero runtime dependencies — Uses the platform fetch
  • ESM-only — Modern JavaScript module support
  • Auth-aware — Methods requiring secret keys throw errors at call time, not silently as 401s
  • Typed errors — Each HTTP status maps to a discriminated subclass
  • Type-safe — Full TypeScript support

Installation

npm install @swiftpayfi/api-client
Requires Node.js 18+.

Quick Start

import { SwiftPay } from '@swiftpayfi/api-client';

const client = new SwiftPay({
  secretKey: process.env.SWIFTPAY_SECRET_KEY,
});

// Create an invoice
const { invoice, created } = await client.invoices.create({
  amount: '100.00',
  token: 'USDC',
  network: 'ethereum',
  recipients: { evm: '0xYourWallet...' },
  externalRef: 'order_8675309',
});

console.log(created ? 'New invoice' : 'Idempotent hit', invoice.id);

Configuration

new SwiftPay({
  secretKey: 'sk_live_...',                    // optional — required only for secret-scoped methods
  baseUrl: 'https://api.swiftpay.finance',     // optional, defaults to production
  fetch: globalThis.fetch,                     // optional, dependency-injectable
  timeoutMs: 30_000,                           // optional, default 30s
});

Modules

utils (no auth)

Retrieve supported chains and tokens.
const chains = await client.utils.listChains();
// Returns: { id: 'ethereum', name: 'Ethereum', chainId: 1, ... }[]

const tokens = await client.utils.listTokens();
// Returns: { id: 'USDC', name: 'USD Coin', decimals: 6, ... }[]

invoices (requires secret key)

Create, list, and track payment invoices.
// Create invoice
await client.invoices.create({
  amount: '100.00',
  token: 'USDC',
  network: 'ethereum',
  recipients: { evm: '0xYourWallet...' },
  externalRef?: 'order_12345',      // optional, for deduplication
  expiresIn?: 3600,                 // optional, seconds
  metadata?: { orderId: '12345' },  // optional, custom data
});

// List invoices
await client.invoices.list({
  page?: 1,
  limit?: 50,
});

// Get single invoice
await client.invoices.get(invoiceId);

// Get transactions for invoice
await client.invoices.listTransactions(invoiceId);

// Rescan invoice for payments
await client.invoices.rescan(invoiceId, {
  chain: 'ethereum',
  txHash?: '0x...',      // optional, specific transaction
  fromBlock?: 18000000,  // optional, start block
});

x402.facilitator (no auth)

Handle x402 payment protocol operations.
// Check if x402 is supported
await client.x402.facilitator.supported();

// Verify payment requirements
await client.x402.facilitator.verify({
  x402Version: 'v1',
  paymentPayload: {...},
  paymentRequirements: {...},
});

// Settle payment
const response = await client.x402.facilitator.settle({
  x402Version: 'v1',
  paymentPayload: {...},
  paymentRequirements: {...},
});

// Check payment status by nonce
await client.x402.facilitator.paymentStatus({ nonce: '...' });
settle() returns a SettlementResponse for both 200 (settled) and 422 (settlement failed). Always check the success field before assuming settlement completed. Other 4xx/5xx responses throw errors.

x402.endpoints (requires secret key)

Register and manage payment-gated API endpoints.
// Register endpoint for x402 protection
await client.x402.endpoints.register({
  endpointUrl: 'https://api.example.com/v1/analyze',
  asset: 'USDC',
  network: 'ethereum',
  amountUsd: '0.05',
  description?: 'AI analysis endpoint',
});

// List registered endpoints
await client.x402.endpoints.list();

// Deactivate endpoint
await client.x402.endpoints.deactivate(endpointId);

// Get requirements by URL
await client.x402.endpoints.requirements({
  url: 'https://api.example.com/v1/analyze',
});

// Get requirements by endpoint ID
await client.x402.endpoints.requirementsById(endpointId);

Error Handling

The SDK provides typed error classes for different failure scenarios:
import {
  SwiftPay,
  SwiftPayError,
  SwiftPayValidationError,
  SwiftPayAuthError,
  SwiftPayNotFoundError,
  SwiftPayConfigError,
  SwiftPayServerError,
} from '@swiftpayfi/api-client';

const client = new SwiftPay({ secretKey: process.env.SWIFTPAY_SECRET_KEY });

try {
  await client.invoices.create({
    amount: '100.00',
    token: 'INVALID',  // This will throw
    network: 'ethereum',
    recipients: { evm: '0x...' },
  });
} catch (e) {
  if (e instanceof SwiftPayValidationError) {
    console.error('Validation error:', e.details);
  } else if (e instanceof SwiftPayAuthError) {
    console.error('Auth failed — check your secret key');
  } else if (e instanceof SwiftPayConfigError) {
    console.error('Configuration error — missing required field');
  } else if (e instanceof SwiftPayServerError) {
    console.error('Server error:', e.status);
  } else if (e instanceof SwiftPayError) {
    console.error('SwiftPay error:', e.message, e.traceId);
  }
}

Common Patterns

Invoice Polling

Track payment status by polling /invoices/{id}/transactions:
async function pollForPayment(invoiceId, maxAttempts = 60) {
  for (let i = 0; i < maxAttempts; i++) {
    const invoice = await client.invoices.get(invoiceId);
    
    if (invoice.status === 'paid' || invoice.status === 'completed') {
      console.log('Payment received!');
      return invoice;
    }
    
    // Wait 1 second before polling again
    await new Promise(resolve => setTimeout(resolve, 1000));
  }
  
  throw new Error('Payment timeout');
}

Webhook Verification

Verify webhook signatures to ensure requests came from SwiftPay:
import crypto from 'crypto';

function verifyWebhook(body: string, signature: string, secret: string) {
  const computed = crypto
    .createHmac('sha256', secret)
    .update(body)
    .digest('hex');
  
  return crypto.timingSafeEqual(
    Buffer.from(signature),
    Buffer.from(computed)
  );
}

Full API Reference

For complete type definitions, advanced patterns, and parameter details, see the official Node.js SDK on NPM. All APIs are in v0.1.0-beta — stable and production-ready.