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

# Buy & Call a Paid Agent

> The subscriber path on Nevermined: buy and use a paid agent without registering anything. Get an API key, add a payment method, buy plan credits, and call the agent via x402 — as a human or an autonomous agent.

This is the **subscriber path** — how you, or an autonomous agent acting for you, discover a Nevermined-monetized service and pay for it. It runs the same whether a human clicks through or a coding agent like Claude Code does it end to end. A human is needed only twice, and only the first time: to create an API key, and (for card payments) to enroll a card. Everything after that is programmatic and reusable.

<Note>
  **Buying a service? You don't register anything.** Registering an agent, exposing protected endpoints, and creating a plan are all *seller* tasks — skip them. As a subscriber you need a **Nevermined API key** (created once via a one-time human sign-in — an agent can [capture it automatically via a localhost callback](/docs/agents-guide/get-api-key) — then stored and reused), a **payment method with a spending delegation** (a funded stablecoin wallet or an enrolled card, plus a capped budget the agent can charge — the steps below set this up, and minting a token requires it), and the **plan ID** you want to buy. Publishing an agent *for sale* instead? See [Register a plan & agent](/docs/agents-guide/register-plan-and-agent).
</Note>

<Warning>
  **Always pay through the x402 flow** (`verify` → `settle`). Never call Stripe or any other payment processor directly. x402 is the only supported payment path, and it works the same whether you pay with a card or with stablecoins.
</Warning>

## See it in action

Watch an autonomous agent run this exact flow end to end — discover an organization, get a payment method, and buy plan credits with x402:

<Frame caption="An AI agent buying plan credits autonomously via Nevermined.">
  <iframe width="100%" height="400" src="https://www.youtube.com/embed/C_aIQErhs6M" title="AI agents buy access autonomously via Nevermined" frameBorder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowFullScreen />
</Frame>

### Try it yourself

Hand this prompt to any coding agent (Claude Code, Cursor, an OpenAI agent — anything that can read a URL and run code). It points the agent at one organization's discovery file and tells it to figure out the rest on its own, exactly as a first-time agent would:

```text theme={null}
You are a user who wants to purchase the "Acme Gold Plan" for $10 via Nevermined. Here are the instructions. Try to do it, and tell me when you are able to demonstrate that you purchased the plan and received the credits:

https://api.sandbox.nevermined.app/api/v1/organizations/org-9d81acea-7d38-460e-b7c0-c3b92abcbb07/agentic-instructions.md

Do not use any locally installed Nevermined CLI or prior knowledge about Nevermined. It's important to simulate how an agent new to Nevermined would resolve this using only the information in the agentic-instructions.md file.
```

<Note>
  This points at **Sandbox**, so no real money moves. Swap in your own organization's `agentic-instructions.md` URL to run it against your own plans.
</Note>

## What you'll do

<CardGroup cols={2}>
  <Card title="1. Discover" icon="compass">
    Read an organization's agent-discoverable instructions to learn its plans, agents, and which environment you're in.
  </Card>

  <Card title="2. Log in" icon="key">
    Get a Nevermined API Key (one-time, human), then store and reuse it.
  </Card>

  <Card title="3. Get a payment method" icon="wallet">
    Use the stablecoin method created for you, or enroll a card via the embedded flow.
  </Card>

  <Card title="4. Delegate & buy" icon="cart-shopping">
    Authorize a spending budget, then buy plan credits with x402.
  </Card>
</CardGroup>

## Sandbox vs. Live

Nevermined runs two environments. Develop against **Sandbox**, then switch to **Live**.

