x402是一个基于HTTP的支付协议,使用标准的402 Payment Required状态码来实现互联网原生支付。
在几分钟内集成x402支付协议到您的应用中。
# 使用 npm
npm install x402
# 使用 yarn
yarn add x402
# 使用 pip (Python)
pip install x402
// TypeScript/Node.js
import { paymentMiddleware } from 'x402';
app.use('/api', paymentMiddleware('0xYourAddress', {
'/weather': '$0.01',
'/premium': '$0.05'
}));
// 客户端代码
import { payForResource } from 'x402/client';
const response = await payForResource(
'https://api.example.com/weather',
'$0.01',
'base-sepolia'
);
console.log('数据:', response.data);
{
"x402Version": number, // x402协议版本
"accepts": [paymentRequirements], // 接受的支付要求列表
"error": string // 错误消息(可选)
}
{
"scheme": string, // 支付协议方案
"network": string, // 区块链网络
"maxAmountRequired": string, // 最大支付金额(原子单位)
"resource": string, // 资源URL
"description": string, // 资源描述
"mimeType": string, // 响应MIME类型
"payTo": string, // 收款地址
"maxTimeoutSeconds": number, // 最大超时时间
"asset": string, // ERC20合约地址
"extra": object // 额外信息(可选)
}
{
"x402Version": number, // 协议版本
"scheme": string, // 支付方案
"network": string, // 网络ID
"payload": object // 方案特定的载荷
}
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');
});
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)
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);
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'])
验证支付载荷的有效性
{
"x402Version": 1,
"paymentHeader": "base64...",
"paymentRequirements": {...}
}
{
"isValid": true,
"invalidReason": null
}
执行支付结算
{
"x402Version": 1,
"paymentHeader": "base64...",
"paymentRequirements": {...}
}
{
"success": true,
"txHash": "0x...",
"networkId": "base-sepolia"
}
获取支持的支付方案和网络
{
"kinds": [
{
"scheme": "exact",
"network": "base-sepolia"
},
{
"scheme": "exact",
"network": "ethereum"
}
]
}
精确支付指定金额的简单支付方案。
基于EIP-3009标准的无gas转账,使用授权转账机制。
// 载荷结构
{
"type": "ethereum",
"tx": {
"to": "0x...",
"data": "0x...",
"value": "0x..."
}
}
// 完整的天气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);
原因:支付载荷格式不正确或签名无效
解决方案:
原因:区块链网络延迟或协调器无响应
解决方案:
原因:客户端钱包余额不足以支付费用
解决方案: