x402


Namex402 JSON
Version 0.1.4 PyPI version JSON
download
home_pageNone
Summaryx402: An internet native payments protocol
upload_time2025-07-16 18:52:11
maintainerNone
docs_urlNone
authorCoinbase Developer Platform
requires_python>=3.10
licenseApache-2.0
keywords cdp crypto payments sdk web3 x402
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # x402 Python

Python package for the x402 payments protocol.

## Installation

```bash
pip install x402
```

## Overview

The x402 package provides the core building blocks for implementing the x402 Payment Protocol in Python. It's designed to be used by:

- FastAPI middleware for accepting payments
- Flask middleware for accepting payments
- httpx client for paying resources
- requests client for paying resources

## FastAPI Integration

The simplest way to add x402 payment protection to your FastAPI application:

```py
from fastapi import FastAPI
from x402.fastapi.middleware import require_payment

app = FastAPI()
app.middleware("http")(
    require_payment(price="0.01", pay_to_address="0x209693Bc6afc0C5328bA36FaF03C514EF312287C")
)

@app.get("/")
async def root():
    return {"message": "Hello World"}
```

To protect specific routes:

```py
app.middleware("http")(
    require_payment(price="0.01",
    pay_to_address="0x209693Bc6afc0C5328bA36FaF03C514EF312287C"),
    path="/foo"  # <-- this can also be a list ex: ["/foo", "/bar"]
)
```

## Flask Integration

The simplest way to add x402 payment protection to your Flask application:

```py
from flask import Flask
from x402.flask.middleware import PaymentMiddleware

app = Flask(__name__)

# Initialize payment middleware
payment_middleware = PaymentMiddleware(app)

# Add payment protection for all routes
payment_middleware.add(
    price="$0.01",
    pay_to_address="0x209693Bc6afc0C5328bA36FaF03C514EF312287C",
)

@app.route("/")
def root():
    return {"message": "Hello World"}
```

To protect specific routes:

```py
# Protect specific endpoint
payment_middleware.add(
    path="/foo",
    price="$0.001",
    pay_to_address="0x209693Bc6afc0C5328bA36FaF03C514EF312287C",
)
```

## Client Integration

### Simple Usage

#### Httpx Client
```py
from eth_account import Account
from x402.clients.httpx import x402HttpxClient

# Initialize account
account = Account.from_key("your_private_key")

# Create client and make request
async with x402HttpxClient(account=account, base_url="https://api.example.com") as client:
    response = await client.get("/protected-endpoint")
    print(await response.aread())
```

#### Requests Session Client
```py
from eth_account import Account
from x402.clients.requests import x402_requests

# Initialize account
account = Account.from_key("your_private_key")

# Create session and make request
session = x402_requests(account)
response = session.get("https://api.example.com/protected-endpoint")
print(response.content)
```

### Advanced Usage

#### Httpx Extensible Example
```py
import httpx
from eth_account import Account
from x402.clients.httpx import x402_payment_hooks

# Initialize account
account = Account.from_key("your_private_key")

# Create httpx client with x402 payment hooks
async with httpx.AsyncClient(base_url="https://api.example.com") as client:
    # Add payment hooks directly to client
    client.event_hooks = x402_payment_hooks(account)
    
    # Make request - payment handling is automatic
    response = await client.get("/protected-endpoint")
    print(await response.aread())
```

#### Requests Session Extensible Example
```py
import requests
from eth_account import Account
from x402.clients.requests import x402_http_adapter

# Initialize account
account = Account.from_key("your_private_key")

# Create session and mount the x402 adapter
session = requests.Session()
adapter = x402_http_adapter(account)

# Mount the adapter for both HTTP and HTTPS
session.mount("http://", adapter)
session.mount("https://", adapter)

# Make request - payment handling is automatic
response = session.get("https://api.example.com/protected-endpoint")
print(response.content)
```

## Manual Server Integration

If you're not using the FastAPI middleware, you can implement the x402 protocol manually. Here's what you'll need to handle:

1. Return 402 error responses with the appropriate response body
2. Use the facilitator to validate payments
3. Use the facilitator to settle payments
4. Return the appropriate response header to the caller

Here's an example of manual integration:

```py
from typing import Annotated
from fastapi import FastAPI, Request
from x402.types import PaymentRequiredResponse, PaymentRequirements
from x402.encoding import safe_base64_decode

payment_requirements = PaymentRequirements(...)
facilitator = FacilitatorClient(facilitator_url)

@app.get("/foo")
async def foo(req: request: Request):
    payment_required = PaymentRequiredResponse(
        x402_version: 1,
        accepts=[payment_requirements],
        error="",
    )
    payment_header = req.headers.get("X-PAYMENT", "")

    if payment_header == "":
        payment_required.error = "X-PAYMENT header not set"
        return JSONResponse(
            content=payment_required.model_dump(by_alias=True),
            status_code=402,
        )
    
    payment = PaymentPayload(**json.loads(safe_base64_decode(payment_header)))

    verify_response = await facilitator.verify(payment, payment_requirements)
    if not verify_response.is_valid:
        payment_required.error = "Invalid payment"
        return JSONResponse(
            content=payment_required.model_dump(by_alias=True),
            status_code=402,
        )

    settle_response = await facilitator.settle(payment, payment_requirements)
    if settle_response.success:
        response.headers["X-PAYMENT-RESPONSE"] = base64.b64encode(
            settle_response.model_dump_json().encode("utf-8")
        ).decode("utf-8")
    else:
        payment_required.error = "Settle failed: " + settle_response.error
        return JSONResponse(
            content=payment_required.model_dump(by_alias=True),
            status_code=402,
        )
```

