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

# AI Agent Payments: Autonomous Crypto Transactions

> Enable AI agents to send and receive stablecoin payments autonomously. Non-custodial, self-hosted crypto payment infrastructure for agentic workflows.

AI agents can send and receive stablecoin payments autonomously using XPayLabs. Agents call the REST API to create collection orders and initiate payouts, listen for webhook events, and manage balances — with zero gateway fees and full self-custody of funds.

## Why Crypto for AI Agents?

| Challenge                            | XPayLabs Solution                                                             |
| ------------------------------------ | ----------------------------------------------------------------------------- |
| Agents need programmable money       | REST API for createCollection / createPayout — agents call endpoints directly |
| No human in the loop for approvals   | Automated signing with environment-stored secrets                             |
| Cross-border agent-to-agent payments | Stablecoins on TRON, EVM, and SUI settle in seconds                           |
| Microtransactions                    | Zero gateway fees — only blockchain gas costs ($0.01–$0.50)                   |
| Self-custody required                | Non-custodial — keys stay in your Docker containers                           |

## Agent Payment Flows

### Incoming Payments (Agent Gets Paid)

An agent receives crypto payments by creating collection orders. This is the most common flow — users or other agents send funds to a deposit address generated by the agent.

```typescript theme={null}
// AI agent creates a payment request
async function requestPayment(userId: string, amount: number, orderId: string) {
  const collection = await xpay.createCollection({
    amount,
    symbol: 'USDT',
    chain: 'TRON',
    orderId,
    uid: userId,
  });

  return {
    depositAddress: collection.data.address,
    expiresAt: collection.data.expiredTime,
    checkoutUrl: collection.data.paymentUrl,
  };
}
```

The agent then listens for the `ORDER_SUCCESS` webhook to release the service:

```typescript theme={null}
// Webhook handler for the agent
app.post('/webhook', (req, res) => {
  const event = xpay.parseWebhook(JSON.stringify(req.body), req.body.sign, req.body.timestamp.toString());

  if (event?.notifyType === 'ORDER_SUCCESS') {
    const data = event.data as any;
    // Release API credits, unlock features, or start a job
    await unlockService(data.orderId, data.actualAmount);
  }

  res.status(200).send('ok');
});
```

### Outgoing Payments (Agent Pays Out)

An agent initiates payouts to external addresses — paying for compute, staking, or settling with other agents:

```typescript theme={null}
// Agent pays for compute resources
async function payComputeProvider(providerAddress: string, amount: number, jobId: string) {
  const payout = await xpay.createPayout({
    amount,
    symbol: 'USDT',
    chain: 'ETH',
    orderId: `compute-${jobId}`,
    receiveAddress: providerAddress,
    uid: 'ai-agent-01',
  });

  return payout.data.orderId;
}
```

### Agent-to-Agent Payments

Two autonomous agents can transact directly:

```
Agent A  ──POST /v1/order/createCollection──▶  Gateway  ──returns deposit address──▶  Agent A
                                                                                           │
                                                                                           │ sends deposit address to Agent B
                                                                                           ▼
Agent B  ──sends USDT to address─────────────▶  Blockchain  ──scanner detects──▶  Gateway
                                                                                           │
                                                                                           │ ORDER_SUCCESS webhook
                                                                                           ▼
Agent A  ──receives webhook──▶  fulfills agreement
```

## Autonomous Agent Architecture

```
┌─────────────────────────────────────────────────┐
│                  Your Server                     │
│                                                   │
│  ┌──────────┐     ┌─────────────┐               │
│  │  Agent A  │────▶│ XPayLabs    │               │
│  │ (buyer)   │◀───│ SDK / API   │               │
│  └──────────┘     └──────┬──────┘               │
│                          │                       │
│  ┌──────────┐            │   ┌───────────────┐  │
│  │  Agent B  │───────────┘   │  Webhook      │  │
│  │ (seller)  │───────────────│  Endpoint     │  │
│  └──────────┘               └───────────────┘  │
│                          │                       │
│                   ┌──────▼──────┐               │
│                   │  Blockchain │               │
│                   │  Scanner    │               │
│                   └─────────────┘               │
└─────────────────────────────────────────────────┘
```

## Key Design Considerations

### Secret Management

The merchant token and API secret must be accessible to the agent at runtime without hardcoding:

```bash theme={null}
# Environment variables — never commit to git
XPAYLABS_MERCHANT_TOKEN=your-merchant-token
XPAYLABS_API_SECRET=your-api-secret
XPAYLABS_GATEWAY_URL=http://gateway:180
```

### Idempotency

Agents may retry failed requests. Use the `orderId` field as an idempotency key — the same `orderId` on a `createCollection` or `createPayout` call returns the existing order instead of creating a duplicate.

### Webhook Reliability

Agents should use the polling fallback (`getOrderStatus`) if webhooks are missed. Poll every 3 seconds until `SUCCESS`, `EXPIRED`, or `FAILED`:

```typescript theme={null}
async function waitForConfirmation(orderId: string, maxWaitMs = 120000): Promise<boolean> {
  const start = Date.now();

  while (Date.now() - start < maxWaitMs) {
    const status = await xpay.getOrderStatus(orderId);
    const s = status.data?.status;

    if (s === 'SUCCESS') return true;
    if (s === 'EXPIRED' || s === 'FAILED') return false;

    await new Promise(r => setTimeout(r, 3000));
  }

  return false; // timeout
}
```

### Balance Management

Before creating payouts, check the gateway's hot wallet balance:

```typescript theme={null}
const balance = await xpay.getMerchantBalance('USDT');
console.log(`Available: ${balance.data?.balance}, Frozen: ${balance.data?.frozenBalance}`);
```

For EVM chains, also ensure the hot wallet has sufficient native gas tokens (ETH, BNB, MATIC, AVAX) to cover transaction fees.

## Use Cases

| Use Case                  | Flow                                                                   | Example                 |
| ------------------------- | ---------------------------------------------------------------------- | ----------------------- |
| API access pay-per-call   | Agent creates collection → user pays → webhook unlocks endpoint        | LLM inference API       |
| Compute marketplace       | Agent A pays Agent B for GPU time via payout                           | Distributed ML training |
| Autonomous affiliate      | Affiliate agent receives collection webhook, splits payout to referrer | Referral program        |
| Agent-to-agent settlement | Periodic batch payouts between agent wallets                           | Cross-agent accounting  |
| Micropayment streaming    | Frequent small collections (ticketed)                                  | Real-time data feeds    |

## Getting Started

1. Deploy XPayLabs via [Docker Compose](/quickstart)
2. Install the [Node.js SDK](/guides/nodejs-integration) or call the [REST API](/api-reference/overview) directly
3. Configure your agent's environment with the merchant token and API secret
4. Create a webhook endpoint for `ORDER_SUCCESS` events
5. Start creating collection and payout orders programmatically

<Tip>
  For agent-to-agent payments, both agents can share the same XPayLabs gateway instance — or run separate instances with their own keys for full isolation.
</Tip>
