OpenCard/Docs

OpenCard API 文档

基于 x402 协议的 AI 代理虚拟卡发行

OpenCard 让 AI 代理通过 x402 支付协议使用 USDC 自主购买虚拟预付卡。

无需账户。无需 API 密钥。无需注册。 支付即认证。

基础 URL

plaintext
https://api.opencard.dev

概述

OpenCard 提供三类 REST API 端点:

类型认证方式费用用途
公开免费健康检查、定价信息、层级发现
付费 (x402)USDC 支付按层级不同创建卡片
钱包签名Ed25519/ECDSA 签名免费查看卡片

支持的网络

  • BNB (首选)— 更低费用,更快确认
  • Base — EVM 替代方案

SDK

官方客户端 SDK 将原始 x402 流程封装为一行代码方法。

安装

bash
npm install @opencardcode/opencard-sdk @bnb/web3.js

快速开始 (BNB)

typescript
import { OpenCardClient } from '@opencardcode/opencard-sdk';

const client = new OpenCardClient({
  bnbPrivateKey: 'base58-private-key',
  network: 'bnb',  // default
});

const result = await client.createCard({
  amount: 10,               // $10 tier
  nameOnCard: 'AI AGENT',
  email: 'agent@example.com',
});

console.log(result.order);  // { cardId, status: 'processing' }
// Card details delivered via webhook (5-15 min)

快速开始 (Base)

typescript
import { OpenCardClient } from '@opencardcode/opencard-sdk';

const client = new OpenCardClient({
  privateKey: '0x...',  // Base wallet with USDC
  network: 'base',
});

配置

new OpenCardClient(config)

