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.jsClient 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://andhttps://schemesBlocks localhost and private IPs (unless
allowLocalis enabled)Validates URL format
For local development, enable allowLocal:
Cleanup
Always close the client when done to cleanup connections:
Complete Example
Best Practices
Always close the client when done
Use maximum payment amounts as safety limits
Store wallet keys securely (never in code)
Use
allowLocalonly for local developmentHandle errors appropriately
Monitor payment amounts and transactions
Use the automatic client for simpler workflows
Use the explicit client for fine-grained control
Next Steps
Learn about Explicit Client in detail
Explore Automatic Client features
Check out Security best practices
Last updated
