importorg.openlibx402.client.X402Client;importorg.openlibx402.core.errors.*;importorg.openlibx402.core.models.*;importorg.p2p.solanaj.core.Account;importokhttp3.Response;// Initialize clientAccountaccount=newAccount(secretKey);X402Clientclient=newX402Client(account,"https://api.devnet.solana.com",true// allowLocal for development only);try{// Make requestResponseresponse=client.get("https://api.example.com/premium-data");System.out.println(response.body().string());}catch(PaymentRequiredErrore){// Handle 402 Payment RequiredPaymentRequestrequest=e.getPaymentRequest();// Create paymentPaymentAuthorizationauth=client.createPayment(request);// Retry with paymentResponseretryResponse=client.get("https://api.example.com/premium-data",auth);System.out.println(retryResponse.body().string());}finally{client.close();}
// Development mode - allows local URLsX402ClientdevClient=newX402Client(account,null,true);// Production mode - blocks local URLs (default)X402ClientprodClient=newX402Client(account,null,false);
Security
Never use allowLocal=true in production environments. This protection prevents Server-Side Request Forgery (SSRF) attacks.
importorg.openlibx402.client.X402AutoClient;// Build client with configurationX402AutoClientclient=newX402AutoClient.Builder(account).rpcUrl("https://api.devnet.solana.com").maxPaymentAmount("1.0")// Max 1 USDC per request.maxRetries(3)// Retry up to 3 times.allowLocal(true)// Development only.build();try{// Automatically handles 402 and retriesResponseresponse=client.get("https://api.example.com/premium-data");System.out.println(response.body().string());}finally{client.close();}
// This will throw an error if payment exceeds 1.0 USDCX402AutoClientclient=newX402AutoClient.Builder(account).maxPaymentAmount("1.0").build();try{Responseresponse=client.get(url);}catch(PaymentRequiredErrore){PaymentRequestrequest=e.getPaymentRequest();if(request.getMaxAmountRequired().compareTo("1.0")>0){System.err.println("Payment exceeds limit: "+request.getMaxAmountRequired());}}
// Access the base X402ClientX402ClientbaseClient=autoClient.getBaseClient();// Access the processorSolanaPaymentProcessorprocessor=autoClient.getProcessor();Stringbalance=processor.getBalance(account.getPublicKey());
Use X402Client when you need:
- Fine-grained control over payments
- Custom payment decision logic
- Explicit user approval for payments
- Complex payment workflows
- Integration with existing payment systems
Use X402AutoClient when you need:
- Quick integration with automatic payments
- Simplified error handling
- Built-in retry logic
- Payment limit enforcement
- Reduced boilerplate code
// Thread-safe usageExecutorServiceexecutor=Executors.newFixedThreadPool(10);for(inti=0;i<10;i++){executor.submit(()->{// Each thread gets its own clienttry(X402Clientclient=newX402Client(account,null,false)){Responseresponse=client.get("https://api.example.com/data");// ... process response}catch(Exceptione){e.printStackTrace();}});}