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

# Payment Middleware

> Protect your routes with 4Mica x402 payment middleware.

Payment middleware turns an ordinary HTTP route into a paid resource. It is the server-side bridge between your application and 4Mica's x402 credit flow.

Use it for APIs, model endpoints, agent workflows, paid datasets, or any route where the server should verify payment before serving the response.

## What the middleware does

For a protected route, the middleware handles the payment gate before your application performs paid work.

<Steps>
  <Step title="Return payment requirements">
    When a request is unpaid, the route returns HTTP 402 with the price, asset, network, and `payTo` address.
  </Step>

  <Step title="Accept the paid retry">
    The buyer signs a guarantee with a unique request ID and retries with an x402 payment header.
  </Step>

  <Step title="Verify and settle">
    The middleware verifies the signed guarantee and settles through the facilitator.
  </Step>

  <Step title="Run your handler">
    Your paid handler runs only after payment validation succeeds.
  </Step>
</Steps>

This keeps your paid product API-native. Buyers and agents can discover the price from the HTTP response and pay without opening an account on your service.

## Route configuration

```ts theme={null}
import { paymentMiddlewareFromConfig } from "@4mica/x402/server/express";

app.use(
  paymentMiddlewareFromConfig({
    "POST /agent/summarize": {
      accepts: {
        scheme: "4mica-credit",
        price: "$0.02",
        network: "eip155:84532",
        payTo: "0xYourSellerAddress",
      },
    },
  })
);
```

After changing route pricing or `payTo`, confirm the advertised values in [4mica dashboard](https://app.4mica.io).

## Fields you should make explicit

| Field             | Your decision                                                                                                       |
| ----------------- | ------------------------------------------------------------------------------------------------------------------- |
| `scheme`          | Use `4mica-credit` for collateral-backed off-chain guarantees.                                                      |
| `price`           | Set the amount for this unit of work. Start small in sandbox.                                                       |
| `network`         | Use Base Sepolia (`eip155:84532`) for testing and Base (`eip155:8453`) for production when supported by your route. |
| `payTo`           | Use your wallet address that should receive payment.                                                                |
| Guarantee version | Use V1 for immediately payable work or V2 for validation-gated work.                                                |

## Pricing dynamic work

If the final cost depends on tokens, compute, data, or task complexity, use your application logic to quote before work begins. The buyer should see the price before paying.

| Pattern               | Example                                                                            |
| --------------------- | ---------------------------------------------------------------------------------- |
| Fixed price per route | `$0.02` per summary.                                                               |
| Tiered routes         | `/basic`, `/pro`, and `/enterprise`.                                               |
| Quoted task           | Your agent estimates cost and returns payment requirements for the accepted quote. |
| Metered work          | You require prepayment or a credit cap before streaming or long-running execution. |

Keep the payment requirement honest. If the buyer paid for one request, do not silently perform more work that requires a larger charge.

<Tip>
  For long-running routes, split the work into paid stages or require a higher cap before execution. That keeps cost growth visible to the buyer.
</Tip>

## Delivery and logging

Log enough information to connect payment, request, and result.

| Log field                           | Why it matters                                                   |
| ----------------------------------- | ---------------------------------------------------------------- |
| Route and method                    | Shows which protected resource was called.                       |
| Request ID and guarantee ID         | Connects the application request to the payment flow.            |
| Payer address and `payTo` address   | Shows who paid and which seller address received the obligation. |
| Quoted price                        | Shows what the buyer authorized.                                 |
| Payment header version              | Helps debug client compatibility.                                |
| Verification and settle result      | Shows whether payment validation succeeded.                      |
| Response status and delivery marker | Connects payment to the response you delivered.                  |

These records are how you answer "which request was paid for?" and "what response did the agent deliver?"

Keep these logs close to dashboard settlement records so support can trace buyer claims quickly.

## Failure behavior

If verification or settlement fails, do not run the paid handler. Return a clear payment failure response and include a stable error code that your support team can map back to logs.

If a buyer retries repeatedly with invalid payment headers, rate limit the payer, guarantee, IP, or agent identity depending on what your application can observe.

<Warning>
  Do not treat payment middleware failures as ordinary application errors. A failed verification means the paid handler should not run.
</Warning>
