Client Usage

The @shade402/client package provides HTTP clients for making X402 payment requests. It offers two client types: explicit (manual control) and automatic (automatic payment handling).

Installation

pnpm add @shade402/client @shade402/core @solana/web3.js

Client Types

Explicit Client

The X402Client provides manual control over the payment flow. You explicitly check for 402 responses, create payments, and retry requests.

Automatic Client

The X402AutoClient automatically handles the payment flow. When it receives a 402 response, it automatically creates a payment and retries the request.

Explicit Client

Basic Usage

import { X402Client } from '@shade402/client';
import { Keypair } from '@solana/web3.js';

const wallet = Keypair.generate();
const client = new X402Client(wallet, process.env.SOLANA_RPC_URL);

try {
  // Make initial request
  let response = await client.get('https://api.example.com/data');

  // Check if payment required
  if (client.paymentRequired(response)) {
    // Parse payment request
    const paymentRequest = client.parsePaymentRequest(response);

    // Create payment
    const authorization = await client.createPayment(paymentRequest);

    // Retry with payment
    response = await client.get('https://api.example.com/data', {
      payment: authorization,
    });
  }

  // Process response
  console.log(response.data);
} finally {
  // Always close the client
  await client.close();
}

HTTP Methods

The explicit client supports all HTTP methods:

Options

Request options include standard Axios options plus:

Local Development

For local development with localhost URLs, enable allowLocal:

Automatic Client

Basic Usage

Configuration Options

HTTP Methods

Error Handling

The automatic client throws errors for payment issues:

Resource Encryption

Both clients support resource encryption:

Payment Amount Control

You can specify a custom payment amount:

URL Validation

The client validates URLs to prevent SSRF attacks:

  • Only allows http:// and https:// schemes

  • Blocks localhost and private IPs (unless allowLocal is enabled)

  • Validates URL format

For local development, enable allowLocal:

Cleanup

Always close the client when done to cleanup connections:

Complete Example

Best Practices

  1. Always close the client when done

  2. Use maximum payment amounts as safety limits

  3. Store wallet keys securely (never in code)

  4. Use allowLocal only for local development

  5. Handle errors appropriately

  6. Monitor payment amounts and transactions

  7. Use the automatic client for simpler workflows

  8. Use the explicit client for fine-grained control

Next Steps

Last updated