x402 技术文档

x402是一个基于HTTP的支付协议,使用标准的402 Payment Required状态码来实现互联网原生支付。

核心特性

  • 无手续费协议
  • 2秒快速结算
  • HTTP原生集成
  • 多链支持
  • 最小化信任
  • 一行代码集成

技术架构

客户端 (Client)
发起支付请求的用户或应用
资源服务器 (Resource Server)
提供付费资源的HTTP服务器
协调器 (Facilitator)
处理支付验证和结算的服务

快速开始

在几分钟内集成x402支付协议到您的应用中。

1. 安装依赖

# 使用 npm
npm install x402

# 使用 yarn
yarn add x402

# 使用 pip (Python)
pip install x402

2. 服务器端集成

// TypeScript/Node.js
import { paymentMiddleware } from 'x402';

app.use('/api', paymentMiddleware('0xYourAddress', {
  '/weather': '$0.01',
  '/premium': '$0.05'
}));

3. 客户端调用

// 客户端代码
import { payForResource } from 'x402/client';

const response = await payForResource(
  'https://api.example.com/weather',
  '$0.01',
  'base-sepolia'
);

console.log('数据:', response.data);

协议规范

数据类型

PaymentRequiredResponse

{
  "x402Version": number,           // x402协议版本
  "accepts": [paymentRequirements], // 接受的支付要求列表
  "error": string                  // 错误消息(可选)
}

paymentRequirements

{
  "scheme": string,                // 支付协议方案
  "network": string,               // 区块链网络
  "maxAmountRequired": string,     // 最大支付金额(原子单位)
  "resource": string,              // 资源URL
  "description": string,           // 资源描述
  "mimeType": string,              // 响应MIME类型
  "payTo": string,                 // 收款地址
  "maxTimeoutSeconds": number,     // 最大超时时间
  "asset": string,                 // ERC20合约地址
  "extra": object                  // 额外信息(可选)
}

PaymentPayload

{
  "x402Version": number,           // 协议版本
  "scheme": string,                // 支付方案
  "network": string,               // 网络ID
  "payload": object                // 方案特定的载荷
}

HTTP流程

1
客户端请求
GET /resource
2
402响应
HTTP/1.1 402 Payment Required
3
支付请求
X-PAYMENT: base64_encoded_payload
4
成功响应
HTTP/1.1 200 OK + 资源

服务器集成

TypeScript/Node.js

import express from 'express';
import { paymentMiddleware } from 'x402';

const app = express();

// 基础集成
app.use('/api', paymentMiddleware('0xYourAddress', {
  '/weather': '$0.01',
  '/news': '$0.05'
}));

// 自定义配置
app.use('/api', paymentMiddleware('0xYourAddress', {
  '/weather': {
    amount: '$0.01',
    network: 'base-sepolia',
    description: 'Weather API access',
    maxTimeout: 30
  }
}));

app.listen(3000, () => {
  console.log('Server running on port 3000');
});

Python/Flask

from flask import Flask
from x402 import payment_middleware

app = Flask(__name__)

# 集成支付中间件
app.wsgi_app = payment_middleware(
    app.wsgi_app,
    '0xYourAddress',
    {
        '/weather': '$0.01',
        '/news': '$0.05'
    }
)

@app.route('/')
def hello():
    return 'Hello World!'

if __name__ == '__main__':
    app.run(debug=True)

客户端集成

JavaScript/TypeScript

import { payForResource } from 'x402/client';

// 简单调用
const response = await payForResource(
  'https://api.example.com/weather',
  '$0.01',
  'base-sepolia'
);

// 带参数调用
const response = await payForResource(
  'https://api.example.com/weather',
  '$0.01',
  'base-sepolia',
  {
    city: 'Beijing',
    units: 'metric'
  }
);

console.log('响应:', response.data);

Python

from x402 import pay_for_resource

# 调用付费资源
response = pay_for_resource(
    'https://api.example.com/weather',
    '$0.01',
    'base-sepolia'
)

# 带参数调用
response = pay_for_resource(
    'https://api.example.com/weather',
    '$0.01',
    'base-sepolia',
    {
        'city': 'Beijing',
        'units': 'metric'
    }
)

