r402_http/server/mod.rs
1//! Axum middleware for enforcing [x402](https://www.x402.org) payments on protected routes (V2-only).
2//!
3//! This middleware validates incoming payment headers using a configured x402 facilitator,
4//! verifies the payment, executes the request, and settles valid payments after successful
5//! execution. If the handler returns an error (4xx/5xx), settlement is skipped.
6//!
7//! Returns a `402 Payment Required` response if the request lacks a valid payment.
8//!
9//! See [`X402Middleware`] for full configuration options.
10//! For low-level interaction with the facilitator, see [`facilitator::FacilitatorClient`].
11//!
12//! ## Configuration Notes
13//!
14//! - **[`X402Middleware::with_price_tag`]** sets the assets and amounts accepted for payment (static pricing).
15//! - **[`X402Middleware::with_dynamic_price`]** sets a callback for dynamic pricing based on request context.
16//! - **[`X402Middleware::with_base_url`]** sets the base URL for computing full resource URLs.
17//! If not set, defaults to `http://localhost/` (avoid in production).
18//! - **[`X402Middleware::with_supported_cache_ttl`]** configures the TTL for caching facilitator capabilities.
19//! - **[`X402LayerBuilder::with_description`]** is optional but helps the payer understand what is being paid for.
20//! - **[`X402LayerBuilder::with_mime_type`]** sets the MIME type of the protected resource (default: `application/json`).
21//! - **[`X402LayerBuilder::with_resource`]** explicitly sets the full URI of the protected resource.
22
23pub mod facilitator;
24pub mod layer;
25pub mod paygate;
26pub mod pricing;
27
28pub use layer::{X402LayerBuilder, X402Middleware};
29pub use pricing::{DynamicPriceTags, PriceTagSource, StaticPriceTags};
30
31/// Common verification errors shared between protocol versions.
32#[derive(Debug, thiserror::Error)]
33pub enum VerificationError {
34 /// Required payment header is missing.
35 #[error("{0} header is required")]
36 PaymentHeaderRequired(&'static str),
37 /// Payment header is present but malformed.
38 #[error("Invalid or malformed payment header")]
39 InvalidPaymentHeader,
40 /// No matching payment requirements found.
41 #[error("Unable to find matching payment requirements")]
42 NoPaymentMatching,
43 /// Verification with facilitator failed.
44 #[error("Verification failed: {0}")]
45 VerificationFailed(String),
46}
47
48/// Paygate error type that wraps verification and settlement errors.
49#[derive(Debug, thiserror::Error)]
50pub enum PaygateError {
51 /// Payment verification failed.
52 #[error(transparent)]
53 Verification(#[from] VerificationError),
54 /// On-chain settlement failed.
55 #[error("Settlement failed: {0}")]
56 Settlement(String),
57}