For more examples and advanced usage patterns, check out our [examples directory](https://github.com/coinbase/x402/tree/main/examples/python).
            

Raw data

            {
    "_id": null,
    "home_page": null,
    "name": "x402",
    "maintainer": null,
    "docs_url": null,
    "requires_python": ">=3.10",
    "maintainer_email": null,
    "keywords": "cdp, crypto, payments, sdk, web3, x402",
    "author": "Coinbase Developer Platform",
    "author_email": "erik <erik.reppel@coinbase.com>",
    "download_url": "https://files.pythonhosted.org/packages/46/41/429566029142dbbd1f06686814ebd9a47fdc019f02fdd9af664bd40ff09b/x402-0.1.4.tar.gz",
    "platform": null,
    "description": "# x402 Python\n\nPython package for the x402 payments protocol.\n\n## Installation\n\n```bash\npip install x402\n```\n\n## Overview\n\nThe x402 package provides the core building blocks for implementing the x402 Payment Protocol in Python. It's designed to be used by:\n\n- FastAPI middleware for accepting payments\n- Flask middleware for accepting payments\n- httpx client for paying resources\n- requests client for paying resources\n\n## FastAPI Integration\n\nThe simplest way to add x402 payment protection to your FastAPI application:\n\n```py\nfrom fastapi import FastAPI\nfrom x402.fastapi.middleware import require_payment\n\napp = FastAPI()\napp.middleware(\"http\")(\n    require_payment(price=\"0.01\", pay_to_address=\"0x209693Bc6afc0C5328bA36FaF03C514EF312287C\")\n)\n\n@app.get(\"/\")\nasync def root():\n    return {\"message\": \"Hello World\"}\n```\n\nTo protect specific routes:\n\n```py\napp.middleware(\"http\")(\n    require_payment(price=\"0.01\",\n    pay_to_address=\"0x209693Bc6afc0C5328bA36FaF03C514EF312287C\"),\n    path=\"/foo\"  # <-- this can also be a list ex: [\"/foo\", \"/bar\"]\n)\n```\n\n## Flask Integration\n\nThe simplest way to add x402 payment protection to your Flask application:\n\n```py\nfrom flask import Flask\nfrom x402.flask.middleware import PaymentMiddleware\n\napp = Flask(__name__)\n\n# Initialize payment middleware\npayment_middleware = PaymentMiddleware(app)\n\n# Add payment protection for all routes\npayment_middleware.add(\n    price=\"$0.01\",\n    pay_to_address=\"0x209693Bc6afc0C5328bA36FaF03C514EF312287C\",\n)\n\n@app.route(\"/\")\ndef root():\n    return {\"message\": \"Hello World\"}\n```\n\nTo protect specific routes:\n\n```py\n# Protect specific endpoint\npayment_middleware.add(\n    path=\"/foo\",\n    price=\"$0.001\",\n    pay_to_address=\"0x209693Bc6afc0C5328bA36FaF03C514EF312287C\",\n)\n```\n\n## Client Integration\n\n### Simple Usage\n\n#### Httpx Client\n```py\nfrom eth_account import Account\nfrom x402.clients.httpx import x402HttpxClient\n\n# Initialize account\naccount = Account.from_key(\"your_private_key\")\n\n# Create client and make request\nasync with x402HttpxClient(account=account, base_url=\"https://api.example.com\") as client:\n    response = await client.get(\"/protected-endpoint\")\n    print(await response.aread())\n```\n\n#### Requests Session Client\n```py\nfrom eth_account import Account\nfrom x402.clients.requests import x402_requests\n\n# Initialize account\naccount = Account.from_key(\"your_private_key\")\n\n# Create session and make request\nsession = x402_requests(account)\nresponse = session.get(\"https://api.example.com/protected-endpoint\")\nprint(response.content)\n```\n\n### Advanced Usage\n\n#### Httpx Extensible Example\n```py\nimport httpx\nfrom eth_account import Account\nfrom x402.clients.httpx import x402_payment_hooks\n\n# Initialize account\naccount = Account.from_key(\"your_private_key\")\n\n# Create httpx client with x402 payment hooks\nasync with httpx.AsyncClient(base_url=\"https://api.example.com\") as client:\n    # Add payment hooks directly to client\n    client.event_hooks = x402_payment_hooks(account)\n    \n    # Make request - payment handling is automatic\n    response = await client.get(\"/protected-endpoint\")\n    print(await response.aread())\n```\n\n#### Requests Session Extensible Example\n```py\nimport requests\nfrom eth_account import Account\nfrom x402.clients.requests import x402_http_adapter\n\n# Initialize account\naccount = Account.from_key(\"your_private_key\")\n\n# Create session and mount the x402 adapter\nsession = requests.Session()\nadapter = x402_http_adapter(account)\n\n# Mount the adapter for both HTTP and HTTPS\nsession.mount(\"http://\", adapter)\nsession.mount(\"https://\", adapter)\n\n# Make request - payment handling is automatic\nresponse = session.get(\"https://api.example.com/protected-endpoint\")\nprint(response.content)\n```\n\n## Manual Server Integration\n\nIf you're not using the FastAPI middleware, you can implement the x402 protocol manually. Here's what you'll need to handle:\n\n1. Return 402 error responses with the appropriate response body\n2. Use the facilitator to validate payments\n3. Use the facilitator to settle payments\n4. Return the appropriate response header to the caller\n\nHere's an example of manual integration:\n\n```py\nfrom typing import Annotated\nfrom fastapi import FastAPI, Request\nfrom x402.types import PaymentRequiredResponse, PaymentRequirements\nfrom x402.encoding import safe_base64_decode\n\npayment_requirements = PaymentRequirements(...)\nfacilitator = FacilitatorClient(facilitator_url)\n\n@app.get(\"/foo\")\nasync def foo(req: request: Request):\n    payment_required = PaymentRequiredResponse(\n        x402_version: 1,\n        accepts=[payment_requirements],\n        error=\"\",\n    )\n    payment_header = req.headers.get(\"X-PAYMENT\", \"\")\n\n    if payment_header == \"\":\n        payment_required.error = \"X-PAYMENT header not set\"\n        return JSONResponse(\n            content=payment_required.model_dump(by_alias=True),\n            status_code=402,\n        )\n    \n    payment = PaymentPayload(**json.loads(safe_base64_decode(payment_header)))\n\n    verify_response = await facilitator.verify(payment, payment_requirements)\n    if not verify_response.is_valid:\n        payment_required.error = \"Invalid payment\"\n        return JSONResponse(\n            content=payment_required.model_dump(by_alias=True),\n            status_code=402,\n        )\n\n    settle_response = await facilitator.settle(payment, payment_requirements)\n    if settle_response.success:\n        response.headers[\"X-PAYMENT-RESPONSE\"] = base64.b64encode(\n            settle_response.model_dump_json().encode(\"utf-8\")\n        ).decode(\"utf-8\")\n    else:\n        payment_required.error = \"Settle failed: \" + settle_response.error\n        return JSONResponse(\n            content=payment_required.model_dump(by_alias=True),\n            status_code=402,\n        )\n```\n\nFor more examples and advanced usage patterns, check out our [examples directory](https://github.com/coinbase/x402/tree/main/examples/python).",
    "bugtrack_url": null,
    "license": "Apache-2.0",
    "summary": "x402: An internet native payments protocol",
    "version": "0.1.4",
    "project_urls": null,
    "split_keywords": [
        "cdp",
        " crypto",
        " payments",
        " sdk",
        " web3",
        " x402"
    ],
    "urls": [
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "2541f5e84cb49258d4452ef9421a19b2c940e6c2572394f7bc1b4d21c379ffc8",
                "md5": "30c2c778f7f15a9c7d8df80d17bd4bd6",
                "sha256": "2b8d4d8bceadb67ffe9437131ad0496c7b18bd46ba3bcbd3c795d9af31cb645e"
            },
            "downloads": -1,
            "filename": "x402-0.1.4-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "30c2c778f7f15a9c7d8df80d17bd4bd6",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.10",
            "size": 1843550,
            "upload_time": "2025-07-16T18:52:09",
            "upload_time_iso_8601": "2025-07-16T18:52:09.688501Z",
            "url": "https://files.pythonhosted.org/packages/25/41/f5e84cb49258d4452ef9421a19b2c940e6c2572394f7bc1b4d21c379ffc8/x402-0.1.4-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "4641429566029142dbbd1f06686814ebd9a47fdc019f02fdd9af664bd40ff09b",
                "md5": "9718b58cb804b9e79ca509631a18ef6c",
                "sha256": "1799b8b5249f090c6fc30f49e38bf84b5a96317fc7e1895cfaf3614965395e10"
            },
            "downloads": -1,
            "filename": "x402-0.1.4.tar.gz",
            "has_sig": false,
            "md5_digest": "9718b58cb804b9e79ca509631a18ef6c",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.10",
            "size": 1963565,
            "upload_time": "2025-07-16T18:52:11",
            "upload_time_iso_8601": "2025-07-16T18:52:11.438840Z",
            "url": "https://files.pythonhosted.org/packages/46/41/429566029142dbbd1f06686814ebd9a47fdc019f02fdd9af664bd40ff09b/x402-0.1.4.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2025-07-16 18:52:11",
    "github": false,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "lcname": "x402"
}
        
Elapsed time: 1.90983s