A. McDermott e9d9b3a5ba
feat: Payment Identifier Extension SDK - Python (#1111)
* feat(python): add payment-identifier extension types and constants

- Add PaymentIdentifierInfo and PaymentIdentifierExtension Pydantic models
- Add constants: PAYMENT_IDENTIFIER, PAYMENT_ID_MIN_LENGTH, PAYMENT_ID_MAX_LENGTH, PAYMENT_ID_PATTERN
- Define PaymentIdentifierSchema type alias

* feat(python): add payment-identifier utility functions

- Add generate_payment_id() to create UUID v4-based payment IDs
- Add is_valid_payment_id() to validate ID format (16-128 chars, alphanumeric + hyphens/underscores)

* feat(python): add payment-identifier JSON Schema definition

- Add payment_identifier_schema compliant with JSON Schema Draft 2020-12
- Schema validates required boolean and optional id string field

* feat(python): add payment-identifier validation and extraction functions

- Add ValidationResult dataclass for validation results
- Add is_payment_identifier_extension() type guard
- Add validate_payment_identifier() for full extension validation
- Add extract_payment_identifier() to extract ID from PaymentPayload
- Add extract_and_validate_payment_identifier() combined function
- Add has_payment_identifier() to check extension presence
- Add is_payment_identifier_required() to check requirement flag
- Add validate_payment_identifier_requirement() for requirement compliance

* feat(python): add payment-identifier client utilities

- Add append_payment_identifier_to_extensions() to append payment ID to extensions dict
- Only appends if server declared the extension
- Generates new ID if not provided

* feat(python): add payment-identifier resource server utilities

- Add declare_payment_identifier_extension() to create extension declaration
- Add PaymentIdentifierResourceServerExtension class implementing ResourceServerExtension protocol
- Add payment_identifier_resource_server_extension singleton instance

* feat(python): add payment-identifier extension main module

- Export all public APIs from payment-identifier extension
- Add comprehensive usage documentation with examples for servers, clients, and idempotency

* feat(python): export payment-identifier extension from extensions module

- Add payment-identifier imports and exports to main extensions __init__.py
- Export all constants, types, functions, and classes for public API

* fix(python): resolve ValidationResult type mismatch in extensions module

- Export payment_identifier.ValidationResult as ValidationResult (matches payment_identifier function return types)
- Export bazaar.ValidationResult as BazaarValidationResult for explicit bazaar usage
- Both ValidationResult classes are structurally equivalent (same dataclass fields)
- Fixes type mismatch where payment_identifier functions returned payment_identifier.ValidationResult but ValidationResult imported from x402.extensions was bazaar.ValidationResult

* refactor(python): rename payment_identifier ValidationResult to PaymentIdentifierValidationResult

- Rename ValidationResult class to PaymentIdentifierValidationResult in payment_identifier/validation.py
- Update all function return types and usages throughout validation.py
- Update exports in payment_identifier/__init__.py
- Update imports/exports in extensions/__init__.py
- Keep ValidationResult from bazaar as default export for backward compatibility
- Export PaymentIdentifierValidationResult separately for explicit payment_identifier usage
- Makes naming consistent with BazaarValidationResult pattern

* test(python): add comprehensive test suite for payment_identifier extension

- Add test_types.py: Test constants and Pydantic models
- Add test_utils.py: Test ID generation and validation functions
- Add test_validation.py: Test all validation and extraction functions
- Add test_client.py: Test client-side utilities
- Add test_server.py: Test server-side utilities
- Tests cover all major functionality including edge cases and error handling
- Follows same structure as bazaar extension tests

* fix(python): fix payment_identifier test helper and assertions

- Fix create_extension_with_id helper to handle invalid IDs for testing
- Update test assertion to check for 'identifier' in error message
- All 67 tests now passing

* fix(python): add ValidationResult alias for backward compatibility

- Add ValidationResult = BazaarValidationResult alias after bazaar import
- Fixes AttributeError when importing ValidationResult from x402.extensions
- ValidationResult was imported as BazaarValidationResult but exported in __all__
- Now both ValidationResult and BazaarValidationResult are available

* test(python): add test to verify __all__ exports are importable

- Add test_exports.py to verify all items in __all__ can be imported
- Tests that ValidationResult alias works correctly
- Tests that 'import *' works as expected
- This would have caught the ValidationResult AttributeError bug

* fix(python): make jsonschema import lazy in payment_identifier validation

- Remove module-level jsonschema import that raised ImportError
- Import jsonschema lazily only when schema validation is needed
- Return validation error instead of raising ImportError at module level
- Allows payment_identifier extension to be imported without jsonschema
- Users can still use non-validation functions without optional dependency

* fix(python): fix linting errors

- Remove unused variable in test_types.py
- Fix import sorting in extensions/__init__.py
- Add noqa comment for intentional E402 (import after alias)

* Lint

* docs(python): add payment-identifier extension examples

Add client and server examples demonstrating how to use the
payment-identifier extension for idempotent payment processing.

Client example shows:
- Generating payment IDs with generate_payment_id()
- Using on_before_payment_creation hook to inject the ID
- Making duplicate requests to demonstrate cache behavior

Server example shows:
- Declaring extension support with declare_payment_identifier_extension()
- Extracting payment IDs with extract_payment_identifier()
- Caching responses after settlement for idempotency

* Lint

* Format

* Changelog
2026-02-11 18:46:46 -05:00
..
2025-12-11 07:41:57 -08:00

X402 Python Examples

This directory contains a collection of Python examples demonstrating how to use the X402 protocol in various contexts. These examples use the Python x402 package and standard Python web frameworks/HTTP clients.

Setup

Before running any examples, ensure you have:

  • Python 3.10+
  • uv package manager installed (see https://github.com/astral-sh/uv)

Then install dependencies for the examples you want to run. You can either:

# Option A: sync each example individually (recommended by each example README)
cd <example-dir>
uv sync

# Option B: run the helper script to sync all examples
cd examples/python
uv run python sync.py

Example Structure

The examples are organized into several categories:

Clients

Examples of different client implementations for interacting with x402-protected services:

  • clients/httpx/ - Two approaches with httpx: a pre-configured x402HttpxClient and an extensible event_hooks integration.
  • clients/requests/ - Two approaches with requests: a simple x402_requests session and an extensible HTTP adapter.

Discovery

  • discovery/ - Uses the facilitator to list available x402-protected resources (Bazaar) with CDP credentials.

Fullstack

  • fullstack/fastapi/ - FastAPI application with x402 middleware protecting routes. Includes simple UI assets.
  • fullstack/flask/ - Flask application with x402 middleware protecting routes. Includes simple UI assets.

Servers

Examples of different server implementations:

  • servers/fastapi/ - FastAPI server using x402 middleware to protect endpoints.
  • servers/flask/ - Flask server using x402 middleware to protect endpoints.
  • servers/advanced/ - FastAPI server without middleware: delayed settlement, dynamic pricing, multiple requirements.
  • servers/mainnet/ - Server example for accepting real USDC on Base mainnet using the Coinbase hosted facilitator.

Running Examples

Each example directory contains its own README with specific instructions. In general:

cd <example-dir>
cp .env-local .env   # then fill in required values
uv sync
uv run python main.py

Some client examples also provide an extensible.py variant that demonstrates lower-level integrations.

Development

This workspace uses:

  • uv for Python environment and dependency management
  • Python 3.10+ and standard tooling

The examples are independent projects; install dependencies per example before running.

A note on private keys

The examples in this folder commonly use private keys to sign messages. Never put a private key with mainnet funds in a .env file. This can result in keys getting checked into codebases and being drained.

Use a development wallet funded on testnets (e.g., Base Sepolia USDC/ETH). You can fund a dev wallet via the testnet CDP Faucet.