Metadata-Version: 2.4
Name: billmyagent
Version: 5.0.3
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.5
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'
Requires-Dist: httpx>=0.27; 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.

After an authorization is submitted, every non-2xx response raises
`PaymentPendingError`, except HTTP 402 with the JSON boolean
`payment_attempted: false` and no contradictory `error: "payment_pending"`.
That explicit refusal is returned as an ordinary Requests response. Its
same-key authorization and policy budget remain retained; a retry does not
create a replacement signature. Before signing, ordinary HTTP errors keep
normal Requests behavior.

## 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.

With `stream=True`, a connection/body error can occur later while your code
reads the response, outside `PaymentPendingError`. Keep the same client and
explicit operation key, and retry with
`client.http.send(response.request.copy())` to reuse the retained authorization.
This preserves the final URL, method, body and headers after an opt-in redirect;
resending the original redirecting URL with that key is refused as a different
request. Closing a streamed response does not cancel 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; policy-approved 402 challenges are 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.list_payments()
```

Changing a payout address also requires a recent-password-authentication grant:

```python
from getpass import getpass

grant_response = client.merchant_http.post(
    f"{client.base_url}/auth/recent-auth",
    headers={"Authorization": f"Bearer {jwt}"},
    json={"password": getpass("Confirm your password: "), "operation": "payout_settings.update"},
)
grant_response.raise_for_status()
client.update_payout_settings(
    {"base_address": new_payout_address},
    recent_auth=grant_response.json()["recent_auth"],
)
```

Use the same merchant JWT for both calls. The grant expires after ten minutes
and is consumed by one successful protected write. The SDK sends it only on the
specified update; it does not store, refresh or automatically retry it. If the
update response is lost, read the payout settings before deciding whether
another update and a fresh grant are needed.

## 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`.

> For mainnet (base), configure a facilitator that supports that network via
> `facilitator_url=...`. Omit it to use the public x402.org testnet facilitator.

These Python wrappers use the upstream x402 v2 seller middleware. Their default
facilitator is `https://x402.org/facilitator`; they do not route payments through
your BillMyAgent account. Changing only `facilitator_url` to the BillMyAgent
gateway is insufficient: that gateway accepts v1 and requires merchant API-key
authentication, while these wrappers provide neither a version adapter nor an
API-key option.

The upstream Python middleware verifies the payment, runs your protected
handler, and then attempts settlement. If settlement fails, the buyer receives
a failure response even though your handler's side effects have already occurred.
This differs from the BillMyAgent Express middleware's settlement-before-handler
boundary. Use these Python wrappers for handlers that tolerate that ordering;
they do not provide settlement-before-effect or exactly-once execution. Store
business-operation keys and results when your handler must avoid duplicate effects.

The buyer's `client.http` is a synchronous `requests.Session`. In an async
application, run buyer requests in a worker thread; the FastAPI seller wrapper's
async request handling does not make the buyer client asynchronous.

## 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.