参数类型描述
network"bnb" | "base"Payment network (default: "bnb")
bnbPrivateKeystringBase58-encoded BNB secret key
bnbKeypairKeypair@bnb/web3.js Keypair instance
privateKey0x${string}EVM hex private key (for Base)
walletClientWalletClientviem WalletClient (for Base)
baseUrlstringAPI URL (default: https://api.opencard.dev)
timeoutnumberRequest timeout in ms (default: 60000)

方法

client.createCard(params): Promise<CardResult>

创建虚拟卡。自动支付 USDC。

typescript
const result = await client.createCard({
  amount: 50,    // 10 | 25 | 50 | 100 | 200 | 500
  nameOnCard: 'AI AGENT',
  email: 'agent@example.com',
  webhookUrl: 'https://your-agent.com/card-callback',  // optional
});

client.getTiers(): Promise<Tier[]>

获取定价层级和费用明细(无需支付)。

client.health(): Promise<{ status: string }>

检查 OpenCard API 是否可达。

client.address: string

用于支付的钱包地址。


错误处理

typescript
import {
  OpenCardClient,
  InsufficientBalanceError,
  PaymentError,
  ConfigError,
  ApiError,
} from '@opencardcode/opencard-sdk';

try {
  const result = await client.createCard({ ... });
} catch (error) {
  if (error instanceof InsufficientBalanceError) {
    console.log(`Need ${error.required}, have ${error.available}`);
  } else if (error instanceof PaymentError) {
    console.log(`Payment failed: ${error.message}`);
  } else if (error instanceof ConfigError) {
    console.log(`Configuration error: ${error.message}`);
  } else if (error instanceof ApiError) {
    console.log(`Server error ${error.status}:`, error.body);
  }
}

认证

x402 支付流程

付费端点使用 x402 协议 — 您的代理支付 USDC,支付本身即为认证。

步骤 1 — 无支付请求

bash
curl -X POST https://api.opencard.dev/cards/create/tier/10 \
  -H "Content-Type: application/json" \
  -d '{"nameOnCard": "AGENT ALPHA", "email": "agent@example.com"}'

步骤 2 — 收到 402 支付指令

json
{
  "x402Version": 1,
  "accepts": [
    {
      "scheme": "exact",
      "network": "bnb:mainnet",
      "asset": "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v",
      "maxAmountRequired": "11800000",
      "payTo": "6NsXb5ChS8fxH9N3qvtMzGNZ6k2RABxuq3fgwB9hnnB",
      "maxTimeoutSeconds": 300,
      "extra": { "chainName": "BNB" }
    },
    {
      "scheme": "exact",
      "network": "eip155:8453",
      "asset": "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
      "maxAmountRequired": "11800000",
      "payTo": "0x6A119204301bF22E7358f30A6DA0BFbF7A6B9E68",
      "maxTimeoutSeconds": 300,
      "extra": { "chainName": "Base" }
    }
  ]
}
字段描述
networkbnb:mainnet eip155:8453 (Base)
assetUSDC 合约/铸造地址
maxAmountRequiredUSDC 金额(6位小数):11800000 = $11.80
payTo财务钱包地址

步骤 3 — 代理支付 USDC

将指定的 USDC 金额发送到 payTo 地址,选择您的网络。

步骤 4 — 携带支付证明重试

重新发送原始请求,附带 X-Payment 头部,包含 base64 编码的 JSON 载荷:

json
{
  "scheme": "exact",
  "network": "bnb:mainnet",
  "payload": {
    "authorization": {
      "from": "YourAgentWalletPublicKey",
      "to": "TreasuryPublicKey",
      "value": "11800000"
    },
    "txHash": "YourTransactionSignature..."
  }
}

钱包签名(免费端点)

对于读取操作,使用钱包签名进行认证。

必需的请求头

请求头描述
X-WALLET-ADDRESS您的钱包公钥
X-WALLET-SIGNATURE签名(BNB 为 base58,EVM 为 hex)
X-WALLET-TIMESTAMPUnix 时间戳(5分钟内有效)

消息格式

plaintext
opencard-auth:<unix_timestamp>
超过5分钟的时间戳将被拒绝。每次请求请生成新的时间戳。

定价

卡片为 一次性预付卡 (不可充值)。

卡面价值总费用端点
$10~$11.80/cards/create/tier/10
$25~$28.00/cards/create/tier/25
$50~$55.00/cards/create/tier/50
$100~$109.00/cards/create/tier/100
$200~$217.00/cards/create/tier/200
$500~$541.00/cards/create/tier/500

价格为估算值。402 响应中包含确切所需金额。

费用明细

  • 供应商费用(~6%)
  • 服务费(2%)
  • 安全缓冲($0.50)
所有金额以美元计。支付使用 USDC(6位小数精度)。x402 402 响应将包含确切所需的 USDC 金额。

接口端点

公开端点

这些端点无需认证。

GET/health

健康检查。

json
{
  "status": "ok",
  "timestamp": "2026-02-27T00:00:00.000Z",
  "version": "2.0.0",
  "service": "OpenCard"
}
GET/pricing

完整定价明细。

json
{
  "cardCreation": {
    "providerFeePercent": 6,
    "ourMarkupPercent": 2,
    "safetyBuffer": 0.5,
    "example": {
      "loadAmount": 50,
      "totalCostUsd": 55
    }
  },
  "network": "base",
  "asset": "USDC",
  "tiers": {
    "creation": [
      { "loadAmount": 10, "totalCost": 11.8, "endpoint": "/cards/create/tier/10" }
    ]
  }
}
GET/cards/tiers

可用层级及费用明细。


这些端点需要通过 x402 协议进行 USDC 支付。参见 认证.

POST/cards/create/tier/:amount

创建新的虚拟卡。

层级: 10, 25, 50, 100, 200, 500

参数类型描述
nameOnCardstring持卡人姓名(自动大写)
emailstring卡片交付邮箱
webhookUrlstring接收卡片详情的 URL
json
// Response 202 Accepted
{
  "success": true,
  "order": {
    "cardId": "550e8400-e29b-41d4-a716-446655440000",
    "tradeId": "abc123",
    "status": "processing",
    "loadAmount": 10,
    "createdAt": "2026-02-27T00:00:00.000Z"
  },
  "delivery": {
    "method": "webhook",
    "webhookUrl": "https://your-agent.com/callback",
    "estimatedWait": "5-15 minutes",
    "statusEndpoint": "/cards/550e8400.../status"
  },
  "payment": {
    "amountCharged": 11.8,
    "txHash": "...",
    "network": "bnb"
  }
}
卡片详情通过 webhook 异步交付(5-15分钟)。响应包含订单状态,而非卡片详情。

钱包签名端点

这些端点免费,但需要 钱包签名认证.

GET/cards

列出认证钱包拥有的所有卡片。

json
{
  "cards": [{
    "cardId": "550e8400-...",
    "nameOnCard": "AGENT ALPHA",
    "loadAmount": 10,
    "status": "completed",
    "createdAt": "2026-02-27T00:00:00.000Z"
  }]
}
GET/cards/:cardId

获取卡片详情。如已完成,包含解密的卡片信息。

json
{
  "cardId": "550e8400-...",
  "status": "completed",
  "details": {
    "cardNumber": "4111111111111111",
    "cvv": "123",
    "expiryMonth": "12",
    "expiryYear": "2028",
    "billingAddress": { ... }
  }
}
GET/cards/:cardId/status

轻量级状态检查(不含卡片详情)。


Webhooks

当卡片准备就绪时,OpenCard 会向您的 webhookUrl:

成功

json
{
  "orderId": "550e8400-...",
  "status": "completed",
  "cardDetails": {
    "cardNumber": "4111111111111111",
    "cvv": "123",
    "expiryMonth": "12",
    "expiryYear": "2028",
    "billingAddress": { ... }
  },
  "timestamp": "2026-02-27T00:15:00.000Z"
}

失败

json
{
  "orderId": "550e8400-...",
  "status": "failed",
  "error": "Card provider rejected the order",
  "timestamp": "2026-02-27T00:15:00.000Z"
}

错误

状态码含义
400无效的请求体或参数
401缺少或无效的认证
402需要支付 — 请遵循 x402 流程
404未找到卡片
429超出速率限制
500内部服务器错误

速率限制

范围限制
通用 API每 IP 每分钟 30 次请求
付费端点 (x402)每 IP 每分钟 10 次请求
Webhooks每 IP 每分钟 30 次请求

当您达到速率限制时,API 返回 429 Too Many Requests。请等待窗口重置后再重试。


架构

plaintext
AI Agent (BNB/Base wallet + USDC)
        │
        ▼
   HTTP Request (no auth)
        │
        ▼
┌──────────────────────────────┐
│        OpenCard API          │
│     (Express + x402)         │
│                              │
│  x402 paid:                  │
│   POST /cards/create/tier/N  │
│                              │
│  Wallet-signed (free):       │
│   GET  /cards                │
│   GET  /cards/:id            │
│   GET  /cards/:id/status     │
│                              │
│  Public:                     │
│   GET  /health               │
│   GET  /pricing              │
│   GET  /cards/tiers          │
└──────────┬───────────────────┘
           │
     ┌─────┴─────┐
     ▼           ▼
 Treasury     Card
 (USDC)       Provider
     │             │
     └──────┬──────┘
            ▼
      Card Delivered
      via Webhook