使用 Go 构建 x402 付费 API 服务器:从 Gin 中间件到多网络结算的完整实战指南
使用 Go 构建 x402 付费 API 服务器从 Gin 中间件到多网络结算的完整实战指南【免费下载链接】x402A payments protocol for the internet. Built on HTTP.项目地址: https://gitcode.com/GitHub_Trending/x4/x402导读本文基于 x402 项目 go/SERVER.md 官方文档系统讲解如何用 Go 语言构建「按 HTTP 请求收费」的支付服务器。x402 是一套构建在 HTTP 之上的互联网支付协议服务器把路由声明为受保护资源客户端先支付、后访问整条链路通过 facilitator促进器完成签名验证与链上结算。读完本文你将掌握路由支付配置、Gin 中间件接入、动态定价、生命周期钩子、多网络支持、错误处理与生产部署等全部实战能力并能对照仓库源码理解每一步的底层实现。一、x402 服务器的核心职责与支付流程1.1 什么是 x402 服务器一个 x402 server 是「用支付要求保护 HTTP 资源」的应用程序其核心职责链路如下定义路由——声明哪些路由需要付费返回 402——对未付费请求返回402 Payment Required及支付要求payment requirements验证签名——通过 facilitator 验证支付签名链上结算——通过 facilitator 完成 on-chain settlement放行资源——支付成功后返回受保护资源。1.2 一次请求的完整生命周期根据 go/SERVER.md 与 HTTP 层实现一次受保护请求的完整处理流如下Client Request→ 服务器收到请求Route Matching→ 检查该路由是否需要支付对应ProcessHTTPRequest中的getRouteConfigPayment Check→ 从PAYMENT-SIGNATURE头中提取支付载荷V2 格式Base64 编码Decision 分支路由无需支付 → 直接进入业务 handler未携带支付头 → 返回 402并携带PAYMENT-REQUIRED头与支付要求携带支付但要求不匹配 → 返回 402 与 No matching payment requirements携带支付且匹配 → 调用VerifyPayment交给 facilitator 验证Verification→ facilitator 校验签名有效性Handler Execution→ 运行受保护的业务 handler此时中间件已把x402_payload与x402_requirements注入 Gin contextSettlement→ 捕获响应体后调用ProcessSettlement提交链上结算交易Response→ 返回资源并在响应头附加PAYMENT-RESPONSE结算凭证。在 Gin 中间件实现 中可以看到一个关键工程细节验证通过后中间件用一个responseCapture包装c.Writer先缓冲响应体、延迟写出待 settlement 成功后再把PAYMENT-RESPONSE头与响应体一并写出若 handler 返回了 400的状态码则跳过结算。同时Flush()与WriteHeaderNow()被实现为空操作避免在结算前提前提交 HTTP 头见 middleware.go#L482-L490。二、快速开始安装与最小 Gin 服务器2.1 安装go get github.com/x402-foundation/x402/go2.2 最小可运行示例package main import ( github.com/gin-gonic/gin x402 github.com/x402-foundation/x402/go x402http github.com/x402-foundation/x402/go/http ginmw github.com/x402-foundation/x402/go/http/gin evm github.com/x402-foundation/x402/go/mechanisms/evm/exact/server ) func main() { r : gin.Default() // 1. 配置支付路由 routes : x402http.RoutesConfig{ GET /data: { Accepts: x402http.PaymentOptions{ { Scheme: exact, PayTo: 0x..., Price: $0.001, Network: eip155:84532, }, }, Description: Get data, MimeType: application/json, }, } // 2. 创建 facilitator 客户端 facilitator : x402http.NewHTTPFacilitatorClient(x402http.FacilitatorConfig{ URL: https://x402.org/facilitator, }) // 3. 添加支付中间件 r.Use(ginmw.X402Payment(ginmw.Config{ Routes: routes, Facilitator: facilitator, Schemes: []ginmw.SchemeConfig{ {Network: eip155:84532, Server: evm.NewExactEvmScheme()}, }, })) // 4. 受保护端点 handler r.GET(/data, func(c *gin.Context) { c.JSON(200, gin.H{result: protected data}) }) r.Run(:8080) }仓库中提供了同款完整可运行示例 examples/go/servers/gin/main.go它同时注册了 Base Sepoliaeip155:84532与 Solanasolana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1两个网络并通过环境变量EVM_PAYEE_ADDRESS、SVM_PAYEE_ADDRESS、FACILITATOR_URL注入收款地址与 facilitator 地址还附带一个无需付费的/health探活端点非常适合作为上手模板。三、核心概念路由配置与模式匹配3.1 路由支付配置每个路由通过PaymentOption声明一种支付方式routes : x402http.RoutesConfig{ GET /resource: { Accepts: x402http.PaymentOptions{ { Scheme: exact, // 支付方案exact、upto 等 PayTo: 0x..., // 收款地址 Price: $0.001, // 美元计价价格 Network: eip155:84532, // 区块链网络CAIP-2 }, }, Description: Resource description, MimeType: application/json, }, }对照源码PaymentOption 结构体 还支持MaxTimeoutSeconds支付超时构建 requirements 时若未指定默认取 60 秒见 server.go 的 BuildPaymentRequirements与Extra额外元数据RouteConfig 还包含Resource资源 URL缺省时取请求 URL、CustomPaywallHTML自定义支付墙 HTML与UnpaidResponseBody未付费 API 请求的自定义 402 响应体回调。V2 的PaymentRequirements结构可在 go/types/v2.go#L23-L32 查看由scheme / network / asset / amount / payTo / maxTimeoutSeconds / extra构成。3.2 路由模式匹配路由键Route key支持三类模式解析逻辑见 parseRoutePattern 实现routes : x402http.RoutesConfig{ GET /exact-match: {...}, // 精确路径匹配 GET /users/*: {...}, // 通配符后缀* 转为 .*? *: {...}, // 匹配所有路由 }此外路由键还支持参数占位[param]Next.js 风格与:paramExpress 风格都会被编译为[^/]正则片段。路径匹配前会经过normalizePathserver.go#L1120-L1144去掉 query/fragment、URL 解码、\转/、合并多斜杠、去掉尾部斜杠。注意路由键省略动词如/api/*时 verb 默认为*可匹配任意 HTTP 方法。3.3 资源服务器核心x402.X402ResourceServerX402ResourceServer是支付验证与要求的核心管理器实现见 go/server.go#L62-L84其职责包括维护network → scheme → SchemeNetworkServer注册表、按网络/方案分发 facilitator 客户端、缓存 facilitator 能力SupportedCache默认 TTL 5 分钟以及执行六类生命周期钩子。构造与使用server : x402.Newx402ResourceServer( x402.WithFacilitatorClient(facilitator), x402.WithSchemeServer(network, schemeServer), ) // 为资源构建支付要求 requirements, _ : server.BuildPaymentRequirements(ctx, config) // 验证支付 verifyResult, _ : server.VerifyPayment(ctx, payload, requirements) // 结算支付 settleResult, _ : server.SettlePayment(ctx, payload, requirements)一个值得关注的实现细节WithFacilitatorClient只做临时登记真正按network/scheme建立索引发生在Initialize——它会调用 facilitator 的/supported端点把返回的 kinds含x402Version映射进facilitatorClients映射表server.go#L176-L208。这意味着先 Initialize、后处理请求是正确工作的前提中间件的SyncFacilitatorOnStart选项正是为此设计。3.4 HTTP 集成层x402http.Newx402HTTPResourceServer在核心服务器之上叠加请求/响应处理httpServer : x402http.Newx402HTTPResourceServer( routes, x402.WithFacilitatorClient(facilitator), x402.WithSchemeServer(network, schemeServer), ) // 处理 HTTP 请求 result : httpServer.ProcessHTTPRequest(ctx, reqCtx, nil) // 携带传输上下文处理结算 settleResult : httpServer.ProcessSettlement(ctx, payload, requirements, nil, x402http.HTTPTransportContext{ Request: reqCtx, ResponseBody: responseBody, ResponseHeaders: responseHeaders, })HTTP 层还提供了框架无关的适配器抽象HTTPAdapterserver.go#L32-L41只需实现GetHeader / GetMethod / GetPath / GetURL / GetAcceptHeader / GetUserAgent六个方法即可把支付能力嫁接到任意 Web 框架。仓库中GinAdaptergin/middleware.go#L27-L73就是标准范例Echo 与 net/http 的适配器分别见 go/http/echo 与 go/http/nethttp。另外Initialize在填充 facilitator 映射后还会执行validateRouteConfigurationserver.go#L317-L365对每条路由做两类校验方案是否已注册missing_scheme与facilitator 是否支持该网络/方案组合missing_facilitator任何不匹配都会以聚合的RouteConfigurationError在启动阶段暴露避免把错误留到线上。3.5 Facilitator 客户端服务器通过 facilitator 客户端完成验证与结算facilitator : x402http.NewHTTPFacilitatorClient(x402http.FacilitatorConfig{ URL: https://x402.org/facilitator, }) // 验证支付由中间件调用 verifyResp, err : facilitator.Verify(ctx, payloadBytes, requirementsBytes) // 结算支付由中间件调用 settleResp, err : facilitator.Settle(ctx, payloadBytes, requirementsBytes)对照 facilitator_client.goFacilitatorConfig还支持HTTPClient自定义 HTTP 客户端、AuthProvider为 verify/settle/supported 各端点注入鉴权头、Timeout默认 30 秒、Identifier缺省为 URL。客户端请求{url}/verify、{url}/settle、{url}/supported三个端点其中GetSupported对 429 限流做最多 3 次指数退避重试facilitator_client.go#L289-L352。四、中间件Gin 一键接入与自定义实现4.1 Gin 中间件import ginmw github.com/x402-foundation/x402/go/http/gin r.Use(ginmw.X402Payment(ginmw.Config{ Routes: routes, Facilitator: facilitator, Schemes: schemes, Timeout: 30 * time.Second, }))ginmw.Config的完整字段builder.go#L13-L44与说明如下字段说明Routes每个路由的支付要求Facilitator单个 facilitator 客户端与Facilitators二选一Facilitatorsfacilitator 客户端数组用于冗余/容灾与Facilitator二选一Schemes要注册的方案服务器[]ginmw.SchemeConfig含Network与ServerPaywallConfig浏览器支付墙 UI 配置可选SyncFacilitatorOnStart启动时查询 facilitator 能力默认在配置了 facilitator 时为 trueTimeout支付操作的 context 超时默认 30 秒ErrorHandler自定义错误处理SettlementHandler结算成功后回调X402Payment内部会归一化 facilitator 列表、把SchemeConfig转为WithScheme选项并委托给PaymentMiddlewareFromConfig复用全部逻辑builder.go#L94-L129。对于只想快速保护全站的最简场景还有SimpleX402Payment(payTo, price, network, facilitatorURL)一行接入的便捷函数builder.go#L154-L179。4.2 自定义中间件不使用 Gin 时可以直接基于 HTTP server 实现自己的中间件func customPaymentMiddleware(server *x402http.HTTPServer) gin.HandlerFunc { return func(c *gin.Context) { adapter : NewGinAdapter(c) reqCtx : x402http.HTTPRequestContext{ Adapter: adapter, Path: c.Request.URL.Path, Method: c.Request.Method, } result : server.ProcessHTTPRequest(ctx, reqCtx, nil) switch result.Type { case x402http.ResultNoPaymentRequired: c.Next() case x402http.ResultPaymentError: // 返回 402 及支付要求 case x402http.ResultPaymentVerified: // 继续执行并结算 } } }三种结果类型常量定义于 server.go#L185-L190ResultNoPaymentRequired无需支付、ResultPaymentVerified支付已验证、ResultPaymentError支付错误/未支付。完整实现可参考 examples/go/servers/custom/ 与 examples/go/servers/nethttp/原生 net/http 接入更多中间件变体见 go/http/echo/builder.go 与 go/http/nethttp/builder.go。五、高级特性动态定价、动态收款与自定义资产5.1 动态定价Dynamic Pricing按请求上下文收取不同金额例如按用户等级定价routes : x402http.RoutesConfig{ GET /data: { Accepts: x402http.PaymentOptions{ { Scheme: exact, PayTo: 0x..., Network: eip155:84532, Price: x402http.DynamicPriceFunc(func(ctx context.Context, reqCtx x402http.HTTPRequestContext) (x402.Price, error) { tier : extractTierFromRequest(reqCtx) if tier premium { return $0.005, nil } return $0.001, nil }), }, }, }, }DynamicPriceFunc与DynamicPayToFunc的类型定义见 server.go#L55-L59它们在BuildPaymentRequirementsFromOptions中被逐一解析若Price是函数则调用求值否则作为静态值使用server.go#L399-L411。5.2 动态收款地址Dynamic PayTo把支付路由到不同地址典型场景是市场/平台向不同卖家分成routes : x402http.RoutesConfig{ GET /marketplace/item/*: { Accepts: x402http.PaymentOptions{ { Scheme: exact, Price: $10.00, Network: eip155:84532, PayTo: x402http.DynamicPayToFunc(func(ctx context.Context, reqCtx x402http.HTTPRequestContext) (string, error) { sellerID : extractSellerFromPath(reqCtx.Path) return getSellerAddress(sellerID) }), }, }, }, }5.3 自定义货币解析器Custom Money Parser默认价格解析为 USDC可注册自定义解析器切换代币例如大额用 DAIevmScheme : evm.NewExactEvmScheme().RegisterMoneyParser( func(amount float64, network x402.Network) (*x402.AssetAmount, error) { // 大额使用 DAI if amount 100 { return x402.AssetAmount{ Amount: fmt.Sprintf(%.0f, amount*1e18), Asset: 0x50c5725949A6F0c72E6C4a641F24049A917DB0Cb, // DAI Extra: map[string]interface{}{token: DAI}, }, nil } return nil, nil // 小额使用默认 USDC }, )5.4 生命周期钩子Lifecycle Hooks在支付处理的关键节点插入自定义逻辑server : x402.Newx402ResourceServer( x402.WithFacilitatorClient(facilitator), x402.WithSchemeServer(network, schemeServer), ) server.OnBeforeVerify(func(ctx x402.VerifyContext) (*x402.BeforeHookResult, error) { log.Printf(Verifying payment for %s, ctx.Requirements.Network) return nil, nil }) server.OnAfterSettle(func(ctx x402.SettleResultContext) error { log.Printf(Payment settled: %s, ctx.Result.Transaction) return nil })六个钩子均支持链式调用且线程安全见 server.go#L257-L301 的注册实现。钩子执行语义有明确区分verify 钩子返回错误或Abort: true会终止请求settle 钩子同样可中止结算如黑名单校验而after 类钩子的错误仅记录、不影响主流程_ hook(resultCtx)见 server.go#L449-L453。失败类钩子OnVerifyFailure/OnSettleFailure返回Recovered: true时可接管失败结果实现降级恢复。5.5 扩展Extensions可为路由附加协议扩展例如 Bazaar 资源发现import ( github.com/x402-foundation/x402/go/extensions/bazaar github.com/x402-foundation/x402/go/extensions/types ) discoveryExt, _ : bazaar.DeclareDiscoveryExtension( bazaar.MethodGET, map[string]interface{}{city: San Francisco}, types.InputConfig{...}, , types.OutputConfig{...}, ) routes : x402http.RoutesConfig{ GET /weather: { Accepts: x402http.PaymentOptions{ {Scheme: exact, PayTo: 0x..., Price: $0.001, Network: eip155:84532}, }, Extensions: map[string]interface{}{ types.BAZAAR: discoveryExt, }, }, }注意 Gin 中间件默认注册了bazaar.BazaarResourceServerExtension见 gin/middleware.go#L187请求时扩展声明会通过EnrichExtensions用传输上下文请求路径、方法等补充元数据后写入 402 响应server.go#L547-L565。完整扩展实现可参考 go/extensions/bazaar/ 与 examples/go/servers/bazaar/。六、API 参考6.1 x402.X402ResourceServer// 构造 func Newx402ResourceServer(opts ...ResourceServerOption) *X402ResourceServer // 选项 func WithFacilitatorClient(client FacilitatorClient) ResourceServerOption func WithSchemeServer(network Network, server SchemeNetworkServer) ResourceServerOption // 钩子方法均返回自身可链式调用 func (s *X402ResourceServer) OnBeforeVerify(hook BeforeVerifyHook) *X402ResourceServer func (s *X402ResourceServer) OnAfterVerify(hook AfterVerifyHook) *X402ResourceServer func (s *X402ResourceServer) OnVerifyFailure(hook OnVerifyFailureHook) *X402ResourceServer func (s *X402ResourceServer) OnBeforeSettle(hook BeforeSettleHook) *X402ResourceServer func (s *X402ResourceServer) OnAfterSettle(hook AfterSettleHook) *X402ResourceServer func (s *X402ResourceServer) OnSettleFailure(hook OnSettleFailureHook) *X402ResourceServer // 支付方法 func (s *X402ResourceServer) BuildPaymentRequirements(ctx context.Context, config ResourceConfig) ([]PaymentRequirements, error) func (s *X402ResourceServer) VerifyPayment(ctx context.Context, payload PaymentPayload, requirements PaymentRequirements) (VerifyResponse, error) func (s *X402ResourceServer) SettlePayment(ctx context.Context, payload PaymentPayload, requirements PaymentRequirements) (SettleResponse, error)6.2 x402http.RoutesConfig 与支付选项type RoutesConfig map[string]RouteConfig type RouteConfig struct { Accepts []PaymentOption // 该路由的支付选项 Description string // 资源描述 MimeType string // 响应内容类型 Extensions map[string]interface{} // 协议扩展 } type PaymentOption struct { Scheme string // exact 等 PayTo interface{} // string 或 DynamicPayToFunc Price interface{} // x402.Price 或 DynamicPriceFunc Network x402.Network // eip155:84532 等CAIP-2 MaxTimeoutSeconds int // 支付超时秒 Extra map[string]interface{} }6.3 ginmw.Configtype Config struct { Routes RoutesConfig Facilitator FacilitatorClient Facilitators []FacilitatorClient Schemes []SchemeConfig PaywallConfig *x402http.PaywallConfig SyncFacilitatorOnStart bool Timeout time.Duration ErrorHandler func(*gin.Context, error) SettlementHandler func(*gin.Context, *x402.SettleResponse) }七、错误处理与结算回调7.1 自定义错误处理器r.Use(ginmw.X402Payment(ginmw.Config{ // ... 其他配置 ... ErrorHandler: func(c *gin.Context, err error) { log.Printf(Payment error: %v, err) c.JSON(http.StatusPaymentRequired, gin.H{ error: Payment failed, details: err.Error(), }) }, }))错误处理器不仅接收验证失败也接收结算失败此时错误信息为settlement failed: 原因见 middleware.go#L395-L414因此它是统一兜底入口。未配置ErrorHandler时结算失败会走内置的 402 响应带PAYMENT-RESPONSE头。7.2 结算处理器r.Use(ginmw.X402Payment(ginmw.Config{ // ... 其他配置 ... SettlementHandler: func(c *gin.Context, resp x402.SettleResponse) { log.Printf(Payment settled: tx%s, payer%s, resp.Transaction, resp.Payer) // 入库、上报指标等 db.RecordPayment(resp.Transaction, resp.Payer) }, }))SettleResponse的关键字段包括Success、Transaction交易哈希、Network、Payer、ErrorReason。结算成功时中间件还会在响应头附加PAYMENT-RESPONSEBase64 编码的结算凭证客户端可据此对账。八、最佳实践8.1 启动时同步 facilitator 能力r.Use(ginmw.X402Payment(ginmw.Config{ SyncFacilitatorOnStart: true, // 启动时查询 /supported // ... }))该选项让服务器启动时即拉取 facilitator 支持的方案/网络并校验路由配置尽早暴露配置错误。注意未配置任何 facilitator 且未显式开启时同步默认关闭builder.go#L82-L92。8.2 设置合理超时r.Use(ginmw.X402Payment(ginmw.Config{ Timeout: 30 * time.Second, // 支付操作超时 // ... }))Timeout同时作用于启动同步与每请求的支付处理 context见 middleware.go#L301-L305默认 30 秒。8.3 使用描述性路由routes : x402http.RoutesConfig{ GET /api/weather: { Accepts: x402http.PaymentOptions{ {Scheme: exact, PayTo: 0x..., Price: $0.001, Network: eip155:84532}, }, Description: Get current weather data for a city, MimeType: application/json, }, }Description与MimeType会写入 402 响应的resource信息ResourceInfo{URL, Description, MimeType}见 go/types/v2.go#L52-L57帮助客户端理解资源并选择是否支付。8.4 同时处理成功与失败r.Use(ginmw.X402Payment(ginmw.Config{ ErrorHandler: func(c *gin.Context, err error) { // 记录并告警 }, SettlementHandler: func(c *gin.Context, resp x402.SettleResponse) { // 记录成功支付 }, // ... }))8.5 只保护特定路由routes : x402http.RoutesConfig{ // 受保护 GET /api/premium: {Accepts: x402http.PaymentOptions{{Price: $1.00, ...}}}, POST /api/compute: {Accepts: x402http.PaymentOptions{{Price: $5.00, ...}}}, // /health、/docs 等保持不保护 }未在RoutesConfig中声明的路由会命中ResultNoPaymentRequired直接放行因此路由表之外的端点天然免付费。九、进阶模式9.1 多网络支持r.Use(ginmw.X402Payment(ginmw.Config{ Routes: routes, Facilitator: facilitator, Schemes: []ginmw.SchemeConfig{ {Network: eip155:84532, Server: evm.NewExactEvmScheme()}, {Network: eip155:8453, Server: evm.NewExactEvmScheme()}, {Network: solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1, Server: svm.NewExactSvmScheme()}, }, }))EVM 与 SVM 的 exact 方案服务器分别位于 go/mechanisms/evm/exact/server 与 go/mechanisms/svm/exact。同一路由可在Accepts中声明多条不同网络的PaymentOption如 gin 示例中的双网络天气接口客户端任选其一支付。9.2 按路由差异化定价routes : x402http.RoutesConfig{ GET /api/basic: {Accepts: x402http.PaymentOptions{{Price: $0.001, ...}}}, // 便宜 GET /api/premium: {Accepts: x402http.PaymentOptions{{Price: $0.10, ...}}}, // 中等 POST /api/compute: {Accepts: x402http.PaymentOptions{{Price: $1.00, ...}}}, // 昂贵 }9.3 分层定价Tiered Pricingroutes : x402http.RoutesConfig{ GET /api/data: { Accepts: x402http.PaymentOptions{ { Scheme: exact, PayTo: 0x..., Network: eip155:84532, Price: x402http.DynamicPriceFunc(func(ctx context.Context, reqCtx x402http.HTTPRequestContext) (x402.Price, error) { tier : getUserTier(reqCtx) switch tier { case free: return $0.10, nil case premium: return $0.01, nil case enterprise: return $0.001, nil default: return $0.10, nil } }), }, }, }, }9.4 市场支付路由Marketplace Payment Routingroutes : x402http.RoutesConfig{ GET /marketplace/item/*: { Accepts: x402http.PaymentOptions{ { Scheme: exact, Price: $10.00, Network: eip155:84532, PayTo: x402http.DynamicPayToFunc(func(ctx context.Context, reqCtx x402http.HTTPRequestContext) (string, error) { itemID : extractItemID(reqCtx.Path) seller, err : db.GetItemSeller(itemID) if err ! nil { return , err } return seller.WalletAddress, nil }), }, }, }, }十、生命周期钩子实战用例10.1 数据库日志server.OnAfterSettle(func(ctx SettleResultContext) error { return db.InsertPayment(Payment{ Transaction: ctx.Result.Transaction, Payer: ctx.Result.Payer, Network: ctx.Result.Network, Amount: ctx.Requirements.Amount, Timestamp: time.Now(), }) })10.2 指标上报server.OnAfterVerify(func(ctx VerifyResultContext) error { metrics.IncrementCounter(payments.verified) return nil })10.3 访问控制黑名单server.OnBeforeSettle(func(ctx SettleContext) (*BeforeHookResult, error) { if isBlacklisted(ctx.Payload.Payer) { return BeforeHookResult{ Abort: true, Reason: Payer not allowed, }, nil } return nil, nil })十一、测试11.1 测试受保护端点func TestProtectedEndpoint(t *testing.T) { // 创建测试服务器 r : gin.Default() // 添加 mock 中间件 r.Use(mockPaymentMiddleware()) r.GET(/protected, handler) // 携带有效支付测试 req : httptest.NewRequest(GET, /protected, nil) req.Header.Set(PAYMENT-SIGNATURE, validPayment) w : httptest.NewRecorder() r.ServeHTTP(w, req) if w.Code ! 200 { t.Errorf(Expected 200, got %d, w.Code) } }11.2 集成测试仓库在 go/test/integration/ 提供了面向真实 facilitator 的集成测试含 core_test.go、http_test.go、evm_test.go 等单元测试集中在 go/test/unit/其中 http_test.go 覆盖了 HTTP 中间件与支付流程的核心逻辑可作为编写自身测试的参考。Go HTTP 客户端/服务端的 mock 资金测试见 go/test/mocks/cash/。十二、部署注意事项12.1 生产检查清单使用生产环境 facilitator URL设置合理超时建议 30 秒实现错误处理器与结算处理器监控 facilitator 健康状态对端点限流记录支付事件日志为支付失败设置告警生产环境启用 HTTPS12.2 Facilitator 选择测试网facilitator : x402http.NewHTTPFacilitatorClient(x402http.FacilitatorConfig{ URL: https://x402.org/facilitator, // 测试网 })主网facilitator : x402http.NewHTTPFacilitatorClient(x402http.FacilitatorConfig{ URL: https://facilitator.coinbase.com, // 生产 })自托管facilitator : x402http.NewHTTPFacilitatorClient(x402http.FacilitatorConfig{ URL: https://your-facilitator.example.com, })上述 URL 均为官方文档中的示例值实际部署时应以你接入的 facilitator 服务商提供的地址为准。注意NewHTTPFacilitatorClient在URL为空时会回退到内置默认值https://x402.org/facilitatorfacilitator_client.go#L62-L63显式配置永远更稳妥。facilitator 端的构建方式见 go/FACILITATOR.md。十三、完整示例索引仓库 examples/go/servers/ 下提供了可直接运行的服务器示例gin基础集成双网络EVMSVM天气接口custom自定义中间件接入advanced动态定价、钩子、扩展的综合示例echoEcho 框架接入nethttp标准库 net/http 接入bazaarBazaar 扩展示例payment-identifier支付标识扩展示例uptoupto上不封顶方案示例十四、V1 迁移到 V214.1 路由配置变化V1routes : x402gin.Routes{ GET /data: { Network: base-sepolia, // ... }, }V2routes : x402http.RoutesConfig{ GET /data: { Network: eip155:84532, // CAIP-2 格式 // ... }, }14.2 导入路径变化V1import github.com/x402-foundation/x402/go/middleware/ginV2import ginmw github.com/x402-foundation/x402/go/http/ginV2 服务器只接受 V2 支付extractPaymentV2会对非 V2 载荷直接报错见 server.go#L795-L798版本检测逻辑见 go/mechanisms/evm 下的工具函数。十五、相关文档导航go/README.mdGo 包总览go/CLIENT.md构建客户端go/FACILITATOR.md构建 facilitatorgo/mechanisms/支付方案实现EVM/SVM 的 exact/uptogo/extensions/协议扩展examples/go/servers/可运行服务器示例【免费下载链接】x402A payments protocol for the internet. Built on HTTP.项目地址: https://gitcode.com/GitHub_Trending/x4/x402创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考