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

# Quickstart

> Integrate Nevermined in minutes. Register an AI agent, create a payment plan, and accept payments using the no-code app or the TypeScript and Python SDKs.

This guide provides a quick path to integrating Nevermined, whether you're an AI Builder looking to monetize an AI agent or service, or a User wanting to access one. You can interact with Nevermined through our user-friendly Web App or programmatically via our SDKs.

## For AI Builders: Monetize Your Agent

### Using the Nevermined Web App (No Code)

The easiest way to get started is by using the [Nevermined App](https://nevermined.app/) to register your agent and create payment plans through a visual interface.

1. **Log In**: Access the app via Web3Auth (socials or wallet).
2. **Register Agent**: Navigate to the "Agents" tab to "Register New Agent". Fill in your agent's metadata (name, description) and register all API endpoints.
3. **Create Pricing Plan**: Define one or more pricing plans for your agent, specifying price, payment currency (fiat or crypto), and usage terms (per-request pricing).
4. **Done!**: Your agent is now discoverable and ready to accept payments.

### Using the SDKs (Programmatic)

For developers who need to automate and integrate directly, our SDKs are the perfect tool.

<Steps>
  <Step title="1. Get Your API Key">
    To interact with the Nevermined API, you need an API key. Follow the [Get Your API Key](/docs/getting-started/get-your-api-key) guide to create one, then store it as an environment variable:

    ```bash theme={null}
    export NVM_API_KEY="sandbox:your-api-key-here"
    ```
  </Step>

  <Step title="2. Install and Initialize the Payments Library">
    Install the PaymentsLibrary and initialize the `Payments` client with your API key.

    <Tabs>
      <Tab title="TypeScript">
        ```bash theme={null}
        npm install @nevermined-io/payments
        ```

        ```typescript theme={null}
        import { Payments } from '@nevermined-io/payments'

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

      <Tab title="Python">
        ```bash theme={null}
        pip install payments-py
        ```

        ```python theme={null}
        import os
        from payments_py import Payments, PaymentOptions

        payments = Payments.get_instance(
            PaymentOptions(
                nvm_api_key=os.environ.get('NVM_API_KEY'),
                environment='sandbox'  # or 'live'
            )
        )
        ```
      </Tab>
    </Tabs>
  </Step>

  <Step title="3. Register Your AI Agent">
    Define your agent's metadata, authentication config, and payment plan. Then register it with a single call. The endpoint allowlist and OpenAPI/agent-definition URL are optional — see the [registration guide](/docs/development-guide/registration) for the opt-in *Additional Security* pattern.

    <Tabs>
      <Tab title="TypeScript">
        ```typescript theme={null}
        // Define agent metadata
        const agentMetadata = {
          name: 'My AI Assistant',
          tags: ['ai', 'assistant'],
          dateCreated: new Date(),
        };

        // Define API authentication. agentDefinitionUrl and the endpoint
        // allowlist are optional ("Additional Security") — see the
        // registration guide for the opt-in pattern.
        const agentApi = {
          authType: 'bearer',
          token: process.env.AGENT_BEARER_TOKEN,
        };

        // Define plan metadata
        const planMetadata = {
          name: 'Basic Plan',
          description: '100 queries per month',
          dateCreated: new Date(),
        };

        // Configure pricing (e.g., 10 USDC)
        const priceConfig = payments.plans.getERC20PriceConfig(
          10_000_000n, // 10 USDC (6 decimals)
          '0xA0b86a33E6441c41F4F2B8Bf4F2B0f1B0F1C1C1C', // USDC address
          process.env.BUILDER_ADDRESS
        );

        // Configure credits (e.g., 100 queries)
        const creditsConfig = payments.plans.getFixedCreditsConfig(100n, 1n);

        // Register agent and plan together
        const { agentId, planId } = await payments.agents.registerAgentAndPlan(
          agentMetadata,
          agentApi,
          planMetadata,
          priceConfig,
          creditsConfig
        );

        console.log(`Agent registered: ${agentId}`);
        ```
      </Tab>

      <Tab title="Python">
        ```python theme={null}
        import os

        from payments_py.common.types import AgentAPIAttributes, AuthType
        from payments_py.plans import get_erc20_price_config, get_fixed_credits_config

        # Define agent metadata
        agent_metadata = {
            'name': 'My AI Assistant',
            'tags': ['ai', 'assistant'],
            'dateCreated': '2023-10-27T10:00:00Z',
        }

        # Define API authentication. agent_definition_url and the endpoint
        # allowlist are optional ("Additional Security") — see the
        # registration guide for the opt-in pattern.
        agent_api = AgentAPIAttributes(
            auth_type=AuthType.BEARER,
            token=os.environ['AGENT_BEARER_TOKEN'],
        )

        # Define plan metadata
        plan_metadata = {
            'name': 'Basic Plan',
            'description': '100 queries per month',
            'dateCreated': '2023-10-27T10:00:00Z',
        }

        # Configure pricing (e.g., 10 USDC)
        price_config = get_erc20_price_config(
            10_000_000,  # 10 USDC (6 decimals)
            '0xA0b86a33E6441c41F4F2B8Bf4F2B0f1B0F1C1C1C',  # USDC address
            os.environ.get('BUILDER_ADDRESS')
        )

        # Configure credits (e.g., 100 queries)
        credits_config = get_fixed_credits_config(100, 1)  # 100 credits, 1 credit per request

        # Register agent and plan together
        agent_info = payments.agents.register_agent_and_plan(
            agent_metadata,
            agent_api,
            plan_metadata,
            price_config,
            credits_config,
            'credits'  # Optional: access_limit ('credits' or 'time'). Auto-inferred if not specified
        )

        print(f"Agent registered: {agent_info['agentId']}")
        ```
      </Tab>
    </Tabs>
  </Step>

  <Step title="4. Accept Payments">
    In your agent's backend, add payment protection to your routes. The `paymentMiddleware` handles the full x402 flow automatically: it returns 402 with payment requirements when no token is present, verifies permissions, executes your handler, and settles (burns) credits.

    <Tabs>
      <Tab title="TypeScript (Express.js)">
        ```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: 'sandbox'
        })

        const PLAN_ID = process.env.NVM_PLAN_ID!

        // Add payment protection — 1 credit per request to /api/query
        app.use(paymentMiddleware(payments, {
          'POST /api/query': { planId: PLAN_ID, credits: 1 }
        }))

        app.post('/api/query', async (req, res) => {
          // If we reach here, payment is already verified
          const result = await processAIQuery(req.body.prompt)
          res.json(result)
        })

        app.listen(3000)
        ```

        <Note>Your `package.json` must include `"type": "module"` for the `@nevermined-io/payments/express` subpath import to work.</Note>
      </Tab>

      <Tab title="Python (FastAPI)">
        ```python theme={null}
        import os
        from fastapi import FastAPI
        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='sandbox'
            )
        )

        PLAN_ID = os.environ['NVM_PLAN_ID']

        # Add payment protection — 1 credit per request to /api/query
        app.add_middleware(
            PaymentMiddleware,
            payments=payments,
            routes={
                "POST /api/query": {"plan_id": PLAN_ID, "credits": 1}
            }
        )

        @app.post("/api/query")
        async def query(request: dict):
            # If we reach here, payment is already verified
            result = await process_ai_query(request.get("prompt"))
            return result
        ```

        <Note>Install with `pip install payments-py[fastapi]` — the `[fastapi]` extra is required for the middleware.</Note>
      </Tab>
    </Tabs>

    This flow protects your agent and automates billing.
  </Step>
</Steps>

## For Users (Subscribers): Access an AI Agent

### Using the Nevermined Web App

1. **Discover**: Find agents in the [Nevermined App](https://nevermined.app/) or other marketplaces.
2. **Purchase**: Select a pricing plan and purchase it with crypto or a credit card.
3. **Get Credentials**: Once purchased, you'll receive API credentials to access the agent.

### Using the SDKs

<Tabs>
  <Tab title="TypeScript">
    ```typescript theme={null}
    // 1. Discover the agent and its plans
    const agent = await payments.agents.getAgent('AGENT_ID');
    const plan = agent.plans[0];

    // 2. Purchase the plan
    // Option A: Crypto payment (nvm:erc4337 scheme)
    const orderResult = await payments.plans.orderPlan(plan.planId);
    console.log('Order transaction:', orderResult.transactionHash);

    // Option B: Fiat payment (credit card → nvm:card-delegation scheme).
    // The browser is redirected to Stripe to complete the purchase.
    const { sessionId, url } = await payments.plans.orderFiatPlan(plan.planId);
    window.location.href = url; // Redirect to Stripe

    // 3. Get X402 access token. Create the delegation first (provider +
    // currency required), then request the token by its delegationId.

    // Crypto plan (Option A)
    const delegation = await payments.delegation.createDelegation({
      provider: 'erc4337',
      spendingLimitCents: 1000,
      durationSecs: 86_400,
      currency: 'usdc',
    });
    const { accessToken } = await payments.x402.getX402AccessToken(plan.planId, agent.agentId, {
      scheme: 'nvm:erc4337',
      delegationConfig: { delegationId: delegation.delegationId },
    });

    // Fiat plan (Option B) — create a card delegation from the enrolled card,
    // then request the token by its delegationId.
    // const cardDelegation = await payments.delegation.createDelegation({
    //   provider: 'stripe',
    //   providerPaymentMethodId: 'pm_xxx',
    //   spendingLimitCents: 1000,
    //   durationSecs: 86_400,
    //   currency: 'usd',
    // });
    // const { accessToken } = await payments.x402.getX402AccessToken(plan.planId, agent.agentId, {
    //   scheme: 'nvm:card-delegation',
    //   delegationConfig: { delegationId: cardDelegation.delegationId },
    // });

    // 4. Query the agent using the access token
    // Extract URL from endpoint object (endpoints have HTTP method as key)
    const endpoint = agent.endpoints[0]
    const method = Object.keys(endpoint)[0]
    const url = endpoint[method]

    const response = await fetch(url, {
      method: method,
      headers: {
        'Content-Type': 'application/json',
        'payment-signature': accessToken
      },
      body: JSON.stringify({
        prompt: "Hello, how can you help me?"
      })
    });

    const result = await response.json();
    console.log('Agent response:', result);
    ```
  </Tab>

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

    # 1. Discover the agent and its plans
    agent = payments.agents.get_agent('AGENT_ID')
    plan = agent['plans'][0]

    # 2. Purchase the plan
    # Option A: Crypto payment
    order_result = payments.plans.order_plan(plan['planId'])
    print(f'Order transaction: {order_result["transactionHash"]}')

    # Option B: Fiat payment (credit card)
    fiat_result = payments.plans.order_fiat_plan(plan['planId'])
    print(f'Stripe checkout URL: {fiat_result["url"]}')

    # 3. Get X402 access token. Create the delegation first (provider +
    # currency required), then request the token by its delegationId.

    # Crypto plan (Option A)
    delegation = payments.delegation.create_delegation(
        CreateDelegationPayload(
            provider="erc4337",  # "stripe" | "braintree" | "visa" for fiat plans
            spending_limit_cents=1000,
            duration_secs=86_400,
            currency="usdc",  # "usd" for fiat plans
        )
    )
    token_response = payments.x402.get_x402_access_token(
        plan['planId'],
        agent['agentId'],
        token_options=X402TokenOptions(
            scheme="nvm:erc4337",
            delegation_config=DelegationConfig(delegation_id=delegation.delegation_id),
        ),
    )
    access_token = token_response['accessToken']

    # Fiat plan (Option B) — create a card delegation from the enrolled card,
    # then request the token by its delegationId.
    # card_delegation = payments.delegation.create_delegation(
    #     CreateDelegationPayload(
    #         provider="stripe",
    #         provider_payment_method_id="pm_xxx",
    #         spending_limit_cents=1000,
    #         duration_secs=86_400,
    #         currency="usd",
    #     )
    # )
    # token_response = payments.x402.get_x402_access_token(
    #     plan['planId'],
    #     agent['agentId'],
    #     token_options=X402TokenOptions(
    #         scheme="nvm:card-delegation",
    #         delegation_config=DelegationConfig(delegation_id=card_delegation.delegation_id),
    #     ),
    # )

    # 4. Query the agent using the access token
    # Extract URL from endpoint object (endpoints have HTTP method as key)
    endpoint = agent['endpoints'][0]
    method = list(endpoint.keys())[0]
    url = endpoint[method]

    response = requests.post(
        url,
        headers={
            'Content-Type': 'application/json',
            'payment-signature': access_token
        },
        json={'prompt': 'Hello, how can you help me?'}
    )

    result = response.json()
    print(f'Agent response: {result}')
    ```
  </Tab>
</Tabs>

<Tip>
  In autonomous or agent-to-agent workflows, you can skip the manual `order_plan()` step: attach a delegation when generating the access token and the facilitator tops up credits automatically when the balance runs out. See [Automatic Credit Top-Ups](/docs/integrate/patterns/top-up).
</Tip>
