Rust
Complete examples for accepting x402 payments with Yuzu402 using Rust.
Dependencies
Add to Cargo.toml:
[dependencies]
reqwest = { version = "0.12", features = ["json"] }
tokio = { version = "1", features = ["full"] }
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
anyhow = "1.0"
tokio-tungstenite = "0.21" # For WebSocket support
futures-util = "0.3"Basic Payment Verification
Verify a Payment
use reqwest::Client;
use serde::{Deserialize, Serialize};
use std::env;
use anyhow::Result;
#[derive(Serialize)]
struct PaymentVerification {
payment_proof: String,
amount: u64,
recipient: String,
}
#[derive(Deserialize, Debug)]
struct VerificationResponse {
verified: bool,
transaction_id: Option<String>,
amount: Option<u64>,
#[serde(default)]
error: Option<String>,
}
async fn verify_payment(
payment_proof: &str,
amount: u64,
recipient: &str,
) -> Result<VerificationResponse> {
let client = Client::new();
let api_key = env::var("API_KEY")?;
let request = PaymentVerification {
payment_proof: payment_proof.to_string(),
amount,
recipient: recipient.to_string(),
};
let response = client
.post("https://api.yuzu402.dev/v1/payments/verify")
.header("Content-Type", "application/json")
.header("Authorization", format!("Bearer {}", api_key))
.json(&request)
.send()
.await?;
let data: VerificationResponse = response.json().await?;
if data.verified {
println!("✅ Payment verified!");
println!("Transaction ID: {:?}", data.transaction_id);
println!("Amount: {:?}", data.amount);
} else {
println!("❌ Payment invalid");
}
Ok(data)
}
#[tokio::main]
async fn main() -> Result<()> {
let result = verify_payment(
"BASE64_ENCODED_PAYMENT_PROOF",
1000000,
"YOUR_WALLET_ADDRESS",
)
.await?;
println!("Result: {:?}", result);
Ok(())
}Axum Web Framework Integration
Protected API Endpoint
Actix-Web Integration
Payment-Protected Endpoint
WebSocket for Real-Time Notifications
Basic WebSocket Connection
Error Handling
Robust Error Handling with Retry
Complete Example: Payment-Protected API
Best Practices
Error Handling: Use
Result<T, E>and proper error typesAsync/Await: Leverage Tokio for concurrent operations
Type Safety: Use strong typing with Serde for serialization
Environment Variables: Store API keys securely
Logging: Use the
tracingcrate for structured loggingTesting: Write unit and integration tests
Performance: Use connection pooling and caching
Next Steps
See JavaScript examples for JavaScript/TypeScript integration
See Python examples for Python integration
Check out the API Reference for all endpoints
Read about error handling best practices
Last updated

