JavaScript/TypeScript

Complete examples for accepting x402 payments with Yuzu402 using JavaScript and TypeScript.

Installation

# No special installation needed! Just use fetch or your favorite HTTP library
npm install node-fetch  # If using Node.js < 18
npm install ws          # For WebSocket support

Basic Payment Verification

Verify a Payment

async function verifyPayment(
  paymentProof: string,
  expectedAmount: number,
  recipientAddress: string
) {
  const response = await fetch('https://api.yuzu402.dev/v1/payments/verify', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${process.env.API_KEY}`
    },
    body: JSON.stringify({
      payment_proof: paymentProof,
      amount: expectedAmount,
      recipient: recipientAddress
    })
  });

  if (!response.ok) {
    const error = await response.json();
    throw new Error(`Verification failed: ${error.message}`);
  }

  const data = await response.json();
  return data;
}

// Usage
const result = await verifyPayment(
  'BASE64_ENCODED_PAYMENT_PROOF',
  1000000,
  'YOUR_WALLET_ADDRESS'
);

if (result.verified) {
  console.log('Payment verified!');
  console.log('Transaction ID:', result.transaction_id);
  console.log('Amount:', result.amount);
} else {
  console.log('Payment invalid');
}

Express.js Integration

Protect an API Endpoint

Middleware for Payment Protection

WebSocket for Real-Time Notifications

Basic WebSocket Connection

React Hook for Payment Notifications

Error Handling

Robust Error Handling

Complete Example: API with Payments

Best Practices

  1. Environment Variables: Always store API keys in environment variables

  2. Error Handling: Implement retry logic with exponential backoff

  3. Logging: Log all payment verifications for debugging and reconciliation

  4. Validation: Always validate payment amounts match what you expect

  5. Security: Never expose API keys in client-side code

  6. Testing: Test with small amounts first before going live

Next Steps

Last updated