> ## Documentation Index
> Fetch the complete documentation index at: https://neverminedag-sync-api-errors-9d14109.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Add Payments to Your Agent

> Have a coding agent retrofit your existing AI agent or API so callers must pay per request through an x402 paywall — middleware, plan registration, and a test.

This flow is the other side of the market: instead of paying, your agent **gets paid**. Point a coding agent (Claude Code, Cursor, an OpenAI agent) at your existing service and the Nevermined SDK, and it wires an x402 paywall in front of the endpoints you choose — so every call costs credits.

## Useful for

* **Monetizing** an existing Express, FastAPI, MCP, or A2A agent without building billing yourself.
* Charging **per request** (fixed or dynamic credits) with metering and settlement handled for you.
* Generating the **registration script + middleware + a test** in one pass, so you go from unpaid to paid in minutes.

## Try it yourself

Run this in your project with a coding agent that can read and edit your files:

```text theme={null}
My project is an Express (TypeScript, ESM) AI agent with an endpoint `POST /ask`. Add Nevermined payments so callers must pay 1 credit per request via the x402 protocol, using the @nevermined-io/payments SDK (pin ^1.8.0) and following the Nevermined `nevermined-payments` skill (https://github.com/nevermined-io/docs/tree/main/skills/nevermined-payments) — its Track B + references/express-integration.md and references/client-integration.md cover the details.

Project setup: package.json must have "type":"module" (required for the @nevermined-io/payments/express subpath import); local TS imports use .js extensions; run with `npx tsx <file>.ts`. Keep my existing POST /ask handler logic completely intact — add payments only as a front layer (the paymentMiddleware), never inside the handler.

Produce three files:
1. register.ts — publishes my agent and a "Starter" plan granting 100 credits for $10 in USDC on sandbox, then prints agentId and planId. Build configs with payments.plans.getERC20PriceConfig(10_000_000n, '0x036CbD53842c5426634e7929541eC2318f3dCF7e', '<your-builder-wallet>') (10 USDC = 10_000_000n, 6 decimals; all numeric helper args are BigInt — note the n) and payments.plans.getFixedCreditsConfig(100n, 1n), then payments.agents.registerAgentAndPlan(...). (The price helper splits payment into builder + platform-fee receivers, so the builder nets slightly under $10 — expected.)
2. server.ts — wire the middleware: app.use(paymentMiddleware(payments, { 'POST /ask': { planId: NVM_PLAN_ID, agentId: NVM_AGENT_ID, credits: 1 } })), reading NVM_API_KEY, NVM_PLAN_ID, NVM_AGENT_ID from env. Mount express.json() first; keep the existing app.post('/ask', askHandler) unchanged. The middleware auto-returns 402 + payment-required, verifies, runs the handler, then settles/burns and adds payment-response — no manual verify/settle.
3. test.ts — start the server, call POST /ask with no payment-signature (expect 402; decode the base64 payment-required header), then do the TWO-STEP token mint (the inline auto-create `delegationConfig` — passing `spendingLimitCents`/`durationSecs` without a `delegationId` — is deprecated since SDK 1.8.0: it emits a runtime deprecation warning, so use the explicit two-step): first `const { delegationId } = await payments.delegation.createDelegation({ provider: 'erc4337', spendingLimitCents: 10000, durationSecs: 604800, currency: 'usdc' })`, then `const { accessToken } = await payments.x402.getX402AccessToken(planId, agentId, { delegationConfig: { delegationId } })`, and retry POST /ask with header `payment-signature: <accessToken>` (expect 200; decode the base64 payment-response receipt — creditsRedeemed/remainingBalance). Run in the sandbox environment.

Use the modern payment-signature header and X402_HEADERS from @nevermined-io/payments/express; the middleware calls verifyPermissions/settlePermissions internally — do NOT use the deprecated isValidRequest or X-402.
```

<Note>
  Swap the framework line for your stack — guides exist for [Express](/docs/integrate/add-to-your-agent/express), [FastAPI](/docs/integrate/add-to-your-agent/fastapi), [Strands](/docs/integrate/add-to-your-agent/strands), and [generic HTTP](/docs/integrate/add-to-your-agent/generic-http).
