Metadata-Version: 2.4
Name: clawpay-x402
Version: 0.1.0
Summary: ClawPay × x402 client + server SDK — China-localized payment schemes (clawpay-cny, clawpay-dcep, clawpay-cross) on top of the x402 HTTP 402 protocol.
Project-URL: Homepage, https://erc8004.cn/specs/clawpay-x402/
Project-URL: Spec, https://erc8004.cn/specs/clawpay-x402/SPEC.md
Project-URL: Demo, https://erc8004.cn/api/x402/demo
Author: erc8004.cn community
License: CC0-1.0
Keywords: ai-agent,ai-payment,alipay,clawpay,dcep,digital-yuan,erc-8004,http-402,wechat-pay,x402
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: License :: CC0 1.0 Universal (CC0 1.0) Public Domain Dedication
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Topic :: Internet :: WWW/HTTP
Requires-Python: >=3.10
Requires-Dist: httpx>=0.27
Provides-Extra: fastapi
Requires-Dist: fastapi>=0.110; extra == 'fastapi'
Provides-Extra: test
Requires-Dist: fastapi>=0.110; extra == 'test'
Requires-Dist: pytest-asyncio>=0.23; extra == 'test'
Requires-Dist: pytest>=8; extra == 'test'
Requires-Dist: respx>=0.21; extra == 'test'
Description-Content-Type: text/markdown

# `clawpay-x402` — Python SDK

> ClawPay × x402 client + server SDK for the **`clawpay-cny` / `clawpay-dcep` / `clawpay-cross`** schemes.
> Implements the [x402 HTTP 402 protocol](https://www.x402.org/) with China-localized settlement.
>
> Spec: https://erc8004.cn/specs/clawpay-x402/  · License: CC0 · Python ≥ 3.10 · async-first

## Install

```bash
uv add clawpay-x402              # client only
uv add 'clawpay-x402[fastapi]'   # + FastAPI server dependency
# or:  pip install clawpay-x402
```

## Client — pay an x402 endpoint in 3 lines

```python
import asyncio
from clawpay_x402 import x402_pay

async def main():
    r = await x402_pay("https://erc8004.cn/api/x402/demo", from_="clawpay:my-agent")
    print(r.body, r.receipt)

asyncio.run(main())
```

`x402_pay` returns an `X402Result` with: `status`, `body`, `paid`, `payment_requirements`, `receipt`, `response`. It:

1. `GET`s the URL.
2. If `200`, returns the body (no payment needed).
3. If `402`, parses `accepts[]`, picks the first scheme matching `prefer` (default order: `clawpay-cny` → `clawpay-dcep` → `clawpay-cross` → `exact`), builds a `PaymentPayload`, base64-encodes it as `X-PAYMENT`, retries.

**Real settlement** — pass `on_build_payload` to inject a real `transactionId` from your WeChat/Alipay/DCEP processor:

```python
async def hook(req):
    txn = await wechat_pay.charge(amount=req["maxAmountRequired"], payee=req["payTo"])
    return {"transactionId": txn["id"], "rail": "wechat"}

r = await x402_pay(url, from_="clawpay:user_42", on_build_payload=hook)
```

For the `exact` (USDC on Base) scheme, this SDK raises — use Coinbase's official x402 SDK or filter `exact` out via `prefer`.

## Server — protect a FastAPI endpoint in 1 line

```python
from fastapi import FastAPI, Depends, Response
from clawpay_x402.server import x402_dependency

app = FastAPI()
pay = x402_dependency(
    accepts=[{
        "scheme": "clawpay-cny", "network": "clawpay-mainnet",
        "maxAmountRequired": "150", "asset": "CNY", "payTo": "agent:31981",
        "extra": {"facilitator": "https://erc8004.cn/api/x402/facilitator", "humanPrice": "¥1.50"},
    }],
    verify=lambda payload: True,  # replace with real check (sync or async)
)

@app.get("/api/translate")
async def translate(ctx: dict = Depends(pay)) -> Response:
    import json
    return Response(
        content=json.dumps({"output": "Hello, world"}),
        media_type="application/json",
        headers={"X-PAYMENT-RESPONSE": ctx["receipt_header"]},
    )
```

The dependency:
- emits `402` + `accepts[]` when no `X-PAYMENT` header
- decodes & shape-validates the header (rejects malformed / wrong scheme / under-amount / stale `signedAt`)
- calls your `verify` hook (sync or async)
- on success, returns `{"payload", "paymentRequirements", "receipt", "receipt_header"}` to your route

For framework-agnostic use, the lower-level building blocks are exported too:

```python
from clawpay_x402 import build_402_body, decode_payment, verify_shape, encode_receipt
```

## Test

```bash
uv pip install '.[test]'
uv run pytest tests/ -v          # unit tests (no network)
LIVE=1 uv run pytest tests/test_live.py -v   # hits the real erc8004.cn demo
```

## What this SDK is and isn't

| ✅ | ❌ |
|---|---|
| HTTP layer: 402 ↔ X-PAYMENT ↔ X-PAYMENT-RESPONSE | Real WeChat/Alipay/DCEP settlement |
| Shape & freshness validation | Real fraud check (delegate to facilitator) |
| Spec-compliant PaymentPayload encoding | On-chain USDC signing |
| FastAPI dependency + framework-free building blocks | Crypto custody (illegal for CN domestic entities anyway) |
