> ## Documentation Index
> Fetch the complete documentation index at: https://docs.4mica.io/llms.txt
> Use this file to discover all available pages before exploring further.

# X402 flow

> Pay a 402 Payment Required response with client.fetch, or sign the payment header yourself with X402Flow.

# X402 flow

The SDK implements the `4mica-credit` x402 scheme, versions 1 and 2. There are two ways to use it:

* **`client.fetch`** on a `FourMica` session sends a request, pays a 4Mica 402 within your spend limits, and retries.
* **`X402Flow`** turns the payment requirements from a 402 into a signed payment header, and leaves the HTTP calls to you.

## Pay with `client.fetch`

`fetch` takes a URL, a `method` keyword, and any other keyword argument `httpx.AsyncClient.request` accepts. It returns the `httpx.Response`.

```python theme={null}
import os

from fourmica_sdk import FourMica, SpendLimits

async with await FourMica.connect(
    private_key=os.environ["PRIVATE_KEY"],
    network="base-sepolia",
    spend=SpendLimits(per_payment="0.10 USDC", total="5 USDC"),
) as client:
    response = await client.fetch(
        "https://api.example.com/search",
        method="POST",
        json={"query": "weather in Lisbon"},
    )
    paid = client.payment_for(response)
    if paid:
        print("paid", paid.amount, paid.asset.symbol, "to", paid.pay_to)
```

When the answer is a 402, `fetch` reads the offers, signs a payment for the first `4mica-credit` offer the limits allow, and sends the request once more with the same body. A 402 that is not a `4mica-credit` offer on a network the session has open comes back untouched. The session has open the network it connected to, plus any network a call has named with `network=`.

`client.payment_for(response)` returns a `PaymentRecord` (`amount`, `asset`, `pay_to`, `network`) for a response the seller charged for, or `None`.

### Spend limits

`fetch` only pays within the session's `SpendLimits`. The default is at most 1 USDC per payment, and nothing in any other asset.

| Field | Meaning |
| - | - |
| `per_payment` | The most one payment may be, as one amount or a list. It also names the assets the session may pay in. |
| `total` | One budget per entry for the whole session, across every network it pays on. Once set, an asset no entry names is refused. |
| `pay_to` | When set, the only payee addresses the session pays. |

```python theme={null}
SpendLimits(
    per_payment=["0.10 USDC", "0.10 USDT"],
    total=["5 USDC", "5 USDT"],
    pay_to=["0xSeller..."],
)
```

A payment over a limit raises `SpendLimitError` before anything is signed. Its `limit` attribute is `"per_payment"`, `"total"`, `"assets"`, or `"pay_to"`.

