Skip to main content

概览

什么是 x402 API

x402 是一种全新的开放支付协议,支持通过 HTTP 直接进行即时、自动的稳定币支付。 即时访问,零摩擦。 x402 利用 HTTP 402 状态码,实现了网络上的直接稳定币支付。它用一种简单的协议取代了复杂的身份验证和付费墙:向网络支付,获取资源。无论是用于 API 变现还是数字内容,x402 都允许客户端——从用户到自动化机器人——无需账户即可即时交易。

为什么要使用 x402?

  • 零摩擦访问: 消除对账户、注册或复杂 OAuth 流程的需求。访问权限通过支付即时授予,创造无状态的“随付随用”体验。
  • 专为 AI 代理构建: 专为机器对机器 (M2M) 的商业模式优化,使自主代理能够处理高频微交易和按请求付费的 API 调用。
  • 即时全球结算: 利用互联网原生稳定币协议消除金融中介,确保卖方实现低成本和即时结算。
  • 直接变现: 赋能开发者和内容创作者进行精细化变现(例如:按 API 调用次数或按文章付费),同时允许买家通过编程方式访问资源,无需订阅。

工作原理

x402 使用简单的请求-响应流程,实现了基于 HTTP 的程序化支付。当客户端请求付费资源时,服务器响应支付要求,客户端提交支付,服务器随即交付资源。

主要特性

  • Gas 补贴: 在 Gate Layer 上实现免 Gas 代币(白名单代币)的转账和支付。
  • 多网络支持: 支持 Gate Layer。更多网络支持敬请期待。
  • SDKs: 生产就绪的客户端和服务器端库。

支付流程

支付流程图

API 访问和用法

在使用 API 之前,您需要在开发者门户中创建一个项目并生成 API 密钥 (API Key)。

限流

为了确保服务的稳定性,API 对请求频率实施了限制。

限制规则:

  • 用户级限制: 每个 Access Key 对单个 API 接口的调用频率限制为每秒 1 次请求 。
  • 全局限制: 单个 API 接口 (Action) 全网每秒最多允许发送 50 个请求 (50 QPS)。

响应处理:

如果请求超出限制,API 将返回下方错误码。

错误码常量名描述
10131RATE_LIMIT_GLOBAL_EXCEEDED全局限流超限
10132RATE_LIMIT_PER_AK_EXCEEDED每 Access Key 限流超限
10133RATE_LIMIT_PER_ACTION_EXCEEDED每 Action 限流超限

支持的网络和币种

目前已支持 Gate Layer。更多网络的支持正在开发中,敬请期待。

Networkx402 APIChainIndex
Gate LayerSupported10088

测试网 Facilitator

x402测试网 Facilitator 可用于测试和开发:

Networkx402 APIChainIndex
Gate Layer TestnetSupported10087

开始

开发者平台

为了帮助您快速访问和管理 API 服务,本指南介绍了开发者管理平台的主要功能和使用方法,包括注册/登录、API 密钥创建、账户安全设置和密钥管理。

API 列表

介绍

x402 支付协议是一种基于 HTTP 的支付协议,旨在通过多种支付方式,使运行资源服务器的开发者能够接收用户的付款。x402 Facilitator API 通过暴露三个 API 接口,使您能够利用 x402 支付协议促进支付。

获取基本信息

请求地址 https://openapi.gateweb3.cc/api/v1/x402

{"action": "x402.supported", "params": {}}

请求参数

响应参数

参数类型描述
kindsArray支持的支付类型数组
>x402VersionIntegerx402 的版本,如1
>schemeString结算方案,如 exact (按固定金额一次性支付)
>networkString网络标识,如 gatelayer
extensionsArray[String]扩展字段

请求示例

curl -X POST [https://openapi.gateweb3.cc/api/v1/x402](https://openapi.gateweb3.cc/api/v1/x402) \
-H "Content-Type: application/json" \
-H "X-API-Key: your-api-key" \
-H "X-Signature: your-signature" \
-H "X-Timestamp: $(date +%s%3N)" \
-H "X-Request-Id: ${REQUEST_ID}" \
-d '{
"action": "x402.supported",
"params": {
}
}'

