Explicit Client

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

When to Use

Use the explicit client when you need:

  • Fine-grained control over the payment flow

  • Custom payment logic

  • Different handling for different payment scenarios

  • Integration with custom payment systems

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 {
  await client.close();
}

HTTP Methods

All standard HTTP methods are supported:

Payment Flow

Step 1: Initial Request

Step 2: Check Payment Required

Step 3: Parse Payment Request

Step 4: Validate Payment Request

Step 5: Create Payment

Step 6: Encrypt Resource (Optional)

Step 7: Retry Request

Resource Encryption

The client supports resource encryption for enhanced privacy:

Custom Payment Amount

You can pay less than the maximum amount if allowed:

Error Handling

Handle errors at each step:

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)

For local development:

Complete Example

Best Practices

  1. Always close the client when done

  2. Check payment expiration before paying

  3. Validate payment amounts

  4. Handle errors appropriately

  5. Use resource encryption when available

  6. Never use allowLocal in production

  7. Store wallet keys securely

  8. Monitor payment transactions

Next Steps

Last updated