Metadata-Version: 2.4
Name: billmyagent
Version: 5.0.2
Summary: x402 payment SDK for billmyagent — auto-pays HTTP 402 challenges with an eth-account signer and gates your own endpoints (FastAPI/Flask)
Project-URL: Homepage, https://billmyagent.ai
Project-URL: Documentation, https://developer.billmyagent.ai/guides
Author: billmyagent
License-Expression: Apache-2.0
License-File: LICENSE
License-File: NOTICE
Keywords: ai-agents,eip-3009,ethereum,payments,usdc,x402
Requires-Python: >=3.10
Requires-Dist: eth-account>=0.13
Requires-Dist: requests>=2.31
Requires-Dist: x402[evm]<3,>=2.13
Provides-Extra: dev
Requires-Dist: mypy>=1.11; extra == 'dev'
Requires-Dist: pytest>=8.0; extra == 'dev'
Requires-Dist: responses>=0.25; extra == 'dev'
Requires-Dist: ruff>=0.6; extra == 'dev'
Requires-Dist: types-requests; extra == 'dev'
Provides-Extra: fastapi
Requires-Dist: fastapi>=0.110; extra == 'fastapi'
Requires-Dist: httpx>=0.27; extra == 'fastapi'
Provides-Extra: flask
Requires-Dist: flask>=3.0; extra == 'flask'
Description-Content-Type: text/markdown

# billmyagent (Python)

x402 payment SDK for Python. Pay x402-gated APIs as a **server/agent** and gate
your **own endpoints** with a paywall. The Python counterpart of
[`@billmyagent/payments-core`](https://www.npmjs.com/package/@billmyagent/payments-core), built on the official
[`x402`](https://pypi.org/project/x402/) library + `eth-account`.

Unlike the browser-oriented JS SDK, the agent here holds its private key
directly — which is why this SDK matters for autonomous Python agents
(LangChain, CrewAI, FastAPI services).

## Install

```bash
pip install billmyagent              # buyer client
pip install 'billmyagent[fastapi]'   # + FastAPI seller middleware
pip install 'billmyagent[flask]'     # + Flask seller middleware
```

The v5 buyer transport supplies `Idempotency-Key` before a payment challenge and
retains a created authorization in memory. Catch `PaymentPendingError` and call
its `retry()` to reuse the exact key, request and signature. Keep an explicit
business key for recovery across calls; do not start another payment while its
outcome is unresolved.

## Upgrading from v4

Version 5 requires an explicit `PaymentPolicy` whenever a signer is configured.
Merchant API keys and bearer tokens belong to the separate `merchant_http`
session; `http` is the public payment transport. Merchant requests stay on the
configured API origin and never follow redirects, including prepared requests.
Base URLs require HTTPS, except for loopback development.

Policies match the exact network identifier in the challenge. Permit only the
protocol versions and chains your application intends to pay:

| Chain | x402 v1 identifier | x402 v2 identifier |
| --- | --- | --- |
| Base | `base` | `eip155:8453` |
| Base Sepolia | `base-sepolia` | `eip155:84532` |

The example below explicitly permits both Base identifiers. The Python seller
middleware emits v2 CAIP-2 identifiers. A v1-only integration can permit just
`base`; a v2-only integration can permit just `eip155:8453`.

Retain an explicit `Idempotency-Key` for each logical business operation. If a
payment becomes uncertain, retain the client and retry the original error:

```python
from billmyagent import PaymentPendingError

try:
    response = client.http.get(url, headers={"Idempotency-Key": operation_key})
except PaymentPendingError as pending:
    response = pending.retry()  # Reuses the same request, key and authorization.
```

Do not sign a new payment or create a new key while that outcome is unresolved.
Authorization state is held in memory; after a process restart, reconcile the
existing business key before authorizing another payment.

Policy budgets are integer strings in the asset's smallest unit. For USDC's six
decimals, `10000` is **0.01 USDC** and `100000` is **0.10 USDC**. The aggregate
budget is tracked in memory by the `PaymentPolicy` instance, including when that
policy is shared by clients. A signed authorization stays reserved while its
outcome is unresolved.

## Pay an x402-gated API (buyer / agent)

```python
import os
from datetime import datetime, timedelta, timezone
from billmyagent import PaymentClient, PaymentPolicy, create_signer

# The private key is held in-process and never leaves it.
signer = create_signer("base", os.environ["PRIVATE_KEY"])
client = PaymentClient(
    signer=signer,
    payment_policy=PaymentPolicy(
        allowed_origins=["https://api.example.com"],
        allowed_networks=["base", "eip155:8453"],  # Base, x402 v1 and v2
        allowed_assets=["0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"],
        allowed_recipients=[merchant_payout_address],
        max_amount_per_payment="10000",
        max_total_amount="100000",
        expires_at=datetime.now(timezone.utc) + timedelta(minutes=15),
    ),
)

# client.http is a requests.Session; any HTTP 402 it hits is paid and retried.
res = client.http.get("https://api.example.com/paid-resource")
paid = bool(res.headers.get("PAYMENT-RESPONSE") or res.headers.get("X-PAYMENT-RESPONSE"))
print(res.json(), "paid:", paid)
```

## Manage your merchant account (REST)

Merchant credentials are sent only to the exact origin configured by
`base_url`. Public x402 requests use a separate credential-free session, and
cross-origin redirects are denied by default.

```python
client = PaymentClient(api_key=os.environ["BMA_API_KEY"], auth_token=jwt)

client.get_payout_settings()
client.update_payout_settings({"base_address": "0x…"})
client.list_payments()
```

## Charge for your endpoints (seller)

FastAPI:

```python
from fastapi import FastAPI
from billmyagent.middleware.fastapi import add_payment_middleware

app = FastAPI()
add_payment_middleware(
    app,
    pay_to="0xYourPayoutAddress",
    routes={"GET /premium": "$0.01"},
    network="base-sepolia",   # base | base-sepolia
)

@app.get("/premium")
def premium():
    return {"unlocked": True}
```

Flask is identical via `billmyagent.middleware.flask.add_payment_middleware`.

> Mainnet (base) settlement needs a facilitator with CDP credentials —
> pass `facilitator_url=...`. Omit it to use the public x402.org testnet facilitator.

## Supported networks

EVM only, `exact` scheme: **base**, **base-sepolia** (testing).

## Development

```bash
pip install -e '.[dev,fastapi,flask]'
pytest && ruff check . && mypy billmyagent
```

## License

BillMyAgent-authored SDK code is licensed under Apache-2.0. See the bundled
LICENSE and NOTICE files for the full terms and upstream attribution.
Previously published versions retain their published license declarations.