`total` counts every payment the session sends to a seller, whatever the seller answers, because the seller holds a signed payment. A payment that was never sent because signing failed is released. The count lives in memory: a new `connect` starts from zero. See [spend limits](https://docs.4mica.io/buyer/make-paid-requests-automatically.md#spend-limits) for how to choose them.

### What `fetch` does for you

* **Checkpoints.** When the seller refuses a payment because core wants a checkpoint, `fetch` signs the checkpoint and pays once more under the refused payment's request id. Core issues one guarantee per request id, so the seller can redeem only one of the two, and `total` counts one.
* **Redirects.** `fetch` follows none unless you pass `follow_redirects=True` or an `http_client` that follows them. A 402 from another origin than the URL you asked for is not paid. The paid retry follows no redirect, so the payment is never forwarded.
* **Bodies.** The request body is read into memory once, so the retry sends the same bytes even for a file or a generator.
* **Timeouts.** The session's own HTTP client allows five minutes for an answer, since a paid request can be slow.

## Sign the header yourself

`X402Flow` handles the client-side protocol without sending your request. Create a flow from a `Client`:

```python theme={null}
from fourmica_sdk import X402Flow

client = await session.low_level()  # or a Client you built with ConfigBuilder
flow = X402Flow.from_client(client)
```

There is no setup step per seller: each payment carries a random `req_id` minted locally, and uniqueness is all core asks of it. The only read before signing is the asset's active settlement cycle. The flow builds the payment with `client.new_payment`, scoped to that cycle and stamped by core's clock, and signs it with the client as the payer. Both signing methods raise `X402Error` unless the scheme is exactly `4mica-credit`.

### What the SDK expects

At minimum, the payment requirements must include:

* `scheme` (exactly `4mica-credit`) and `network`.
* `payTo` (recipient address), `asset`, and `maxAmountRequired` (v1) or `amount` (v2).
* Optionally `extra.validation` (`{ validator, subject, deadline?, params? }`) to gate the payment on an external validator.

### Version 1

Version 1 returns payment requirements in the JSON response body. Sign them into an `X-PAYMENT` header.

```python theme={null}
import httpx

from fourmica_sdk import PaymentRequirementsV1

async with httpx.AsyncClient() as http:
    # 1) GET the protected endpoint and parse the JSON body
    res = await http.get("https://resource-url/resource")
    body = res.json()

    # 2) Select a payment option
    requirements = PaymentRequirementsV1.from_raw(body["accepts"][0])

    # 3) Build the X-PAYMENT header
    payment = await flow.sign_payment(requirements)

    # 4) Call the protected resource with the header
    await http.get(
        "https://resource-url/resource",
        headers={"X-PAYMENT": payment.header},
    )
```

### Version 2

Version 2 delivers requirements in a base64-encoded `payment-required` header and signs them into a `PAYMENT-SIGNATURE` header. If `accepted.extra["validation"]` is present, the SDK attaches the validation requirement to the signed payment.

```python theme={null}
import base64
import json

from fourmica_sdk import X402PaymentRequired

# 1) GET the protected endpoint and read the payment-required header
res = await http.get("https://resource-url/resource")
header = res.headers.get("payment-required")
if header is None:
    raise RuntimeError("missing payment-required header")

# 2) Decode and parse the challenge
payment_required = X402PaymentRequired.from_raw(json.loads(base64.b64decode(header)))

# 3) Select a payment option
accepted = payment_required.accepts[0]

# 4) Build the PAYMENT-SIGNATURE header
signed = await flow.sign_payment_v2(payment_required, accepted)

# 5) Call the protected resource with the header
await http.get(
    "https://resource-url/resource",
    headers={"PAYMENT-SIGNATURE": signed.header},
)
```

`X402PaymentRequired.from_raw` raises `X402Error` when the challenge has no `x402Version` or no `resource.url`.

To sign again for a payment the seller refused, pass the first payment's request id: `flow.sign_payment(requirements, req_id=payment.payload.payload.req_id)`. Core issues one guarantee per request id, so the seller can redeem only one of the two.

## Settle through a facilitator

If your resource server proxies to a facilitator, reuse the SDK to settle a payment after verifying it. `settle_payment` POSTs `{ x402Version, paymentPayload, paymentRequirements }` to `{facilitator_url}/settle`. `paymentPayload` is the envelope object, not the base64 header.

```python theme={null}
from fourmica_sdk import PaymentRequirementsV1, X402Flow, X402SignedPayment


async def settle(
    flow: X402Flow,
    facilitator_url: str,
    requirements: PaymentRequirementsV1,
    payment: X402SignedPayment,
) -> None:
    settled = await flow.settle_payment(payment, requirements, facilitator_url)
    if not settled.settlement.success:
        # error_reason is a code such as invalid_4mica_credit_checkpoint_required;
        # retryable and details say whether and how the payer can act on it.
        print(
            "settlement rejected:",
            settled.settlement.error_reason,
            settled.settlement.error_message,
        )
        return
    # settled.settlement.receipt is core's GuaranteeReceipt, read from
    # the facilitator's extra.receipt
```

The signed payment carries the request in two forms: `payment.envelope` is the wire object the facilitator takes, and `payment.payload` is the typed `PaymentRequest`. When the facilitator relays core's receipt, `settlement.receipt` holds it as a `GuaranteeReceipt`. Check it with `client.payment.verify_guarantee`.

> [!NOTE]
>
> `settle_payment` only hits `/settle`. Resource servers should still verify a
> payment before granting access. Rejections come back as HTTP 200 with
> `success: false`, so check `settlement.success`, not just the absence of an
> exception.

A flow built with `X402Flow.from_client` opens its own `httpx.AsyncClient` as `flow.http`. Close it with `await flow.http.aclose()`, or pass your own client as the second argument: `X402Flow(client, http)`.

## Next steps

> [card] [Client operations](https://docs.4mica.io/sdks/python/client-operations.md)
>
> Deposit collateral, sign payments, and settle cleared cycles.

> [card] [Errors](https://docs.4mica.io/sdks/python/errors.md)
>
> Handle spend-limit refusals, coded refusals, and unknown outcomes.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.