* chore: renamed python/x402 to python/legacy * feat: initial Python core SDK * feat: added core HTTP wrappers * feat: added core types * feat: added evm mechanism for exact v1/v2 * feat: added httpx client * feat: added requests client * feat: added fastapi middleware * feat: added flask middleware * feat: added integration tests * feat: added Python SDK to e2e tests * python-v2: fix workflow checks (#863) * fix format * fix lint * fix build * fix pytest * Fix syntax errors and missing imports in manual integration example (#902) - Add missing imports (base64, json, Response, JSONResponse, PaymentPayload, FacilitatorClient) - Fix function signature syntax error - Fix dict initialization syntax (colon to equals) - Add missing return statement after successful payment - Remove trailing whitespace * feat: add Python SDK v2 server examples (FastAPI, Flask) (#879) * feat: add fastapi example project configuration * feat: add fastapi example with x402 payment middleware * docs: add comprehensive README for fastapi example * feat: add flask example project configuration * feat: add flask example with x402 payment middleware * docs: add comprehensive README for flask example * feat: add test clients for fastapi and flask examples * docs: add test client usage to READMEs * chore - remove python-version and test-client.py * docs - remove test client guide from README.md * chore - remove license and classifier * feat - add description and mime type * feat - update .env-local * feat: add Python v2 client examples (httpx & requests) (#857) * feat: add Python v2 client examples (httpx & requests) Add simple client examples demonstrating httpx (async) and requests (sync) usage with the x402 Python v2 SDK. - examples/python/clients/example.py - Simple example showing both httpx and requests - Uses EthAccountSigner with register_exact_evm_client helper - Minimal configuration required * refactor: split Python client examples into separate directories Address PR review feedback: - Separate httpx/ and requests/ directories - Add pyproject.toml for uv sync support - Add environment variable validation - Add payment response header extraction - Use context manager for requests session cleanup Tested on Base Sepolia testnet: - httpx: tx 0xce49f668aba01c4b0b1af2eb0d9a381f4c62295506a91f20af479e0e834ef350 - requests: tx 0xb83b6feefa5a744b7779ba5b37df33f9c7241f58119454d66102acd97a92f024 * Update examples/python/clients/httpx/main.py Co-authored-by: phdargen <pdargent@icloud.com> * Update examples/python/clients/requests/main.py Co-authored-by: phdargen <pdargent@icloud.com> --------- Co-authored-by: phdargen <pdargent@icloud.com> * feat(python): Make v2 framework and client dependencies optional extras (#901) * python-v2: add svm mechanism (#904) * add svm mechanism * add unit tests * add integration tests * update server examples * add e2e tests * update clients * make EVM/SVM dependencies optional extras * fix legacy uv paths * V2 python bazaar (#929) * add bazaar extension * strip query params for discovery * fix 862 * updated e2e tests * Add advanced Python client examples (#947) * Add advanced Python client examples Implements 5 advanced patterns demonstrating x402 SDK v2 features: - hooks.py: Payment lifecycle hooks (before, after, failure) - preferred_network.py: Custom network preference selector - builder_pattern.py: Network-specific registration with wildcards - error_recovery.py: Error classification and recovery strategies - custom_transport.py: Custom httpx transport with retry/timing Includes: - CLI entry point (index.py) for running examples - Comprehensive test suite (40 unit tests) - E2E integration tests - README documentation All tests passing. * Remove tests and examples beyond TypeScript SDK parity Address PR review feedback: - Remove tests directory (tests belong in SDK, not examples) - Remove custom_transport.py (runtime error, beyond TS parity) - Remove error_recovery.py (duplicate of hooks.py, beyond TS parity) - Update index.py, README.md, pyproject.toml accordingly * Address PR feedback: add SVM support and use optional deps - Update pyproject.toml to use x402[evm,svm,httpx] instead of listing dependencies separately - Add Solana/SVM network examples to preferred_network.py - Support both EVM and SVM signers for cross-chain flexibility - Update .env-local with SOLANA_PRIVATE_KEY option * Python-v2: facilitator example + e2e (#950) * add facilitator example * improve svm signer * add description to DiscoveredResource * add facilitator e2e * add paywall builder (#953) * Add Python custom client example (#954) Demonstrates manual x402 v2 payment flow without convenience wrappers. Shows the 6-step process: 1. Initialize client and register payment schemes 2. Make initial request, receive 402 3. Decode PAYMENT-REQUIRED header 4. Create signed payment payload 5. Retry with PAYMENT-SIGNATURE header 6. Handle success/failure response Useful for integrating with non-standard HTTP libraries or implementing custom retry logic. * feat(v2-sdk): support async dynamic hooks for price and metadata (#900) * feat(http): implement dual class design for sync/async support - Add x402HTTPResourceServer (async) for FastAPI/Starlette - Add x402HTTPResourceServerSync (sync) for Flask/Django - Share common logic via _x402HTTPServerBase - Remove dynamic description/resource (keep only dynamic price/payTo) - Update Flask middleware to use sync server directly - Integrate with enrich_extensions for bazaar support - Add per-route hook_timeout_seconds configuration Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * fix(types): add missing Awaitable import and fix test import sorting - Add Awaitable import to types.py for DynamicPayTo/DynamicPrice type hints - Fix import block sorting in test_async_hooks.py and test_core.py Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * refactor: simplify API by removing unused types and making timeout opt-in Address reviewer feedback from @phdargen: - Remove SyncDynamicPayTo/SyncDynamicPrice (unused types that would require SyncPaymentOption to be useful) - Change hook_timeout_seconds default to None (opt-in, matching TS/Go parity) - Export x402HTTPResourceServerSync from http/__init__.py Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com> * python-v2: make create_facilitator_config work with both V1 and V2 (#968) * make create_facilitator_config work with both V1 and V2 * fix lint * feat: add Python SDK v2 server advanced example (FastAPI) (#952) * feat - add pyproject.toml, uv.lock for advanced example * feat - add bazaar extension * feat - add hooks * feat - add x402 extensions to pyproject.toml * feat - add dynamic pricing feature * feat - add dynamic pay-to and custom money parser features * docs - add README for advanced server example * style - apply lint * chore - add comments for bazaar extension code * fix: python v2 x402HTTPAdapter retry logic (#978) * fix: fix consecutive payment bug in x402HTTPAdapter - Replace instance-level _is_retry flag with per-request header to prevent state leakage between consecutive 402 requests. * tests - add test case for consecutive payment with x402HTTPAdapter * style - apply lint * Python-v2: async lifecycle hooks (#975) * add dual sync/async classes for server/client/facilitator * update integration/e2e tests * add unit tests for core, http and implement wrapHttpxWithPaymentFromConfig/wrapRequestsWithPayment * refactor core server/client/facilitator * refactor x402_http_server/facilitator_client/x402_http_client * update exmamples * add utility function that takes care of html-safe escaping * add sdk readmes * add retry unit tests to httpx client * Update Python SDK Docs for v2 (#976) * Porting docs and updating for v2 changes (#813) * porting docs and updating for v2 changes * update quickstart for sellers * update quickstarts, miniapps, and mcp docs * update doc links * update FAQs * fix getting started docs * update core concepts * remove miniapps guide * update extensions * fix bazaar code examples * fix broken links and yaml file * remove unnecessary protocol layer doc * add migration guide * update documentation for python v2 sdk * testing pr preview * docs(python): remove unused os imports and align with TS tab patterns - Remove unused 'import os' from FastAPI and Flask examples in quickstart-for-sellers - Update bazaar-discovery-layer Python example to use hardcoded '0xYourPrivateKey' to match TypeScript tab consistency * update migration doc * cleanup comments * cleanup readme * fix: Python facilitator e2e code * fix: lint --------- Co-authored-by: phdargen <p.dargent@cern.ch> Co-authored-by: somesome <57699892+sohw400@users.noreply.github.com> Co-authored-by: Logan Kang <kcs93023@gmail.com> Co-authored-by: 1bcMax <viewitter@gmail.com> Co-authored-by: phdargen <pdargent@icloud.com> Co-authored-by: Vladimir Sotnikov <bubert9@gmail.com> Co-authored-by: Shuhei <shuhei0866@gmail.com> Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com> Co-authored-by: Faris Habib <faris.habib@coinbase.com>
294 lines
9.4 KiB
Python
294 lines
9.4 KiB
Python
"""Custom x402 Server Implementation.
|
|
|
|
This example demonstrates how to implement x402 payment handling manually
|
|
without using the pre-built middleware packages like PaymentMiddlewareASGI.
|
|
|
|
It shows you how the payment flow works under the hood:
|
|
1. Check for payment in request headers
|
|
2. If no payment, return 402 with payment requirements
|
|
3. If payment provided, verify with facilitator
|
|
4. Execute handler
|
|
5. Settle payment and add settlement headers to response
|
|
|
|
Use this approach when you need:
|
|
- Complete control over the payment flow
|
|
- Integration with unsupported frameworks
|
|
- Custom error handling or logging
|
|
- Understanding of how x402 works internally
|
|
"""
|
|
|
|
import base64
|
|
import json
|
|
import os
|
|
import sys
|
|
from dataclasses import dataclass, field
|
|
|
|
from dotenv import load_dotenv
|
|
from fastapi import FastAPI, Request, Response
|
|
from fastapi.responses import JSONResponse
|
|
|
|
from x402.http import FacilitatorConfig, HTTPFacilitatorClient
|
|
from x402.mechanisms.evm.exact import ExactEvmServerScheme
|
|
from x402.schemas import Network, PaymentPayload, PaymentRequirements, ResourceConfig
|
|
from x402.server import x402ResourceServer
|
|
|
|
load_dotenv()
|
|
|
|
# Config
|
|
EVM_ADDRESS = os.getenv("EVM_ADDRESS")
|
|
EVM_NETWORK: Network = "eip155:84532" # Base Sepolia
|
|
FACILITATOR_URL = os.getenv("FACILITATOR_URL", "https://x402.org/facilitator")
|
|
|
|
if not EVM_ADDRESS:
|
|
print("โ EVM_ADDRESS environment variable is required")
|
|
sys.exit(1)
|
|
|
|
if not FACILITATOR_URL:
|
|
print("โ FACILITATOR_URL environment variable is required")
|
|
sys.exit(1)
|
|
|
|
print("\n๐ง Custom x402 Server Implementation")
|
|
print("This example demonstrates manual payment handling without middleware.\n")
|
|
print(f"โ
Payment address: {EVM_ADDRESS}")
|
|
print(f"โ
Facilitator: {FACILITATOR_URL}\n")
|
|
|
|
|
|
# Create facilitator client and resource server
|
|
facilitator_client = HTTPFacilitatorClient(FacilitatorConfig(url=FACILITATOR_URL))
|
|
resource_server = x402ResourceServer(facilitator_client).register(
|
|
EVM_NETWORK,
|
|
ExactEvmServerScheme(),
|
|
)
|
|
|
|
|
|
# Route payment configuration
|
|
@dataclass
|
|
class RoutePaymentConfig:
|
|
"""Payment configuration for a route."""
|
|
|
|
scheme: str
|
|
price: str
|
|
network: Network
|
|
pay_to: str
|
|
description: str
|
|
mime_type: str
|
|
|
|
|
|
route_configs: dict[str, RoutePaymentConfig] = {
|
|
"GET /weather": RoutePaymentConfig(
|
|
scheme="exact",
|
|
price="$0.001",
|
|
network=EVM_NETWORK,
|
|
pay_to=EVM_ADDRESS, # type: ignore
|
|
description="Weather data",
|
|
mime_type="application/json",
|
|
),
|
|
}
|
|
|
|
|
|
# Cache for built payment requirements
|
|
@dataclass
|
|
class RouteRequirementsCache:
|
|
"""Cache for route payment requirements."""
|
|
|
|
cache: dict[str, PaymentRequirements] = field(default_factory=dict)
|
|
|
|
|
|
route_requirements = RouteRequirementsCache()
|
|
|
|
|
|
# Create FastAPI app
|
|
app = FastAPI(
|
|
title="Custom x402 Server",
|
|
description="Manual x402 payment handling implementation",
|
|
)
|
|
|
|
|
|
@app.middleware("http")
|
|
async def custom_payment_middleware(request: Request, call_next) -> Response:
|
|
"""Custom payment middleware implementation.
|
|
|
|
Demonstrates the x402 payment flow:
|
|
1. Check for payment in request headers
|
|
2. If no payment, return 402 with payment requirements
|
|
3. If payment provided, verify with facilitator
|
|
4. Execute handler
|
|
5. Settle payment and add settlement headers to response
|
|
"""
|
|
route_key = f"{request.method} {request.url.path}"
|
|
route_config = route_configs.get(route_key)
|
|
|
|
# If route doesn't require payment, continue
|
|
if route_config is None:
|
|
return await call_next(request)
|
|
|
|
print(f"๐ฅ Request received: {route_key}")
|
|
|
|
# Build PaymentRequirements from config (cached for efficiency)
|
|
if route_key not in route_requirements.cache:
|
|
config = ResourceConfig(
|
|
scheme=route_config.scheme,
|
|
price=route_config.price,
|
|
network=route_config.network,
|
|
pay_to=route_config.pay_to,
|
|
)
|
|
built_requirements = resource_server.build_payment_requirements(config)
|
|
if len(built_requirements) == 0:
|
|
print("โ Failed to build payment requirements")
|
|
return JSONResponse(
|
|
status_code=500,
|
|
content={"error": "Server configuration error"},
|
|
)
|
|
route_requirements.cache[route_key] = built_requirements[0]
|
|
|
|
requirements = route_requirements.cache[route_key]
|
|
|
|
# Step 1: Check for payment in headers (v2: PAYMENT-SIGNATURE, v1: X-PAYMENT)
|
|
payment_header = request.headers.get("payment-signature") or request.headers.get("x-payment")
|
|
|
|
if not payment_header:
|
|
print("๐ณ No payment provided, returning 402 Payment Required")
|
|
|
|
# Step 2: Return 402 with payment requirements
|
|
payment_required = resource_server.create_payment_required_response(
|
|
[requirements],
|
|
resource={
|
|
"url": str(request.url),
|
|
"description": route_config.description,
|
|
"mime_type": route_config.mime_type,
|
|
},
|
|
)
|
|
|
|
# Use base64 encoding for the PAYMENT-REQUIRED header (v2 protocol)
|
|
requirements_header = base64.b64encode(
|
|
json.dumps(payment_required.model_dump(by_alias=True)).encode()
|
|
).decode()
|
|
|
|
return JSONResponse(
|
|
status_code=402,
|
|
content={
|
|
"error": "Payment Required",
|
|
"message": "This endpoint requires payment",
|
|
},
|
|
headers={"PAYMENT-REQUIRED": requirements_header},
|
|
)
|
|
|
|
try:
|
|
# Step 3: Verify payment
|
|
print("๐ Payment provided, verifying with facilitator...")
|
|
|
|
payment_payload_dict = json.loads(base64.b64decode(payment_header).decode("utf-8"))
|
|
payment_payload = PaymentPayload.model_validate(payment_payload_dict)
|
|
verify_result = await resource_server.verify_payment(payment_payload, requirements)
|
|
|
|
if not verify_result.is_valid:
|
|
print(f"โ Payment verification failed: {verify_result.invalid_reason}")
|
|
return JSONResponse(
|
|
status_code=402,
|
|
content={
|
|
"error": "Invalid Payment",
|
|
"reason": verify_result.invalid_reason,
|
|
},
|
|
)
|
|
|
|
print("โ
Payment verified successfully")
|
|
|
|
# Step 4: Execute handler
|
|
response = await call_next(request)
|
|
|
|
# Only settle for successful responses (2xx)
|
|
if 200 <= response.status_code < 300:
|
|
# Step 5: Settle payment
|
|
print("๐ฐ Settling payment on-chain...")
|
|
|
|
try:
|
|
settle_result = await resource_server.settle_payment(payment_payload, requirements)
|
|
|
|
print(f"โ
Payment settled: {settle_result.transaction}")
|
|
|
|
# Add settlement headers (v2 protocol uses PAYMENT-RESPONSE)
|
|
settlement_header = base64.b64encode(
|
|
json.dumps(settle_result.model_dump(by_alias=True)).encode()
|
|
).decode()
|
|
|
|
# Create new response with settlement header
|
|
body = b""
|
|
async for chunk in response.body_iterator:
|
|
body += chunk
|
|
|
|
return Response(
|
|
content=body,
|
|
status_code=response.status_code,
|
|
headers={**dict(response.headers), "PAYMENT-RESPONSE": settlement_header},
|
|
media_type=response.media_type,
|
|
)
|
|
|
|
except Exception as e:
|
|
print(f"โ Settlement failed: {e}")
|
|
# Continue with response even if settlement fails
|
|
return response
|
|
|
|
return response
|
|
|
|
except Exception as e:
|
|
print(f"โ Payment processing error: {e}")
|
|
return JSONResponse(
|
|
status_code=500,
|
|
content={
|
|
"error": "Payment Processing Error",
|
|
"message": str(e),
|
|
},
|
|
)
|
|
|
|
|
|
# Routes
|
|
@app.get("/health")
|
|
async def health_check() -> dict[str, str]:
|
|
"""Health check endpoint (no payment required)."""
|
|
return {"status": "ok", "version": "2.0.0"}
|
|
|
|
|
|
@app.get("/weather")
|
|
async def get_weather(city: str = "San Francisco") -> dict:
|
|
"""Protected weather endpoint (requires payment)."""
|
|
print("๐ค๏ธ Executing weather endpoint handler")
|
|
|
|
weather_data = {
|
|
"San Francisco": {"weather": "foggy", "temperature": 60},
|
|
"New York": {"weather": "cloudy", "temperature": 55},
|
|
"London": {"weather": "rainy", "temperature": 50},
|
|
"Tokyo": {"weather": "clear", "temperature": 65},
|
|
}
|
|
|
|
data = weather_data.get(city, {"weather": "sunny", "temperature": 70})
|
|
|
|
from datetime import datetime
|
|
|
|
return {
|
|
"city": city,
|
|
"weather": data["weather"],
|
|
"temperature": data["temperature"],
|
|
"timestamp": datetime.now().isoformat(),
|
|
}
|
|
|
|
|
|
@app.on_event("startup")
|
|
async def startup_event() -> None:
|
|
"""Initialize the resource server on startup."""
|
|
resource_server.initialize()
|
|
print("๐ Resource server initialized\n")
|
|
print("Key implementation steps:")
|
|
print(" 1. โ
Check for payment headers in requests")
|
|
print(" 2. โ
Return 402 with requirements if no payment")
|
|
print(" 3. โ
Verify payments with facilitator")
|
|
print(" 4. โ
Execute handler on successful verification")
|
|
print(" 5. โ
Settle payment and add response headers\n")
|
|
print("Test with: curl http://localhost:4021/weather")
|
|
print("Or use a client from: ../../clients/\n")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
import uvicorn
|
|
|
|
uvicorn.run(app, host="0.0.0.0", port=4021)
|