响应示例

{
"code": 0,
"msg": "",
"data": {
"kinds": [
{
"x402Version": 2,
"scheme": "exact",
"network": "gatelayer_testnet"
}
],
"extensions": [

]
},
"timestamp": 1769592841
}

提交交易

请求地址 https://openapi.gateweb3.cc/api/v1/x402

{"action": "x402.settle", "params": {}}

请求参数

参数类型必传描述
x402VersionIntegerx402 的协议版本 如2
paymentPayloadObject客户端随受保护请求携带的 x402 支付载荷
>x402VersionIntegerx402 的协议版本 如2
>acceptObject使用的结算方案
>>schemeString结算方案,如 exact (按固定金额一次性支付),若空则回退回 paymentRequirements
>>networkString网络标识,如 gatelayer,若空则回退回 paymentRequirements
>payloadObject付款签名与授权数据对象
>>signatureString加密签名
>>authorizationObject授权信息
>>>fromString付款地址
>>>toString收款地址
>>>valueString转账金额
>>>validAfterString生效时间(Unix)
>>>validBeforeString失效时间(Unix)
>>>nonceString随机数,防止重放
paymentRequirementsObject支付内容用于付费访问资源的信息(金额/网络/资产/收款方等)
>schemeString结算方案,如 exact (按固定金额一次性支付)
>networkString网络标识,如 gatelayer
>assetString资产标识/合约地址(视网络而定
>amountString转账金额
>payToString收款人
>maxTimeoutSecondsInteger授权有效后最大等待秒数

响应参数

参数类型描述
successBoolean调用是否成功
payerString付款人
transactionString交易的 hash
errorReasonString失败原因
networkString网络

请求示例

curl -X POST [https://openapi.gateweb3.cc/api/v1/x402](https://openapi.gateweb3.cc/api/v1/x402) \
-H "Content-Type: application/json" \
-H "X-API-Key: your-api-key" \
-H "X-Signature: your-signature" \
-H "X-Timestamp: $(date +%s%3N)" \
-H "X-Request-Id: ${REQUEST_ID}" \
-d '{
"action": "x402.settle",
"params": {
"x402Version": 2,
"paymentPayload": {
"x402Version": 2,
"accepted": {
"scheme": "exact",
"network": "gatelayer_testnet"
},
"payload": {
"signature": "0x437830ba823c6d680c43fa820af1acdef16da9db3c58e031031c3a8051e5f1c6379d6cae031a1c5601e81aa866768ec35d6b794351dc7c1b598a74ff2fda93c21b",
"authorization": {
"from": "0x9F7236e6B4AAd75603C0DdB28dE5f12DeDe6E9D4",
"to": "0xe734bb6268fcd90756e36c30d6a5fce30569eb6f",
"value": "1111",
"validAfter": "0",
"validBefore": "1768978707",
"nonce": "0x50f24a1d09b9aa10dd5b8365d871f729303362f7f48269ab431d2f4f90895355"
}
}
},
"paymentRequirements": {
"scheme": "exact",
"network": "gatelayer_testnet",
"asset": "0x9be8Df37C788B244cFc28E46654aD5Ec28a880AF",
"amount": "1111",
"payTo": "0xe734bb6268fcd90756e36c30d6a5fce30569eb6f",
"maxTimeoutSeconds": 3600
}
}
}'

响应示例

成功:

{
"code": 0,
"msg": "",
"data": {
"success": true,
"payer": "0x9F7236e6B4AAd75603C0DdB28dE5f12DeDe6E9D4",
"transaction": "0xc36d65c0de132e47852830e27325552a669e2ab6604facc5bddd674ee3eb594c",
"network": "gatelayer_testnet"
},
"timestamp": 1769593302
}

失败:

{
"code": 200,
"msg": "",
"data": {
"success": false,
"errorReason": "transaction 0x38a864a30dadea91b66ce3bff870a0ead1be4fcc8a647fc58c2f12d1516afca5 reverted on-chain at block 11943682",
"transaction": "",
"network": ""
},
"timestamp": 1768997786
}

验证交易

请求地址 https://openapi.gateweb3.cc/api/v1/x402

{"action": "x402.verify", "params": {}}

请求参数

参数类型必传描述
x402VersionIntegerx402 的协议版本 如2
paymentPayloadObject客户端随受保护请求携带的 x402 支付载荷
>x402VersionIntegerx402 的协议版本 如2
>acceptObject使用的结算方案
>>schemeString结算方案,如 exact (按固定金额一次性支付)
>>networkString网络标识,如 gatelayer
>payloadObject付款签名与授权数据对象
>>signatureString加密签名
>>authorizationObject授权信息
>>>fromString付款地址
>>>toString收款地址
>>>valueString转账金额
>>>validAfterString生效时间(Unix)
>>>validBeforeString失效时间(Unix)
>>>nonceString随机数,防止重放
paymentRequirementsObject支付内容用于付费访问资源的信息(金额/网络/资产/收款方等)
>schemeString结算方案,如 exact (按固定金额一次性支付)
>networkString网络标识,如 gatelayer
>assetString资产标识/合约地址(视网络而定)
>amountString转账金额
>payToString收款人
>maxTimeoutSecondsInteger授权有效后最大等待秒数

响应参数

参数类型描述
isValidboolean是否合法
invalidReasonstring非法原因
payerstring合法情况下 该地址的付款地址

请求示例

curl -X POST [https://openapi.gateweb3.cc/api/v1/x402](https://openapi.gateweb3.cc/api/v1/x402) \
-H "Content-Type: application/json" \
-H "X-API-Key: your-api-key" \
-H "X-Signature: your-signature" \
-H "X-Timestamp: $(date +%s%3N)" \
-H "X-Request-Id: ${REQUEST_ID}" \
-d '{
"action": "x402.verify",
"params": {
"x402Version": 2,
"paymentPayload": {
"x402Version": 2,
"accepted": {
"scheme": "exact",
"network": "gatelayer_testnet"
},
"payload": {
"signature": "0x437830ba823c6d680c43fa820af1acdef16da9db3c58e031031c3a8051e5f1c6379d6cae031a1c5601e81aa866768ec35d6b794351dc7c1b598a74ff2fda93c21b",
"authorization": {
"from": "0x9F7236e6B4AAd75603C0DdB28dE5f12DeDe6E9D4",
"to": "0xe734bb6268fcd90756e36c30d6a5fce30569eb6f",
"value": "1111",
"validAfter": "0",
"validBefore": "1768978707",
"nonce": "0x50f24a1d09b9aa10dd5b8365d871f729303362f7f48269ab431d2f4f90895355"
}
}
},
"paymentRequirements": {
"scheme": "exact",
"network": "gatelayer_testnet",
"asset": "0x9be8Df37C788B244cFc28E46654aD5Ec28a880AF",
"amount": "1111",
"payTo": "0xe734bb6268fcd90756e36c30d6a5fce30569eb6f",
"maxTimeoutSeconds": 3600
}
}

}'

响应示例

成功:

{
"code": 0,
"msg": "",
"data": {
"isValid": true,
"payer": "0x9F7236e6B4AAd75603C0DdB28dE5f12DeDe6E9D4"
},
"timestamp": 1769593299
}

失败:

{
"code": 200,
"msg": "",
"data": {
"isValid": false,
"invalidReason": "nonce already used"
},
"timestamp": 1768997783
}

错误码

错误码常量名说明
0CodeSuccess成功
51001CodeInvalidPayload支付负载无效或缺失
51002CodeInvalidRequirements支付要求无效或缺失
51003CodeMissingPayloadField缺少 payload 字段
51101CodeUnsupportedNetwork不支持的网络
51201CodeTokenNotFoundToken 未找到
51301CodeInvalidExactPayload无效的 exact payload 格式
51302CodeMissingSignature缺少签名
51401CodeRecipientMismatch收款人地址不匹配
51402CodeInvalidAuthValue无效的授权值格式
51403CodeInvalidRequiredAmount无效的所需金额格式
51404CodeInsufficientAmount金额不足
51502CodeNonceAlreadyUsedNonce 已被使用
51602CodeInsufficientBalance余额不足
51701CodeInvalidSignatureFormat无效的签名格式
51702CodeInvalidSignatureLength无效的签名长度(应为 65 字节)
51704CodeInvalidSignature无效的签名(签名验证失败)
51901CodeInvalidValueFormat无效的 value 格式
51902CodeInvalidValidAfterFormat无效的 validAfter 格式
51903CodeInvalidValidBeforeFormat无效的 validBefore 格式
51904CodeInvalidNonceFormat无效的 nonce 格式
51905CodeInvalidNonceLength无效的 nonce 长度(应为32字节)

指南(SDK及Demo)

付款案例

本指南将向您展示如何创建一个 Go 客户端,可以向 x402 保护的资源发起付费请求。

前置条件

在开始之前,请确保您拥有:

  • 拥有 USDC 的加密钱包(任何兼容 EVM 的钱包)
  • 已安装 Go 1.24+
  • 需要通过 x402 支付的服务

1. 安装依赖

将 x402 Go 模块添加到您的项目中:

go get [github.com/gatechain/x402/go](https://github.com/gatechain/x402/go)

2. 创建支持支付的 HTTP 客户端

SDK 自动使用链的 DOMAIN_SEPARATOR 处理支付创建和签名。对于 gatelayer_testnet,它使用代币合约的正确 DOMAIN_SEPARATOR 以确保签名有效。 以下是完整可运行示例:

package main

import (
"context"
"encoding/json"
"fmt"
"net/http"
"os"
"time"

x402 "[github.com/gatechain/x402/go](https://github.com/gatechain/x402/go)"
x402http "[github.com/gatechain/x402/go/http](https://github.com/gatechain/x402/go/http)"
evm "[github.com/gatechain/x402/go/mechanisms/evm/exact/client](https://github.com/gatechain/x402/go/mechanisms/evm/exact/client)"
evmsigners "[github.com/gatechain/x402/go/signers/evm](https://github.com/gatechain/x402/go/signers/evm)"
)

func main() {
// Get configuration from environment
privateKey := os.Getenv("EVM_PRIVATE_KEY")
if privateKey == "" {
fmt.Println("❌ EVM_PRIVATE_KEY environment variable is required")
os.Exit(1)
}

url := os.Getenv("SERVER_URL")
if url == "" {
url = "http://localhost:4021/weather"
}

fmt.Printf("🚀 Making paid request to: %s\n\n", url)

// Create EVM signer from private key
evmSigner, err := evmsigners.NewClientSignerFromPrivateKey(privateKey)
if err != nil {
fmt.Printf("❌ Failed to create signer: %v\n", err)
os.Exit(1)
}

fmt.Printf("✅ Signer created: %s\n\n", evmSigner.Address())

// Create x402 client and register EVM scheme
// The SDK automatically uses the chain's DOMAIN_SEPARATOR for signing
// For gatelayer_testnet, it uses the correct DOMAIN_SEPARATOR from the chain
x402Client := x402.Newx402Client().
Register("gatelayer_testnet", evm.NewExactEvmScheme(evmSigner))

// Wrap HTTP client with payment handling
// PaymentRoundTripper automatically handles 402 responses and retries with payment
httpClient := x402http.WrapHTTPClientWithPayment(
http.DefaultClient,
x402http.Newx402HTTPClient(x402Client),
)

// Make request - payment is handled automatically
// The PaymentRoundTripper will:
// 1. Make the initial request
// 2. If it receives a 402 Payment Required response, it will:
// - Parse the payment requirements from the response
// - Create a payment payload using the chain's DOMAIN_SEPARATOR
// - Sign the payment payload
// - Retry the request with the payment header
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()

req, err := http.NewRequestWithContext(ctx, "GET", url, nil)
if err != nil {
fmt.Printf("❌ Failed to create request: %v\n", err)
os.Exit(1)
}

resp, err := httpClient.Do(req)
if err != nil {
fmt.Printf("❌ Request failed: %v\n", err)
os.Exit(1)
}
defer resp.Body.Close()

// Check response status
if resp.StatusCode != http.StatusOK {
body, _ := json.Marshal(map[string]interface{}{
"status": resp.StatusCode,
"message": "Request failed",
})
fmt.Printf("❌ HTTP %d: %s\n", resp.StatusCode, string(body))
os.Exit(1)
}

// Read response
var data map[string]interface{}
if err := json.NewDecoder(resp.Body).Decode(&data); err != nil {
fmt.Printf("❌ Failed to decode response: %v\n", err)
os.Exit(1)
}

fmt.Println("✅ Response received:")
prettyJSON, _ := json.MarshalIndent(data, " ", " ")
fmt.Printf("%s\n\n", string(prettyJSON))

// Check payment response header
paymentHeader := resp.Header.Get("PAYMENT-RESPONSE")
if paymentHeader == "" {
paymentHeader = resp.Header.Get("X-PAYMENT-RESPONSE")
}

if paymentHeader != "" {
fmt.Println("💰 Payment settled successfully!")
fmt.Printf(" Payment header: %s\n", paymentHeader)
}
}

3. 工作原理

包装的 HTTP 客户端会自动:

  1. 检测 402 响应: 当服务器响应 402 Payment Required 时,客户端从 PAYMENT-REQUIRED 头中提取支付要求。
  2. 创建支付负载: 客户端使用已注册的支付方案创建签名的支付负载。
  3. 使用支付重试: 客户端自动使用包含支付负载的 X-PAYMENT 头重试请求。
  4. 处理结算: 支付验证成功后,服务器返回资源,并在 PAYMENT-RESPONSE 头中包含结算确认。

配置

环境变量

对于 Gate Web3 OpenAPI 认证,设置以下环境变量:

# 必需
export GATE_WEB3_API_KEY="your-api-key"
export GATE_WEB3_API_SECRET="your-api-secret"

# 可选
export GATE_WEB3_PASSPHRASE="your-passphrase"
export GATE_WEB3_REAL_IP="your-real-ip" # Defaults to 127.0.0.1

Facilitator 配置

facilitator 客户端默认使用 Gate Web3 OpenAPI:

facilitatorClient := x402http.NewHTTPFacilitatorClient(&x402http.FacilitatorConfig{
URL: "[https://openapi-test.gateweb3.cc/api/v1/x402](https://openapi-test.gateweb3.cc/api/v1/x402)",
// Optional: Custom HTTP client
HTTPClient: &http.Client{
Timeout: 30 * time.Second,
},
// Optional: Custom auth provider
AuthProvider: &MyAuthProvider{},
})

收款案例

本指南将向您展示如何将 x402 集成到您的 Go 服务器中,以接受 API 或服务的支付。

前置条件

在开始之前,请确保您拥有:

  • 用于接收资金的加密钱包(任何兼容 EVM 的钱包)
  • 已安装 Go 1.24+
  • 现有的 HTTP 服务器(Gin、标准库等)

1. 安装依赖

将 x402 Go 模块添加到您的项目中:

go get [github.com/gatechain/x402/go](https://github.com/gatechain/x402/go)

2. 设置环境变量

在运行服务器之前,设置所需的环境变量:

# 必需:用于接收支付的钱包地址
export PAYEE_ADDRESS="0x1234567890123456789012345678901234567890"

# Gate Web3 OpenAPI 认证所需
export GATE_WEB3_API_KEY="your-api-key"
export GATE_WEB3_API_SECRET="your-api-secret"

# 可选
export GATE_WEB3_PASSPHRASE="your-passphrase"
export GATE_WEB3_REAL_IP="your-real-ip"

3. 创建支付保护服务器

以下是使用 Gin 框架的完整可运行示例:

package main

import (
"fmt"
"net/http"
"os"
"time"

"[github.com/gin-gonic/gin](https://github.com/gin-gonic/gin)"
x402 "[github.com/gatechain/x402/go](https://github.com/gatechain/x402/go)"
x402http "[github.com/gatechain/x402/go/http](https://github.com/gatechain/x402/go/http)"
ginmw "[github.com/gatechain/x402/go/http/gin](https://github.com/gatechain/x402/go/http/gin)"
evm "[github.com/gatechain/x402/go/mechanisms/evm/exact/server](https://github.com/gatechain/x402/go/mechanisms/evm/exact/server)"
)

func main() {
// Get receiving wallet address from environment variable
payTo := os.Getenv("PAYEE_ADDRESS")
if payTo == "" {
fmt.Println("❌ PAYEE_ADDRESS environment variable is required")
fmt.Println(" Example: export PAYEE_ADDRESS=0x1234567890123456789012345678901234567890")
os.Exit(1)
}

network := x402.Network("gatelayer_testnet") // Gate Layer testnet

fmt.Printf("🚀 Starting x402 payment server...\n")
fmt.Printf(" Payee address: %s\n", payTo)
fmt.Printf(" Network: %s\n", network)
fmt.Printf(" Facilitator: [https://openapi-test.gateweb3.cc/api/v1/x402](https://openapi-test.gateweb3.cc/api/v1/x402)\n\n")

r := gin.Default()

// Create facilitator client (Gate Web3 OpenAPI Testnet)
// The client will automatically use Gate Web3 authentication if environment variables are set:
// - GATE_WEB3_API_KEY
// - GATE_WEB3_API_SECRET
// - GATE_WEB3_PASSPHRASE (optional)
// - GATE_WEB3_REAL_IP (optional)
facilitatorClient := x402http.NewHTTPFacilitatorClient(&x402http.FacilitatorConfig{
URL: "[https://openapi-test.gateweb3.cc/api/v1/x402](https://openapi-test.gateweb3.cc/api/v1/x402)",
})

// Apply x402 payment middleware
r.Use(ginmw.X402Payment(ginmw.Config{
Routes: x402http.RoutesConfig{
"GET /weather": {
Accepts: x402http.PaymentOptions{
{
Scheme: "exact",
PayTo: payTo,
Price: "$0.001", // Price in USD - automatically converts to USDC on the network
Network: network,
},
},
Description: "Get weather data for a city",
MimeType: "application/json",
},
},
Facilitator: facilitatorClient,
Schemes: []ginmw.SchemeConfig{
{Network: network, Server: evm.NewExactEvmScheme()},
},
SyncFacilitatorOnStart: true,
Timeout: 30 * time.Second,
}))

// Protected endpoint
r.GET("/weather", func(c *gin.Context) {
city := c.DefaultQuery("city", "San Francisco")
c.JSON(http.StatusOK, gin.H{
"city": city,
"weather": "sunny",
"temperature": 70,
"timestamp": time.Now().Format(time.RFC3339),
})
})

// Health check endpoint (no payment required)
r.GET("/health", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"status": "ok",
"version": "1.0.0",
})
})

fmt.Printf(" Server listening on http://localhost:4021\n")
if err := r.Run(":4021"); err != nil {
fmt.Printf("❌ Error starting server: %v\n", err)
os.Exit(1)
}
}

4. 测试您的集成

启动您的服务器:

go run main.go

发起不带支付的请求:

curl http://localhost:4021/weather

服务器会响应 402 Payment Required,并在 PAYMENT-REQUIRED 头中包含支付说明。 使用兼容的客户端完成支付并重试请求。 支付验证成功后,服务器会返回您的 API 响应。

用户协议

https://web3.gate.com/api-service-agreement

最后更新于2026/02/06