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

> Turn a 402 Payment Required response into a signed payment header with X402Flow.

# X402 flow

`X402Flow` handles the client side of the x402 payment protocol for 4Mica. It turns the payment requirements from a `402 Payment Required` response into a signed payment header, and can call a facilitator's `/settle` endpoint.

Create a flow from your client. Start on Base Sepolia with a test wallet.

```rust theme={null}
use alloy::signers::local::PrivateKeySigner;
use sdk_4mica::{Client, Network, X402Flow};

let signer: PrivateKeySigner = std::env::var("PRIVATE_KEY")?.parse()?;
let client = Client::builder()
    .network(Network::BaseSepolia)
    .signer(signer)
    .connect()
    .await?;

let flow = X402Flow::new(client.clone())?;
```

There is no setup step per seller. Each payment carries a random request id and a blinding salt that the SDK generates. The only read before signing is the asset's active settlement cycle: the flow builds the payment with `client.payment.new_payment`, scoped to that cycle and stamped by core's clock, and signs it with the client as the payer.

The flow makes no HTTP calls to the seller. You send the requests, and the examples below use `reqwest` (with its `json` feature), `serde`, `serde_json`, and `base64`.

> [!WARNING]
>
> The flow signs the amount the requirements ask for, on the network the client
> is connected to. It does not compare `network` with the client's network and
> it applies no spend limit. Check `network`, `payTo`, and the amount yourself
> before you sign.

## What the SDK expects

The requirements types deserialize the canonical x402 JSON (camelCase). At minimum they must include:

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

Any other scheme returns `X402Error::InvalidScheme`.

## Version 1

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

```rust theme={null}
use sdk_4mica::x402::{PaymentRequirements, SCHEME_4MICA_CREDIT};
use serde::Deserialize;

#[derive(Deserialize)]
struct PaymentRequiredBody {
    accepts: Vec<PaymentRequirements>,
}

let url = "https://api.example.com/data";
let http = reqwest::Client::new();

// 1) GET the protected endpoint and parse the JSON body
let body: PaymentRequiredBody = http.get(url).send().await?.json().await?;

// 2) Select a payment option
let requirements = body
    .accepts
    .into_iter()
    .find(|option| option.scheme == SCHEME_4MICA_CREDIT)
    .ok_or("no 4mica-credit payment option")?;

// 3) Build the X-PAYMENT header
let signed = flow.sign_payment(requirements).await?;

// 4) Call the protected resource with the header
let paid = http
    .get(url)
    .header("X-PAYMENT", &signed.header)
    .send()
    .await?
    .error_for_status()?;
```

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

```rust theme={null}
use base64::{Engine as _, engine::general_purpose::STANDARD};
use sdk_4mica::x402::{SCHEME_4MICA_CREDIT, X402PaymentRequiredV2};

// 1) GET the protected endpoint and read the payment-required header
let response = http.get(url).send().await?;
let header = response
    .headers()
    .get("payment-required")
    .ok_or("missing payment-required header")?
    .to_str()?;

// 2) Decode and parse the challenge
let payment_required: X402PaymentRequiredV2 =
    serde_json::from_slice(&STANDARD.decode(header)?)?;

// 3) Select a payment option
let accepted = payment_required
    .accepts
    .iter()
    .find(|option| option.scheme == SCHEME_4MICA_CREDIT)
    .cloned()
    .ok_or("no 4mica-credit payment option")?;

// 4) Build the PAYMENT-SIGNATURE header
let signed = flow.sign_payment_v2(payment_required, accepted).await?;

// 5) Call the protected resource with the header
let paid = http
    .get(url)
    .header("PAYMENT-SIGNATURE", &signed.header)
    .send()
    .await?
    .error_for_status()?;
```

`sign_payment_v2` returns `X402Error::InvalidVersion` unless the challenge's `x402Version` is 2. It echoes the challenge's `resource` and `extensions` back in the signed envelope.

## The signed payment

Both methods return an `X402SignedPayment`:

| Field | Description |
| - | - |
| `header` | Base64 of the envelope, for the `X-PAYMENT` (v1) or `PAYMENT-SIGNATURE` (v2) request header. |
| `envelope` | The decoded envelope as JSON. A facilitator takes this as `paymentPayload`. |
| `x402_version` | `1` or `2`. |
| `payload` | The signed `PaymentRequest`, typed. |

## What a resource server does

The Rust SDK has no HTTP server middleware. To charge for a route, use `@4mica/x402` (TypeScript) or `4mica-x402` (Python); see [payment middleware](https://docs.4mica.io/seller/payment-middleware.md).

A resource server answers an unpaid request with `402` and its payment requirements. When the client retries with a payment header, the server sends the payment to a facilitator's `/verify` endpoint, then to `/settle`, and serves the response only when settlement succeeds.

If you write that server in Rust, `settle_payment` covers the `/settle` call. It POSTs `{ x402Version, paymentPayload, paymentRequirements }` to `{facilitator_url}/settle`, where `paymentPayload` is the envelope object, not the base64 header.

```rust theme={null}
use sdk_4mica::x402::{PaymentRequirements, X402Requirements};
use sdk_4mica::{Client, GuaranteeReceipt, X402Flow, X402SignedPayment};

async fn settle(
    client: &Client,
    flow: &X402Flow<Client>,
    requirements: PaymentRequirements,
    payment: X402SignedPayment,
) -> Result<(), Box<dyn std::error::Error>> {
    let settled = flow
        .settle_payment(
            payment,
            X402Requirements::V1(requirements),
            "https://testnet.payment.4mica.io/",
        )
        .await?;

    if settled.settlement["success"].as_bool() != Some(true) {
        // errorReason is a code such as invalid_4mica_credit_checkpoint_required.
        eprintln!(
            "settlement rejected: {} {}",
            settled.settlement["errorReason"], settled.settlement["errorMessage"],
        );
        return Ok(());
    }

    let receipt: GuaranteeReceipt =
        serde_json::from_value(settled.settlement["extra"]["receipt"].clone())?;
    let guarantee = client.payment.verify_guarantee(&receipt)?;
    println!("guaranteed: {guarantee:?}");
    Ok(())
}
```

Wrap v2 requirements as `X402Requirements::V2(accepted)`. The requirements must be the same x402 version as the payment, or the call returns `X402Error::InvalidVersion`. End a facilitator URL that has a path with a trailing slash, because `settle` is joined onto it as a relative URL.

`settled.settlement` is the facilitator's JSON body. When the facilitator relays core's receipt, it is under `extra.receipt`. Check it with `verify_guarantee` before you serve the response.

> [!NOTE]
>
> `settle_payment` only calls `/settle`. Verify a payment before you grant
> access. A rejection comes back as HTTP 200 with `success: false`, so read the
> body and do not rely on the absence of an error. A non-2xx status returns
> `X402Error::SettlementFailed` with the status and body.

## Next steps

> [card] [Payment middleware](https://docs.4mica.io/seller/payment-middleware.md)
>
> Charge for a route with `@4mica/x402` or `4mica-x402`.

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


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