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

# API Providers

> Let AI agents buy and top up your API autonomously. One server-side endpoint, settled on a delegated card via x402, no human in the loop.

Agents are a new buyer of your API, and they don't onboard the way humans do. They don't sit at a browser, fill out a Stripe Checkout, or remember to top up a credit balance. Today they either stall at your paywall or hardcode a human's API key.

Nevermined turns that failure mode into revenue with a small server-side integration. Agents holding a delegated card mint an [x402](/docs/development-guide/nevermined-x402) access token, send it to your endpoint, and you provision or top up access in response. You verify and settle through Nevermined's [x402 facilitator](/docs/products/x402-facilitator/overview); the buyer's card is charged through Stripe, Braintree, or the Visa Trusted Agent Protocol depending on how it was enrolled. All three settle x402 charges through the same `nvm:card-delegation` scheme — your endpoint code doesn't change.

## Featured provider

[**Exa**](https://exa.ai) is the live reference. Agents pay Exa \$7 via a Nevermined-delegated card and receive an Exa API key with \$7 of credits. When the key runs out, the agent tops up through the same endpoint. Same key, more credits, no human touched it.

* Exa integration mirror: [exa.ai/docs/integrations/nevermined.md](https://exa.ai/docs/integrations/nevermined.md)

## What you build, in five steps

<Steps>
  <Step title="Create a pay-as-you-go plan">
    On the [Nevermined App](https://nevermined.app/), choose **pay-as-you-go** pricing (one charge per purchase) and set your price (e.g. \$7). That's it: the App doesn't ask about credits on PAYG, and one call to your purchase endpoint = one card charge of your plan price. See [Manage Plans](/docs/products/nevermined-app/manage-plans).
  </Step>

  <Step title="Expose one endpoint">
    Accept a `payment-signature` header on a new route or an existing one. Existing customers keep their flow unchanged.
  </Step>

  <Step title="Verify with the facilitator">
    Call `payments.facilitator.verifyPermissions(...)`. Missing or invalid token returns `402 Payment Required` with the payment requirements body.
  </Step>

  <Step title="Run your business logic">
    Provision an API key, top up credits, unlock a resource, whatever your product is.
  </Step>

  <Step title="Settle">
    Call `payments.facilitator.settlePermissions(...)`. The card is charged and you get paid. (On credits-bundle plans, settle also burns credits from the buyer's balance; on PAYG, there's no credit movement.)
  </Step>
</Steps>

## Server-side handler

Your handler does three things: read the `payment-signature` header, verify the token with the Nevermined facilitator, and settle after running your business logic. Examples below for TypeScript, Python, and raw HTTP.

<Tabs>
  <Tab title="TypeScript">
    ```typescript theme={null}
    import { Payments, buildPaymentRequired } from '@nevermined-io/payments'

    const payments = Payments.getInstance({
      nvmApiKey: process.env.NVM_API_KEY!,
      environment: 'live',
    })

    const paymentRequired = buildPaymentRequired(process.env.NVM_PLAN_ID!, {
      endpoint: '/purchase-key',
      httpVerb: 'POST',
      scheme: 'nvm:card-delegation',
    })

    // Pre-encode for the `payment-required` response header (per x402 spec §4.3).
    const paymentRequiredHeader = Buffer.from(
      JSON.stringify(paymentRequired),
    ).toString('base64')

    const send402 = (res) =>
      res
        .status(402)
        .setHeader('payment-required', paymentRequiredHeader)
        .json(paymentRequired)

    app.post('/purchase-key', async (req, res) => {
      const token = req.header('payment-signature')
      if (!token) return send402(res)

      const verification = await payments.facilitator.verifyPermissions({
        paymentRequired,
        x402AccessToken: token,
      })
      if (!verification.isValid) return send402(res)

      const apiKey = await provisionOrTopUp(req)

      const settlement = await payments.facilitator.settlePermissions({
        paymentRequired,
        x402AccessToken: token,
      })

      // Settlement receipt in the `payment-response` header (per x402 spec §4.3).
      res
        .setHeader(
          'payment-response',
          Buffer.from(JSON.stringify(settlement)).toString('base64'),
        )
        .json({ apiKey })
    })
    ```
  </Tab>

  <Tab title="Python">
    ```python theme={null}
    import base64
    import os
    from fastapi import FastAPI, Request
    from fastapi.responses import JSONResponse
    from payments_py import Payments, PaymentOptions
    from payments_py.x402.helpers import build_payment_required

    app = FastAPI()

    payments = Payments.get_instance(
        PaymentOptions(nvm_api_key=os.environ['NVM_API_KEY'], environment='live')
    )

    payment_required = build_payment_required(
        plan_id=os.environ['NVM_PLAN_ID'],
        endpoint='/purchase-key',
        http_verb='POST',
        scheme='nvm:card-delegation',
    )

    # Pre-encode for the `payment-required` response header (per x402 spec §4.3).
    payment_required_header = base64.b64encode(
        payment_required.model_dump_json(by_alias=True).encode()
    ).decode()

    def send_402() -> JSONResponse:
        return JSONResponse(
            status_code=402,
            content=payment_required.model_dump(by_alias=True),
            headers={'payment-required': payment_required_header},
        )

    @app.post('/purchase-key')
    async def purchase_key(request: Request):
        token = request.headers.get('payment-signature')
        if not token:
            return send_402()

        verification = payments.facilitator.verify_permissions(
            payment_required=payment_required,
            x402_access_token=token,
        )
        if not verification.is_valid:
            return send_402()

        api_key = await provision_or_top_up(request)

        settlement = payments.facilitator.settle_permissions(
            payment_required=payment_required,
            x402_access_token=token,
        )

        # Settlement receipt in the `payment-response` header (per x402 spec §4.3).
        settlement_header = base64.b64encode(
            settlement.model_dump_json(by_alias=True).encode()
        ).decode()
        return JSONResponse(
            content={'apiKey': api_key},
            headers={'payment-response': settlement_header},
        )
    ```
  </Tab>

  <Tab title="HTTP (any language)">
    The facilitator API is plain HTTP, no SDK required. Pseudo-code below
    shows the verify/settle calls your handler needs to make.

    **Endpoints** (no `Authorization` header, auth is in the x402 access token):

    ```
    POST https://api.live.nevermined.app/api/v1/x402/verify
    POST https://api.live.nevermined.app/api/v1/x402/settle
    ```

    Use `https://api.sandbox.nevermined.app/api/v1/...` for sandbox.

    **Verify request body:**

    ```json theme={null}
    {
      "paymentRequired": {
        "x402Version": 2,
        "resource": { "url": "/purchase-key", "mimeType": "application/json" },
        "accepts": [{
          "scheme": "nvm:card-delegation",
          "network": "stripe",
          "planId": "<your-plan-id>",
          "extra": { "version": "1", "httpVerb": "POST" }
        }],
        "extensions": {}
      },
      "x402AccessToken": "<token from the payment-signature header>"
    }
    ```

    Response: `{ "isValid": true, ... }` or `{ "isValid": false, "invalidReason": "..." }`.

    **Settle** uses the same body shape posted to `/x402/settle`. Response
    contains `creditsRedeemed`, `remainingBalance`, `transaction`, and
    (when auto top-up fired) `orderTx`.

    **Your response headers** (per x402 spec §4.3):

    * On 402: set `payment-required: <base64(PaymentRequired)>` so buyer-side
      clients can discover requirements
    * On 200: set `payment-response: <base64(settlement-receipt)>` so buyers
      have a structured settlement receipt

    **Pseudo-handler** (curl-style):

    ```bash theme={null}
    # 0. Pre-build the PaymentRequired JSON for your endpoint (see body shape above)
    PAYMENT_REQUIRED='{"x402Version":2,"resource":{"url":"/purchase-key","mimeType":"application/json"},"accepts":[{"scheme":"nvm:card-delegation","network":"stripe","planId":"<your-plan-id>","extra":{"version":"1","httpVerb":"POST"}}],"extensions":{}}'

    # 1. On request: read the payment-signature header
    TOKEN="$(http_header payment-signature)"

    # 2. Verify
    curl -s -X POST https://api.live.nevermined.app/api/v1/x402/verify \
      -H 'Content-Type: application/json' \
      -d "$(jq -n --arg pr "$PAYMENT_REQUIRED" --arg t "$TOKEN" '{
            paymentRequired: ($pr | fromjson),
            x402AccessToken: $t
          }')"
    # → on isValid=false, return 402 with payment-required header set

    # 3. Run business logic (provision/top-up the API key)

    # 4. Settle
    curl -s -X POST https://api.live.nevermined.app/api/v1/x402/settle \
      -H 'Content-Type: application/json' \
      -d "$(jq -n --arg pr "$PAYMENT_REQUIRED" --arg t "$TOKEN" '{
            paymentRequired: ($pr | fromjson),
            x402AccessToken: $t
          }')"

    # 5. Return 200 with the credential
    ```

    See the [Verify](/docs/api-reference/x402/verify-permission) and
    [Settle](/docs/api-reference/x402/settle-permission) API references for
    full request/response schemas, and the
    [card-delegation spec](/docs/specs/x402-card-delegation) §3.2 for the
    PaymentRequired JSON shape.
  </Tab>
</Tabs>

<Note>
  The handlers above set the `payment-required` (on 402) and `payment-response`
  (on 200) response headers per the
  [card-delegation spec](/docs/specs/x402-card-delegation) §4.3. The optional
  middleware below handles this for you automatically.
</Note>

### Optional: middleware (recommended)

If you're on Express or FastAPI, the SDK ships a payment middleware that handles the verify/settle dance and the spec-correct response headers for you. One config line gates your endpoint, your handler stays focused on business logic.

<Tip>
  The route config also accepts an optional `credits` field (default `1`).
  It's inert on PAYG plans and is the per-request burn amount on credits-bundle
  plans. Omitted in the snippets below for the PAYG happy path.
</Tip>

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

    const app = express()
    app.use(express.json())

    const payments = Payments.getInstance({
      nvmApiKey: process.env.NVM_API_KEY!,
      environment: 'live',
    })

    app.use(
      paymentMiddleware(payments, {
        'POST /purchase-key': {
          planId: process.env.NVM_PLAN_ID!,
          scheme: 'nvm:card-delegation',
        },
      }),
    )

    app.post('/purchase-key', async (req, res) => {
      const apiKey = await provisionOrTopUp(req)
      res.json({ apiKey })
    })
    ```
  </Tab>

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

    app = FastAPI()

    payments = Payments.get_instance(
        PaymentOptions(nvm_api_key=os.environ['NVM_API_KEY'], environment='live')
    )

    app.add_middleware(
        PaymentMiddleware,
        payments=payments,
        routes={
            'POST /purchase-key': {
                'plan_id': os.environ['NVM_PLAN_ID'],
                'scheme': 'nvm:card-delegation',
            },
        },
    )

    @app.post('/purchase-key')
    async def purchase_key(request: Request):
        api_key = await provision_or_top_up(request)
        return {'apiKey': api_key}
    ```
  </Tab>
</Tabs>

The middleware reads the `payment-signature` header, calls `verifyPermissions`, runs your handler, then calls `settlePermissions` and attaches the `payment-response` header before sending the response. See the [Express](/docs/integrate/add-to-your-agent/express) and [FastAPI](/docs/integrate/add-to-your-agent/fastapi) integration pages for middleware options (dynamic credits, hooks, custom error handlers).

### Two things to remember

<Warning>
  **Idempotency.** Agents retry. Cache `token → result` so a replayed token
  returns the same response without re-running your business logic or
  re-charging the card.
</Warning>

<Note>
  **402 on your regular endpoints.** When the agent's credits run dry, return
  `402` with a top-up hint on the resource endpoints (not just the purchase
  endpoint). The agent loops back, mints a fresh token, and pays again on the
  same purchase route.
</Note>

## Vend-the-key vs full metering

Two patterns are supported. Pick whichever matches how you already meter usage.

<CardGroup cols={2}>
  <Card title="Vend-the-key" icon="key">
    A Nevermined purchase returns a credential (e.g. an API key with \$X of
    credits). You meter ongoing usage internally with your existing
    infrastructure. Exa works this way. Best when you already have per-key
    billing.
  </Card>

  <Card title="Full metering" icon="gauge">
    Nevermined settles each underlying API call. Best when you don't have
    internal billing infra or prefer per-request settlement. Use the
    [validate-requests](/docs/integrate/patterns/validate-requests) and
    [charge-credits](/docs/integrate/patterns/charge-credits) patterns directly
    on your resource endpoints.
  </Card>
</CardGroup>

## Make it agent-discoverable

Agents don't read your HTML. They read your `llms.txt` and the `.md` mirrors next to your docs pages. Whichever path you took above, you still need these published on your own domain so crawlers find them under your brand.

<Tabs>
  <Tab title="Organization path">
    A Premium org auto-generates both files for you, served live from the Nevermined facilitator:

    ```
    GET https://api.live.nevermined.app/api/v1/organizations/{orgId}/llms.txt
    GET https://api.live.nevermined.app/api/v1/organizations/{orgId}/agentic-instructions.md
    ```

    Swap `api.live` for `api.sandbox` for the sandbox environment. Copy the rendered output to your own domain at whatever path your `llms.txt` references — `your-api.com/integrations/nevermined.md` is the common convention (Exa uses `/docs/integrations/nevermined.md` under their docs subpath). The org endpoint gives you the canonical content; you pick the publication URL and the filename agents discover, as long as the `llms.txt` entry on your side matches. Updates are picked up on next render (5-minute cache).
  </Tab>

  <Tab title="DIY path">
    Publish two files on your own domain:

    1. **A line in your `llms.txt`** (under an `## Integrations` heading or similar):

       ```
       - [Nevermined](/integrations/nevermined.md): Accept autonomous agent payments via x402 card delegation. Plan ID, endpoint, and SDK usage in the link.
       ```

    2. **A `.md` mirror** describing your plan ID, endpoint, and response shape. Common locations: `your-domain.com/integrations/nevermined.md` or `your-domain.com/docs/integrations/nevermined.md` (Exa uses the latter). Match whatever the `llms.txt` entry above points to.

           <Card title="Copy the mirror template" icon="file-lines" href="https://nevermined.ai/integrations/api-provider-template.md">
             Plain-text markdown skeleton with placeholders. Drop it wherever your docs live and fill in your plan ID, endpoint, and response shape.
           </Card>

       Live example: [Exa's `/docs/integrations/nevermined.md`](https://exa.ai/docs/integrations/nevermined.md).
  </Tab>
</Tabs>

Updating your human-facing HTML docs is optional and less agent-native.

## Agent-side call (for context)

What the agent runs to mint a token and call your endpoint:

<Tabs>
  <Tab title="TypeScript">
    ```typescript theme={null}
    // Create a card delegation first (provider + currency required), then
    // request the token by its delegationId.
    const delegation = await payments.delegation.createDelegation({
      provider: 'stripe',
      providerPaymentMethodId: 'pm_...',
      spendingLimitCents: 700,
      durationSecs: 3600,
      currency: 'usd',
    })
    const { accessToken } = await payments.x402.getX402AccessToken(
      YOUR_PLAN_ID,
      undefined,
      {
        scheme: 'nvm:card-delegation',
        delegationConfig: { delegationId: delegation.delegationId },
      },
    )

    const res = await fetch('https://your-api.com/purchase-key', {
      method: 'POST',
      headers: { 'payment-signature': accessToken },
    })
    ```
  </Tab>

  <Tab title="Python">
    ```python theme={null}
    from payments_py.x402 import (
        CreateDelegationPayload,
        DelegationConfig,
        X402TokenOptions,
    )

    # Create a card delegation first (provider + currency required), then
    # request the token by its delegation_id.
    delegation = payments.delegation.create_delegation(
        CreateDelegationPayload(
            provider='stripe',
            provider_payment_method_id='pm_...',
            spending_limit_cents=700,
            duration_secs=3600,
            currency='usd',
        )
    )
    token_res = payments.x402.get_x402_access_token(
        YOUR_PLAN_ID,
        None,
        token_options=X402TokenOptions(
            scheme='nvm:card-delegation',
            delegation_config=DelegationConfig(
                delegation_id=delegation.delegation_id
            ),
        ),
    )
    access_token = token_res['accessToken']

    res = requests.post(
        'https://your-api.com/purchase-key',
        headers={'payment-signature': access_token},
    )
    ```
  </Tab>
</Tabs>

## FAQ

<AccordionGroup>
  <Accordion title="When do I get paid out?">
    Settled funds are paid out via your connected payout provider on the
    provider's standard schedule: Stripe Connect for Stripe and Visa Trusted
    Agent Protocol delegations (Visa settlement runs through Stripe Connect);
    your Braintree OAuth merchant account for Braintree delegations.
  </Accordion>

  <Accordion title="Do my existing customers see any change?">
    No. Your existing API and billing surface stay as-is. Agent-payable signup
    is a parallel path you opt into with a new endpoint.
  </Accordion>

  <Accordion title="Can I keep my current pricing model?">
    Yes. Per-call, top-ups, and credit bundles map cleanly to Nevermined plans.
    For subscriptions, talk to us, recurring billing is supported case-by-case.
  </Accordion>

  <Accordion title="What card rails are supported?">
    Three rails today, all consumed through the same `nvm:card-delegation`
    x402 scheme:

    * **[Stripe](/docs/products/payments/overview)** — direct card enrollment
      and Stripe PaymentIntents settlement
    * **[Braintree](/docs/products/payments/braintree-onboarding)** — Drop-in
      enrollment and `transaction.sale` settlement against OAuth-connected
      seller merchants
    * **Visa Trusted Agent Protocol** — Visa Agentic Token enrollment via VGS
      Credential Management Platform, per-delegation WebAuthn/passkey device
      binding, settlement through Stripe Connect

    The x402 token your endpoint verifies is the same regardless of rail;
    Nevermined handles the rail-specific details. See the
    [card-delegation spec](/docs/specs/x402-card-delegation) for the
    underlying flow.
  </Accordion>

  <Accordion title="Is there a sandbox?">
    Yes, on the Stripe and Braintree rails. Integrate, run end-to-end test
    transactions, and validate your handler before flipping to live. The Visa
    Trusted Agent Protocol uses VGS sandbox with VTS-registered test PANs;
    Visa delegations require a real device that can run a WebAuthn ceremony
    (or fall back to the email OTP that VTS sends).
  </Accordion>

  <Accordion title="What languages and frameworks are supported?">
    TypeScript and Python SDKs ship today, with framework helpers for
    [Express.js](/docs/integrate/add-to-your-agent/express) and
    [FastAPI](/docs/integrate/add-to-your-agent/fastapi). The facilitator API
    is plain HTTP, so any language can call verify/settle directly. See the
    [Generic HTTP guide](/docs/integrate/add-to-your-agent/generic-http).
  </Accordion>

  <Accordion title="Do I need a Stripe account?">
    A Stripe Connect account is required for Stripe and Visa Trusted Agent
    Protocol delegations (Visa settlement runs through Stripe Connect). For
    Braintree delegations, you connect a Braintree OAuth merchant account
    instead (see
    [Braintree onboarding](/docs/products/payments/braintree-onboarding)).
    Nevermined handles card acquisition and PCI scope on the buyer side; you
    just bring your payout destination.
  </Accordion>

  <Accordion title="How are chargebacks and refunds handled?">
    On Stripe destination charges, Nevermined is the merchant of record:
    Stripe routes disputes and refunds through Nevermined, and we surface the
    chargeback or charge reference so you can match it to specific agent
    transactions.
  </Accordion>

  <Accordion title="Multi-currency?">
    Stripe Connect handles currency conversion to your destination account,
    so non-USD payouts work for Stripe and Visa delegations. Braintree
    requires the seller to have a child merchant account per accepted
    currency. The Visa Trusted Agent Protocol currently supports
    predominantly US-based issuers, with the eligibility list expanding
    through the pilot.
  </Accordion>
</AccordionGroup>

## Want a shortcut? Become a Nevermined Organization

A Premium Organization bundles the agent-discovery work above and adds tooling on top: an embeddable PCI-compliant card-capture widget for your domain, auto-generated `llms.txt` and `agentic-instructions.md` rendered live from your plans, a customer list that auto-populates on agent purchases, webhooks, analytics, and multi-seat access. The DIY recipe above stays fully supported and is what powers Exa today; pick whichever fits your operational model. See [Platform Partners (Organizations)](/docs/integrations/organizations) for the org-specific guide.

## Pricing

Three Nevermined Organization plans, picked at sign-up:

| Plan                                       | Cost              | What's included                                                                                                                                          |
| ------------------------------------------ | ----------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Starter**                                | Free              | Publish plans and agents on a single-seat account. No org features (no widgets, no auto-generated agent docs, no customer list).                         |
| **Premium Organization** ⭐ **Recommended** | **\$250 / month** | All Premium features: widget card capture, auto-generated `llms.txt` / `agentic-instructions.md`, customer list, webhooks, analytics, 5 invitable seats. |
| **Enterprise Organization**                | **\$500 / month** | Premium + unlimited agents and plans.                                                                                                                    |

Settlement fees on agent payments are documented in the [Payments overview](/docs/products/payments/overview).

<Note>
  **Pilot / whitelist / fee waiver.** Talk to us before you ship if you're a launch
  partner, an early-stage API provider, or running a closed pilot. We can waive
  or reduce Organization plan fees and settlement fees in select circumstances.
  Email [hello@nevermined.io](mailto:hello@nevermined.io) or
  [contact us](https://nevermined.ai/contact-us/).
</Note>

## Related

* [x402 Card Delegation Spec](/docs/specs/x402-card-delegation) - full
  verify/settle protocol with JWT claims, error codes, and the four-phase flow
* [x402 Facilitator: How it works](/docs/products/x402-facilitator/how-it-works)
  * end-to-end walk-through of the facilitator API
* [Validate Requests](/docs/integrate/patterns/validate-requests) and
  [Charge Credits](/docs/integrate/patterns/charge-credits) - copy-paste
  patterns for the verify and settle steps
* [Manage Plans](/docs/products/nevermined-app/manage-plans) - set up a
  pay-as-you-go plan
* [Payments overview](/docs/products/payments/overview) - how buyers
  enroll cards and create delegations
* [API provider mirror template](https://nevermined.ai/integrations/api-provider-template.md)
  * copy-paste skeleton for the `.md` you publish on your own domain
* [Platform Partners (Organizations)](/docs/integrations/organizations) - the
  recommended org path with widgets, customer list, and webhooks