</Note>

## How it works

<Steps>
  <Step title="Register an agent and a plan">
    Publish the service and price it. The SDK helpers build the on-chain price/credits config for you:

    <Tabs>
      <Tab title="TypeScript">
        ```typescript theme={null}
        const { agentId, planId } = await payments.agents.registerAgentAndPlan(
          { name: 'My Agent', description: 'AI service', tags: ['ai'], dateCreated: new Date() },
          { endpoints: [{ POST: 'https://your-api.com/ask' }] },
          { name: 'Starter Plan', description: '100 requests for $10', dateCreated: new Date() },
          payments.plans.getERC20PriceConfig(10_000_000n, USDC_ADDRESS, process.env.BUILDER_ADDRESS),
          payments.plans.getFixedCreditsConfig(100n, 1n),
        )
        ```
      </Tab>

      <Tab title="Python">
        ```python theme={null}
        result = payments.agents.register_agent_and_plan(
            agent_metadata={'name': 'My Agent', 'description': 'AI service', 'tags': ['ai']},
            agent_api={'endpoints': [{'POST': 'https://your-api.com/ask'}]},
            plan_metadata={'name': 'Starter Plan', 'description': '100 requests for $10'},
            price_config=payments.plans.get_erc20_price_config(10_000_000, USDC_ADDRESS, os.environ['BUILDER_ADDRESS']),
            credits_config=payments.plans.get_fixed_credits_config(100, 1),
        )
        ```
      </Tab>
    </Tabs>

    See [Register a plan & agent](/docs/agents-guide/register-plan-and-agent) for the full options (fiat pricing, time-based and pay-as-you-go plans).
  </Step>

  <Step title="Gate your routes with middleware">
    Add the payment middleware and list the routes to protect with their credit cost. Everything not listed stays public:

    <Tabs>
      <Tab title="Express (TypeScript)">
        ```typescript theme={null}
        import { paymentMiddleware } from '@nevermined-io/payments/express'

        app.use(paymentMiddleware(payments, {
          'POST /ask': { planId: process.env.NVM_PLAN_ID, credits: 1 },
        }))
        ```
      </Tab>

      <Tab title="FastAPI (Python)">
        ```python theme={null}
        from payments_py.x402.fastapi import PaymentMiddleware

        app.add_middleware(
            PaymentMiddleware,
            payments=payments,
            routes={"POST /ask": {"plan_id": os.environ["NVM_PLAN_ID"], "credits": 1}},
        )
        ```
      </Tab>
    </Tabs>

    The middleware returns `402` with a `payment-required` challenge when the token is missing, verifies it when present, runs your handler, then settles (burns credits) and returns the receipt in `payment-response`.
  </Step>

  <Step title="Test the paywall">
    Call without a token (expect `402`), then with a fresh token (expect `200`):

    ```bash theme={null}
    # 1) No token → 402
    curl -i -X POST http://localhost:3000/ask -d '{"q":"hi"}'

    # 2) With an x402 token → 200 (mint one as a buyer would — see "Buy access")
    curl -i -X POST http://localhost:3000/ask \
      -H "payment-signature: <accessToken>" -d '{"q":"hi"}'
    ```
  </Step>
</Steps>

## Related

<CardGroup cols={2}>
  <Card title="Register a plan & agent" icon="store" href="/docs/agents-guide/register-plan-and-agent">
    Publish and price the service you're protecting.
  </Card>

  <Card title="Nevermined x402" icon="bolt" href="/docs/development-guide/nevermined-x402">
    The protocol behind the paywall: schemes, headers, verify/settle.
  </Card>

  <Card title="Check revenue" icon="chart-line" href="/docs/agents-guide/check-revenue">
    Once you're charging, track what you earn.
  </Card>

  <Card title="Buy access" icon="cart-shopping" href="/docs/getting-started/ai-agent-purchase">
    See the buyer side that mints the token your paywall checks.
  </Card>
</CardGroup>