print('响应:', response['data'])

API参考

协调器接口

POST /verify

验证支付载荷的有效性

请求
{
  "x402Version": 1,
  "paymentHeader": "base64...",
  "paymentRequirements": {...}
}
响应
{
  "isValid": true,
  "invalidReason": null
}

POST /settle

执行支付结算

请求
{
  "x402Version": 1,
  "paymentHeader": "base64...",
  "paymentRequirements": {...}
}
响应
{
  "success": true,
  "txHash": "0x...",
  "networkId": "base-sepolia"
}

GET /supported

获取支持的支付方案和网络

{
  "kinds": [
    {
      "scheme": "exact",
      "network": "base-sepolia"
    },
    {
      "scheme": "exact",
      "network": "ethereum"
    }
  ]
}

支付方案

exact 方案

精确支付指定金额的简单支付方案。

适用场景

  • • API调用付费
  • • 文章阅读付费
  • • 单次服务付费
  • • 固定价格商品

实现细节

基于EIP-3009标准的无gas转账,使用授权转账机制。

// 载荷结构
{
  "type": "ethereum",
  "tx": {
    "to": "0x...",
    "data": "0x...",
    "value": "0x..."
  }
}

即将推出的方案

  • upto - 最大限额支付,按实际使用量计费
  • streaming - 流式支付,持续服务付费
  • subscription - 订阅制支付
  • escrow - 托管支付,条件释放

示例代码

天气API服务

// 完整的天气API服务示例
import express from 'express';
import { paymentMiddleware } from 'x402';

const app = express();

// x402支付中间件
app.use('/api/weather', paymentMiddleware('0xYourAddress', {
  '/current': '$0.01',
  '/forecast': '$0.03'
}));

// 天气API端点
app.get('/api/weather/current', (req, res) => {
  const weatherData = {
    temperature: 22.5,
    humidity: 65,
    description: '晴朗',
    city: req.query.city || '北京'
  };
  
  res.json(weatherData);
});

app.get('/api/weather/forecast', (req, res) => {
  const forecastData = {
    city: req.query.city || '北京',
    days: [
      { date: '2025-01-01', temp: 20, description: '多云' },
      { date: '2025-01-02', temp: 18, description: '小雨' },
      { date: '2025-01-03', temp: 22, description: '晴朗' }
    ]
  };
  
  res.json(forecastData);
});

app.listen(3000);

内容付费墙

// 文章付费墙示例
import express from 'express';
import { paymentMiddleware } from 'x402';

const app = express();

// 文章付费中间件
app.use('/articles', paymentMiddleware('0xYourAddress', {
  '/blockchain-guide': '$0.05',
  '/ai-trends': '$0.03',
  '/web3-intro': '$0.02'
}));

// 文章端点
app.get('/articles/blockchain-guide', (req, res) => {
  const article = {
    title: '区块链技术完全指南',
    content: '区块链技术是一种分布式账本技术...',
    author: '技术专家',
    readTime: '15分钟'
  };
  
  res.json(article);
});

app.get('/articles/ai-trends', (req, res) => {
  const article = {
    title: '2025年AI发展趋势',
    content: '人工智能正在快速发展...',
    author: 'AI研究员',
    readTime: '10分钟'
  };
  
  res.json(article);
});

app.listen(3000);

故障排除

常见问题

支付验证失败

原因:支付载荷格式不正确或签名无效

解决方案:

  • • 检查支付载荷的Base64编码
  • • 验证签名和地址匹配
  • • 确保网络ID正确

网络连接超时

原因:区块链网络延迟或协调器无响应

解决方案:

  • • 增加超时时间设置
  • • 检查网络连接状态
  • • 尝试备用协调器

余额不足

原因:客户端钱包余额不足以支付费用

解决方案:

  • • 检查钱包余额
  • • 确保有足够的代币
  • • 考虑使用测试网

调试工具

  • 日志记录 - 启用详细日志记录来跟踪请求流程
  • 网络监控 - 使用浏览器开发者工具监控HTTP请求
  • 测试网 - 在测试网上进行开发和测试
  • 社区支持 - 访问GitHub获取社区支持