X402 Protocol
The X402 protocol is a payment-aware HTTP extension that enables AI agents to require and verify payments for API access. This guide provides a complete overview of X402 implementation in the Nevermined Payments Library.🔐 Bearer-token hygiene. Thepayment-signatureheader is a bearer credential — anyone holding it can spend the associated plan’s credits until it expires. Send it only over HTTPS, never log the full value, and configure your log/trace exporters (pino, winston, OpenTelemetry) to redactpayment-signature,authorization, andcookieheaders by default.
Overview of X402
X402 is an HTTP-based protocol for payment-protected resources:- 402 Payment Required: HTTP status code for payment requests
- payment-signature: Header containing payment credentials (X402 v2)
- PAYMENT-REQUIRED: Header with payment requirements in 402 responses
- PAYMENT-RESPONSE: Header with payment settlement details in success responses
- Cryptographic Signatures: ERC-4337 account abstraction for secure payments
Supported Schemes
Nevermined supports two x402 payment schemes:| Scheme | Network | Use Case | Settlement |
|---|---|---|---|
nvm:erc4337 | eip155:84532 | Crypto payments | ERC-4337 UserOps + session keys |
nvm:card-delegation | stripe | braintree | visa | Fiat/credit card | Provider charge + credit burn |
isCrypto: false use nvm:card-delegation; all others use nvm:erc4337. The SDK auto-detects the scheme via resolveScheme(). The network value within nvm:card-delegation is determined by which provider issued the delegation being consumed (stripe, braintree, or visa).
Visa support
Visa delegations use the samenvm:card-delegation scheme and SDK surface as Stripe and Braintree, but two steps must happen in a browser before the SDK can consume them:
- Card enrolment — the cardholder enrols a Visa card through VGS Collect (PCI-compliant iframe) in the Nevermined webapp. The card is bound to a Visa Agentic Token via the VGS Credential Management Platform.
- Delegation creation — the cardholder approves a delegation via a WebAuthn/passkey (FIDO) device-binding ceremony embedded by Visa VTS. This produces a single-use
assuranceDatablob bound to the spending limit + duration + merchant context.
X402 Version 2 Specification
The Nevermined Payments Library implements X402 v2, which uses:payment-signatureheader for access tokens (replaces Authorization)PAYMENT-REQUIREDheader for payment requirements (replaces custom formats)PAYMENT-RESPONSEheader for settlement receipts- Structured payment credentials with cryptographic signatures
Generate X402 Access Tokens
The supported flow is create-first: create a delegation once withpayments.delegation.createDelegation(...), then request access tokens by
passing only its delegationId. Both schemes (nvm:erc4337 and
nvm:card-delegation) require a delegationConfig — the older
“just pass planId + agentId” shape no longer mints a token and surfaces
BCK.X402.0030 (“Required token-generation input is missing or incomplete”;
the details field names the missing input) at the backend.
⚠️ Inline create-on-the-fly is deprecated. Passing creation fields (spendingLimitCents,durationSecs,providerPaymentMethodId,cardId,currency,merchantAccountId,maxTransactions) directly indelegationConfiginstead of adelegationIdstill works, butgetX402AccessTokennow emits a runtime deprecation warning. Create the delegation first (above) and pass only{ delegationId }.
Generate Tokens via Nevermined App
Users can also generate X402 access tokens through the Nevermined App:- Visit nevermined.app/permissions/agent-permissions
- Select the plan you’ve purchased
- Configure token parameters (agent, expiration, limits)
- Generate and copy the X402 access token
- Use the token in API requests
Generate Card-Delegation Tokens
For fiat plans usingnvm:card-delegation, create the delegation first with
createDelegation (passing the card’s providerPaymentMethodId), then request
tokens by its delegationId. currency is required on creation:
currency: 'eur'. The delegation’s
currency is fixed at creation, so you create one delegation per currency and
reuse each by its delegationId.
Reusing Existing Delegations
PassingdelegationConfig: { delegationId } is the supported pattern for every
provider, and the only supported pattern for Visa delegations (which cannot
be created from the SDK). Reuse one delegation across multiple agents that share
a single spending budget:
delegationId is provided, the backend verifies that the delegation is active and that the requesting API key has access, then returns its existing token without creating a new delegation. The provider (stripe, braintree, or visa) is inferred from the delegation record on the server.
To scope a token request to a specific NVM API key, add apiKeyId alongside
delegationId — both fields stay active (non-deprecated):
Deprecated: inline create-on-the-fly
⚠️ Deprecated. Supplying creation fields directly indelegationConfiginstead of adelegationId(e.g.providerPaymentMethodId+spendingLimitCents, a barecardId, or an identifier-less “auto-select” shape) still creates a delegation on the fly, butgetX402AccessTokennow emits a runtime deprecation warning. Use the create-first pattern above (createDelegation→{ delegationId }); inline creation will be removed in a future major release.
CardDelegationConfig Reference
| Field | Type | Status | Description |
|---|---|---|---|
delegationId | string | Active | Existing delegation UUID to reuse — the supported path |
apiKeyId | string | Active | NVM API Key ID to scope the token request to |
cardId | string | Deprecated | Payment method UUID to target (inline create) |
providerPaymentMethodId | string | Deprecated | Stripe payment method ID (e.g., pm_...) (inline create) |
spendingLimitCents | number | Deprecated | Max spending in cents (inline create) |
durationSecs | number | Deprecated | Duration in seconds (inline create) |
currency | string | Deprecated | Currency code (inline create) |
planId | string | Deprecated | Plan ID to scope a new delegation to (inline create) |
merchantAccountId | string | Deprecated | Stripe Connect account ID (inline create) |
maxTransactions | number | Deprecated | Max transactions allowed (inline create) |
createDelegation and pass only
delegationId (optionally apiKeyId) here.
Auto Scheme Resolution
UseresolveScheme() to auto-detect the correct scheme from plan metadata:
DelegationAPI
Manage payment methods and delegations for card delegation:listPaymentMethods accepts an optional ListOptions:
| Option | Type | Description |
|---|---|---|
provider | DelegationProvider ('stripe' | 'braintree' | 'visa' | 'erc4337') | Server-side filter that restricts the result to payment methods backed by this provider. Omit it (the default) to return methods from every provider. |
accessible | boolean | When true, return only methods accessible to the requesting API key. |
Update Payment Method
Restrict a card to specific NVM API Keys so only designated agents can use it:List Delegations
Retrieve all delegations for the authenticated user:createDelegation
Create a delegation once, then reuse it across token requests by itsdelegationId (the create-first pattern). This is the supported way to
provision spending authority for nvm:erc4337 and nvm:card-delegation —
prefer it over inline create-on-the-fly in getX402AccessToken.
CreateDelegationPayload fields:
| Field | Type | Required | Description |
|---|---|---|---|
provider | 'stripe' | 'braintree' | 'visa' | 'erc4337' | Yes | Delegation provider |
spendingLimitCents | number | Yes | Maximum spending limit in cents |
durationSecs | number | Yes | Delegation lifetime in seconds |
currency | DelegationCurrency ('usd' | 'eur' | 'usdc' | 'eurc') | Yes | Currency code — 'usdc'/'eurc' for erc4337, 'usd'/'eur' for card providers. No silent default; the backend requires it. |
providerPaymentMethodId | string | Card only | Payment method ID (Stripe pm_..., Braintree vault token, Visa Agentic token id) |
planId | string | No | Optional and additive — delegations are plan-agnostic by default; supply planId to bind the delegation to a single plan. (Visa is always plan-specific and requires it.) |
merchantAccountId | string | No | Stripe Connect account ID or Braintree merchantId |
maxTransactions | number | No | Maximum number of transactions allowed |
apiKeyId | string | No | NVM API Key ID to scope the delegation to |
Visa delegations require a browser-side device-binding ceremony and cannot be
created from the SDK — see Visa support. Create them in the
Nevermined webapp, then consume them here by delegationId.
DelegationListResponse Fields
listDelegations() resolves to a DelegationListResponse object:
| Field | Type | Description |
|---|---|---|
delegations | DelegationSummary[] | Array of delegation records |
totalResults | number | Total number of delegations |
page | number | Current page number |
offset | number | Offset into the full result set |
DelegationSummary Fields
Each item in thedelegations array is a DelegationSummary:
| Field | Type | Description |
|---|---|---|
delegationId | string | Unique delegation identifier |
provider | string | Payment provider (stripe, braintree, or visa) |
providerPaymentMethodId | string | Provider-side payment method ID |
status | string | Delegation status (Active, Revoked, etc.) |
spendingLimitCents | string | Maximum spendable amount in cents |
amountSpentCents | string | Amount already spent in cents |
remainingBudgetCents | string | Remaining budget in cents |
currency | string | Currency code (e.g., usd) |
transactionCount | number | Number of transactions made |
expiresAt | string | Expiry timestamp (ISO 8601) |
createdAt | string | Creation timestamp (ISO 8601) |
apiKeyId | string | null | API key this delegation is restricted to, or null if unrestricted |
PaymentMethodSummary Fields
| Field | Type | Description |
|---|---|---|
id | string | Payment method ID (e.g., pm_...) |
brand | string | Card brand (e.g., visa, mastercard) |
last4 | string | Last 4 digits of the card number |
expMonth | number | Card expiration month |
expYear | number | Card expiration year |
allowedApiKeyIds | string[] | null | API keys allowed to use this card (null = unrestricted) |
X402 Access Token Structure
The access token is a JWT containing an X402 v2 payment credential:Card-Delegation Token Structure
For fiat plans usingnvm:card-delegation, the token contains a JWT-based delegation authorization:
Token Components
- x402Version: Protocol version (2 for current spec)
- accepted: Payment method specification
- scheme:
nvm:erc4337for crypto ornvm:card-delegationfor fiat - network:
eip155:84532(Base Sepolia) for crypto, one ofstripe,braintree, orvisafor fiat - planId: The payment plan being used
- extra: Additional metadata (version, agentId, etc.)
- scheme:
- payload: Payment authorization
- signature (erc4337): Cryptographic proof of payment authorization
- token (card-delegation): Signed JWT encoding the delegation claims
- authorization: Subscriber identity and session keys
- extensions: Optional protocol extensions
Verify X402 Permissions
Agents verify tokens before executing requests:Verification Response
Settle X402 Permissions
After successful execution, burn credits:Settlement Response
HTTP Headers (X402 v2)
payment-signature Header
Subscribers include this header in requests:PAYMENT-REQUIRED Header (402 Response)
Agents return this header when payment is required:scheme and network vary by plan type:
Crypto plan:
PAYMENT-RESPONSE Header (Success)
Agents include this header in successful responses:Complete X402 Flow
Subscriber Side
Agent Side
buildPaymentRequired Helper
Simplifies creating X402PaymentRequired objects:scheme is set to 'nvm:card-delegation', the network is automatically set to 'stripe'.
Best Practices
- Always Verify Before Execute: Never skip token verification
- Settle After Success: Only burn credits after successful execution
- Use X402 v2 Headers: Prefer
payment-signatureover Authorization - Return 402 Properly: Include
PAYMENT-REQUIREDheader with details - Log Transactions: Record settlement transaction hashes
- Handle Errors: Provide clear error messages in 402 responses
- Token Reuse: Subscribers can reuse tokens for multiple requests
- Restrict Cards to API Keys: When running multiple agents, restrict each card to specific NVM API Keys using
allowedApiKeyIdsto prevent unauthorized spending - Reuse Delegations: Pass
delegationIdto reuse existing delegations instead of creating new ones on each request — this avoids delegation sprawl and keeps spending consolidated
Related Documentation
- Querying an Agent - How subscribers use X402 tokens
- Validation of Requests - How agents verify and settle
- MCP Integration - Automatic X402 handling in MCP
- A2A Integration - Automatic X402 handling in A2A
Source References:
src/x402/token.ts(getX402AccessToken)src/x402/delegation-api.ts(DelegationAPI: listPaymentMethods, listDelegations, updatePaymentMethod)src/x402/facilitator-api.ts(verifyPermissions, settlePermissions, buildPaymentRequired)tests/e2e/test_x402_e2e.test.ts(complete X402 flow)