Documentation

PayAgents Documentation

Explore our guides and examples to integrate PayAgents in your existing system.

Getting Started

Integrate transactional controls into your workspace in less than five minutes. Our SDK wraps all transaction formatting, signature generation, and verification. Learn how to install the package, obtain API keys, and initialize the client.

Explore

Receive Payments

Monetize your AI agent tools, data feeds, and specialized endpoints by setting up L402 and X402 payment challenges. The PayAgents SDK intercepts incoming calls, handles multiple rails automatically, and settles balances.

Explore

Send Payments

Give your autonomous software agents the power to execute L402 and X402 payments and navigate gated developer portals dynamically using the pay() API wrapper, and configure spend protection limits in the dashboard.

Explore PAY

MCP Monetization

Model Context Protocol (MCP) allows LLMs to safely query data or run scripts. Connect PayAgents middleware to charge L402 or X402 micropayments on a per-tool-call basis. Setup pricing parameters and explore billing modes.

Explore

Introduction

Welcome to the PayAgents developer documentation. PayAgents is an all-in-one payment routing API and SDK built to power the machine-to-machine agentic economy.

As software agents evolve to complete complex workflows—such as querying external data, training LLMs, or executing web actions—they frequently hit paywalls. Traditional subscription models and credit cards fail for automated agent systems because they require interactive manual checks, incur high fraud risks, and charge expensive fees for tiny, high-frequency actions.

Why Machine-Native Payments?

Autonomous AI agents require low-latency, friction-free transactions. PayAgents handles this by routing value instantly using micropayment rails, enabling agents to pay for only what they consume, down to a fraction of a cent.

Key Protocols Supported

  • L402 (Bitcoin Lightning network): A protocol that marries Lightning payment invoices with HTTP headers. Ideal for extremely high-frequency micropayments settled in SATs.
  • x402 (Base Stablecoins): Standardized stablecoin payments on Coinbase's Layer-2 Base network. Perfect for stable, dollar-denominated agentic utilities with low network gas.

Unified Wallet Framework

Developers using PayAgents do not need to run their own node clusters, manage private keys, lock liquidity in payment channels, or worry about swapping base assets to pay transaction gas. In the background, our core engine auto-swaps and routes funds, exposing a unified USD balance. You deposit and withdraw standard currency, and we route the payments across whatever rails the counterparty demands.

Getting Started

Integrate transactional controls into your workspace in less than five minutes. Our SDK wraps all transaction formatting, signature generation, and verification.

1. Install the SDK

Add the PayAgents package to your project repository:

terminal
npm install payagents

2. Obtain an API Key

Go to the PayAgents Dashboard, log in or create an account, and generate a new key inside the **API Settings** tab. Always store this key in your environment variables:

.env
PAYAGENTS_API_KEY=pa_live_58c97be34015f...

3. Initialize the Client

Import and instantiate the PayAgents client in your logic files:

index.ts
import { PayAgents } from 'payagents'; const client = new PayAgents({ apiKey: process.env.PAYAGENTS_API_KEY });

Receiving Payments

Monetize your custom APIs and agentic services by gating endpoints behind a paywall. The SDK offers middleware utilities that automatically issue payment challenges and intercept verification hashes.

Cross-Rail Gating

When gating an API, you only configure the target USD fee. PayAgents automatically formats the response headers so that agents requesting via L402 receive Lightning invoices, while agents requesting via x402 receive EVM stablecoin challenges. The settlement arrives in your USD balance sheet regardless.

Gating HTTP API Endpoints

Below is an integration example demonstrating how to wrap a Node.js Express server endpoint using the PayAgents middleware helper:

server.ts
import express from 'express'; import { PayAgents } from 'payagents'; const app = express(); const pa = PayAgents.server({ apiKey: process.env.PAYAGENTS_API_KEY }); // Gate this endpoint: charge $0.005 per call app.post('/api/v1/extract', pa.middleware({ price: '0.005 USD' }), async (req, res) => { // Inside here, the payment is guaranteed to be validated and settled. const data = await performExtraction(req.body.url); res.json({ success: true, data }); } ); app.listen(3000);

How the Gating Protocol Works

  1. Initial Unpaid Request: An AI agent calls `/api/v1/extract` without headers.
  2. Challenge Issued: The PayAgents middleware intercepts and responds with an `HTTP 402 Payment Required` status, attaching metadata containing payment instructions (Lightning invoice preimage details or EVM signature parameters).
  3. Settlement: The caller agent automatically pays the invoice or stablecoin payload via their own PayAgents client.
  4. Fulfillment Request: The caller retries the original API request, appending the verification token or preimage hash inside the `Authorization` header.
  5. Verification: The middleware parses the headers, validates the preimage through the PayAgents network, settles the balance, and passes execution to your route handler.

Enabling Spending

Give your AI agents the capability to pay for external resources autonomously using the `pay()` API wrapper. The PayAgents engine handles payment rails and checks balance limits locally.

Executing a Payment

To let your agent purchase gated data or tool actions, pass the destination URL and policy bounds directly to the SDK client:

caller.ts
import { PayAgents } from 'payagents'; const client = new PayAgents({ apiKey: '...' }); try { // Call client.pay to query a payment-gated endpoint const response = await client.pay('https://api.scraper.io/gated-route', { maxAmount: '0.01 USD', // Max authorization threshold payload: { target: 'https://news.ycombinator.com' } }); console.log('Response content:', response.data); } catch (err) { console.error('Payment routing failed or budget exceeded:', err); }

Spend Protection against Hallucinations

AI agents can occasionally hallucinate or enter recursive calling loops that drain corporate wallets in seconds. It is highly recommended to set strict transaction caps and monthly limits in your PayAgents dashboard to prevent budget overrun.

Dashboard Spend Policies

Through your developer console, you can customize limits for every API key:

  • Single-Payment Cap: Intercept and abort any transaction exceeding a specific threshold (e.g. max $0.05 per action).
  • Daily/Monthly Quotas: Restrict cumulative daily or monthly spend bounds.
  • Domain Allowlists: Ensure keys are only allowed to spend balances on verified API URLs.
  • Human Approval Gateways: Require manual authentication in your dashboard for transactions above a specified cost (e.g. any charge above $1.00 triggers an email/Slack approval webhook).

MCP Monetization

Model Context Protocol (MCP) is an open standard that allows LLM models to securely read data or run terminal scripts on host systems. By importing the PayAgents server middleware, you can charge micropayments on a per-tool-call basis.

Monetizing MCP Servers

The PayAgents SDK exposes a direct tool wrapper for MCP server platforms. Simply configure the price per tool call using `pa.charge`:

mcp-server.ts
import { McpServer } from '@modelcontextprotocol/sdk'; import { PayAgents } from 'payagents'; const server = new McpServer({ name: 'premium-search', version: '1.0.0' }); const pa = PayAgents.server({ apiKey: process.env.PAYAGENTS_API_KEY }); // Charge $0.002 every time the agent invokes search server.tool('web_search', pa.charge({ price: '0.002 USD', per: 'call' }), async ({ query }) => { const results = await fetchSearchIndex(query); return { content: [{ type: 'text', text: results }] }; } );

Billing Modes Supported

  • Per-Invocation: A flat USD rate for each call (e.g. `$0.01` per tool execution). Great for database reads, stock alerts, or notifications.
  • Volume/Data Gated: Calculate a bill dynamically based on input token lengths or output sizes. Excellent for generative AI tools or bulk page scrapers.