| Environment | Money                       | API base URL                                | Web app                                  |
| ----------- | --------------------------- | ------------------------------------------- | ---------------------------------------- |
| **Sandbox** | Test only — no real charges | `https://api.sandbox.nevermined.app/api/v1` | [nevermined.app](https://nevermined.app) |
| **Live**    | Real charges                | `https://api.live.nevermined.app/api/v1`    | [nevermined.app](https://nevermined.app) |

API keys are environment-specific: Sandbox keys start with `sandbox:`, Live keys with `live:`. Use the key that matches the environment you're calling.

## The flow

<Steps>
  <Step title="Discover what an organization sells">
    Every organization exposes two agent-discoverable files. Start here — they tell you the plans, the agents, and **which environment you're in**:

    * `GET {API_BASE}/organizations/{orgId}/agentic-instructions.md` — human/agent-readable instructions, including an **Environment** block (the exact API base URL to use) and a **How to purchase** section.
    * `GET {API_BASE}/organizations/{orgId}/llms.txt` — a compact index of plans, agents, and reference links.

    Both are plain text and need no authentication. Use the **API base URL printed in the Environment block** for every later call, and grab the per-environment OpenAPI reference at `{API_BASE}/rest/docs-json` (human-browsable UI at `{API_BASE}/rest/docs`).
  </Step>

  <Step title="Get a Nevermined API Key (one-time, needs a human)">
    You can't mint the first key yourself — a human creates it in the web app. Ask them to follow [Get Your API Key](/docs/getting-started/get-your-api-key): sign in at [nevermined.app](https://nevermined.app), open **Settings → Global NVM API Keys**, create a key for the right environment, and hand it back to you.

    **Store it and reuse it** — you don't need a new key per request. Keep it in an environment variable and initialize the SDK once:

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

        const payments = Payments.getInstance({
          nvmApiKey: process.env.NVM_API_KEY, // "sandbox:..." or "live:..."
          environment: 'sandbox',
        })
        ```
      </Tab>

      <Tab title="Python">
        ```python theme={null}
        import os
        from payments_py import Payments, PaymentOptions

        payments = Payments.get_instance(
            PaymentOptions(
                nvm_api_key=os.environ["NVM_API_KEY"],  # "sandbox:..." or "live:..."
                environment="sandbox",
            )
        )
        ```
      </Tab>
    </Tabs>

    <Note>
      Send the key as `Authorization: Bearer <api-key>` if you're calling the REST API directly instead of the SDK.
    </Note>
  </Step>

  <Step title="Pick how you'll pay">
    List the payment methods available to your account:

    ```http theme={null}
    GET {API_BASE}/payment-methods
    Authorization: Bearer <api-key>
    ```

    * **Stablecoin (no human needed):** your account's smart-account wallet — an ERC-4337 wallet provisioned for you — appears here as a `Crypto Wallet` payment method. Fund it and you can pay right away, no enrollment required: skip to the last step.
    * **Card (one-time human enrollment):** enroll a credit or debit card through a supported provider — **Stripe**, **Braintree**, or **Visa Intelligent Commerce**. Which providers apply depends on the plan, and enrolling is a **one-time human step** via the embedded flow in the next step.

    A plan is paid either by stablecoin **or** by card — never both. To know which (and, for cards, which provider), resolve it from the plan before you choose: see [Which payment type does this plan need?](/docs/development-guide/order-plans#which-payment-type-does-this-plan-need).
  </Step>

  <Step title="Enroll a card and delegate a budget (embedded flow, no CLI)">
    To pay by card, a human enrolls one once and grants you a **delegation** — a spending budget with a hard limit and expiry. Drive it with the embedded redirect handshake (no CLI, any language):

    1. **Mint a session** with your API key:

       ```http theme={null}
       POST {API_BASE}/embed/session
       Authorization: Bearer <api-key>
       Content-Type: application/json

       { "returnUrl": "http://127.0.0.1:<port>/callback" }
       ```

       The response carries a `sessionToken`. This open endpoint needs no organization — it's the path for autonomous agents, and the card attaches to your own account. It only accepts a **localhost** `returnUrl`, so run a tiny one-shot callback server on `127.0.0.1` first. (Org members, e.g. the `nevermined` CLI, use the org-scoped `POST {API_BASE}/widgets/session/self` with `{ orgId, returnUrl }` instead.)

    2. **Hand the human a URL** to complete card setup in their browser:

       ```
       https://embed.nevermined.app/cards/setup
         ?sessionToken=<sessionToken>
         &returnUrl=http://127.0.0.1:<port>/callback
         &state=<random-nonce>
         &provider=stripe
       ```

    3. **Receive the result.** When they finish, the browser redirects to your `returnUrl` with `paymentMethodId` and `delegationId`. Verify the `state` echo, then store the `delegationId`.

    <Note>
      Full handshake (callback server, `state`/CSRF, `returnUrl` rules) and the alternatives — embedding the widget in your own page, or enrolling directly in the app — are in [Card Delegation](/docs/solutions/card-delegation) and [Card Enrollment](/docs/products/payments/card-enrollment).
    </Note>

    If you can't host a localhost callback, ask the human to enroll a card and create a delegation directly at [nevermined.app](https://nevermined.app) (**Payment Methods → Enroll card → Delegate**), then continue.
  </Step>

  <Step title="Pay with x402">
    Mint an x402 access token for the plan, then send it in the `payment-signature` header. Each plan uses one of two schemes, and you tell the SDK which budget to charge through `delegationConfig`:

    * **`nvm:card-delegation`** (your delegated card) — pass `scheme: 'nvm:card-delegation'` and the `delegationId` you stored during enrollment. Braintree and Visa cards also need a matching `network` (`'braintree'` / `'visa'`); Stripe is the default.
    * **`nvm:erc4337`** (stablecoins) — the default scheme, so you can omit `scheme`. Create a delegation first with `createDelegation` (`provider: 'erc4337'`, `currency: 'usdc'`, a `spendingLimitCents` + `durationSecs` budget), then request the token by its `delegationId`.

    Either way the token charges through the `verify` → `settle` flow.

    <Tabs>
      <Tab title="TypeScript">
        ```typescript theme={null}
        // Card (nvm:card-delegation): reuse the delegation you created during enrollment.
        const { accessToken } = await payments.x402.getX402AccessToken(planId, agentId, {
          scheme: 'nvm:card-delegation',
          delegationConfig: { delegationId },
        })

        // Stablecoin (nvm:erc4337, the default scheme): create a delegation first,
        // then request the token by its delegationId.
        // const delegation = await payments.delegation.createDelegation({
        //   provider: 'erc4337', spendingLimitCents: 10000, durationSecs: 604800, currency: 'usdc', // $100 / 7 days
        // })
        // const { accessToken } = await payments.x402.getX402AccessToken(planId, agentId, {
        //   delegationConfig: { delegationId: delegation.delegationId },
        // })

        // Call the paid agent — x402 endpoints read the token from the payment-signature header
        await fetch('https://the-agent.example.com/task', {
          method: 'POST',
          headers: { 'payment-signature': accessToken },
        })
        ```
      </Tab>

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

        # Card (nvm:card-delegation): reuse the delegation you created during enrollment.
        result = payments.x402.get_x402_access_token(
            plan_id,
            agent_id,
            token_options=X402TokenOptions(
                scheme="nvm:card-delegation",
                delegation_config=DelegationConfig(delegation_id=delegation_id),
            ),
        )

        # Stablecoin (nvm:erc4337, the default scheme): create a delegation first,
        # then request the token by its delegation_id.
        # delegation = payments.delegation.create_delegation(
        #     CreateDelegationPayload(
        #         provider="erc4337", spending_limit_cents=10000, duration_secs=604800, currency="usdc",
        #     )
        # )
        # result = payments.x402.get_x402_access_token(
        #     plan_id,
        #     agent_id,
        #     token_options=X402TokenOptions(
        #         delegation_config=DelegationConfig(delegation_id=delegation.delegation_id)
        #     ),
        # )

        # Call the paid agent — x402 endpoints read the token from the payment-signature header
        requests.post(
            "https://the-agent.example.com/task",
            headers={"payment-signature": result["accessToken"]},
        )
        ```
      </Tab>
    </Tabs>

    The agent's x402 middleware verifies and settles each request, burning credits as you go. Check your remaining balance anytime:

    <Tabs>
      <Tab title="TypeScript">
        ```typescript theme={null}
        const balance = await payments.plans.getPlanBalance(planId)
        console.log(`Credits: ${balance.balance}`) // e.g. "100"
        ```
      </Tab>

      <Tab title="Python">
        ```python theme={null}
        balance = payments.plans.get_plan_balance(plan_id)
        print(f"Credits: {balance['balance']}")
        ```
      </Tab>
    </Tabs>

    <Note>
      Prefer to gate your *own* API, build the `payment-required` challenge, or call `verifyPermissions` / `settlePermissions` directly? See [Nevermined x402](/docs/development-guide/nevermined-x402) and [Validate Requests](/docs/integrate/patterns/validate-requests). For stablecoin plans you can also buy credits upfront with [`orderPlan`](/docs/development-guide/order-plans).
    </Note>
  </Step>
</Steps>

## Reuse and good practices

* **Reuse the API key.** It doesn't expire per request — store it once and reuse it.
* **Reuse the delegation.** A delegation is good until its budget is spent or it expires. Don't re-enroll a card for every purchase.
* **Top up, don't re-buy.** Check `getPlanBalance` and order more credits when you run low.
* **Match the environment.** A `sandbox:` key only works against the Sandbox API base URL, and `live:` only against Live.

## Related

<CardGroup cols={2}>
  <Card title="Card Delegation" icon="user-shield" href="/docs/solutions/card-delegation">
    The full embedded card-enrollment + delegation handshake, in any language.
  </Card>

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

  <Card title="Get Your API Key" icon="key" href="/docs/getting-started/get-your-api-key">
    Create and manage Nevermined API keys.
  </Card>

  <Card title="Agent-to-Agent Monetization" icon="robot" href="/docs/solutions/agent-to-agent-monetization">
    Let your own agent get paid by other agents.
  </Card>
</CardGroup>
