feat(middleware): support dynamic payment requirements via async hooks #893
+437
−35
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
feat(middleware): Support Dynamic Payment Requirements via Hooks
1. Problem Statement
The current
require_paymentmiddleware in the x402 Python SDK only accepts static values for parameters likeprice,description, andresource. While this works for simple fixed-price APIs, it limits developers in more complex scenarios:/contents/{id}) where each resource has a unique price and metadata.Currently, developers are forced to bypass the middleware and manually construct 402 responses, which increases implementation errors and reduces the value of the SDK.
2. Proposed Solution: Dynamic Hooks
Extend the middleware parameters to accept Async Callables (Hooks). These hooks are executed at request time, allowing the middleware to generate
PaymentRequirementson-the-fly using therequestcontext.Architecture
sequenceDiagram participant Client as Client participant MW as x402 Middleware participant Hook as Dynamic Hook (User Logic) Client->>MW: Request (GET /contents/123) Note over MW, Hook: Lazy Evaluation at Runtime MW->>Hook: execute(request) Hook-->>MW: price, description, etc. MW->>MW: Generate PaymentRequirements MW-->>Client: 402 Payment Required (Dynamic Info)Key Technical Changes
Union[T, Callable[[Request], Awaitable[T]]].middlewarefunction to ensure it has access to theRequestobject.Request. As FastAPI middleware runs before route matching, specific identifiers (like IDs) should be parsed fromrequest.url.path.price=0.10) continue to work seamlessly.3. Testing Performed
4. Expected Impact
This change enables x402 to power sophisticated content delivery platforms and autonomous agents with fluctuating pricing strategies, making the SDK suitable for production-grade CMS and decentralized media applications.