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 supportBasic 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
Environment Variables: Always store API keys in environment variables
Error Handling: Implement retry logic with exponential backoff
Logging: Log all payment verifications for debugging and reconciliation
Validation: Always validate payment amounts match what you expect
Security: Never expose API keys in client-side code
Testing: Test with small amounts first before going live
Next Steps
See Python examples for Python integration
Check out the API Reference for all endpoints
Read about error handling best practices
Last updated

