http
import "github.com/x402-foundation/x402/go/v2/http"
THIS FILE IS AUTO-GENERATED - DO NOT EDIT
THIS FILE IS AUTO-GENERATED - DO NOT EDIT
Package http provides HTTP-specific implementations of x402 components. This includes HTTP-aware clients, services, and facilitator clients.
THIS FILE IS AUTO-GENERATED - DO NOT EDIT
Constants
Result type constants
const (
ResultNoPaymentRequired = "no-payment-required"
ResultPaymentVerified = "payment-verified"
ResultPaymentError = "payment-error"
)AVMPaywallTemplate is the pre-built AVM paywall template with inlined CSS and JS
Source: http/avm_paywall_template.go:5
const AVMPaywallTemplate = "[embedded paywall template literal omitted from generated docs; follow the source link for the complete value]"DefaultFacilitatorURL is the default public facilitator
Source: http/facilitator_client.go:65
const DefaultFacilitatorURL = "https://x402.org/facilitator"EVMPaywallTemplate is the pre-built EVM paywall template with inlined CSS and JS
Source: http/evm_paywall_template.go:5
const EVMPaywallTemplate = "[embedded paywall template literal omitted from generated docs; follow the source link for the complete value]"PaymentRequiredCacheControl is the Cache-Control directive for 402/412 responses carrying PAYMENT-REQUIRED or 402 settlement-failure PAYMENT-RESPONSE.
const PaymentRequiredCacheControl = "no-store"SVMPaywallTemplate is the pre-built SVM paywall template with inlined CSS and JS
Source: http/svm_paywall_template.go:5
const SVMPaywallTemplate = "[embedded paywall template literal omitted from generated docs; follow the source link for the complete value]"SettlementOverridesHeader is the HTTP header name for settlement overrides. The value is the canonical HTTP header form (Title-Case) so it works correctly with both http.Header methods and direct map access.
const SettlementOverridesHeader = "Settlement-Overrides"Functions
func DefaultPaywallProvider() PaywallProvider
DefaultPaywallProvider creates a PaywallProvider with built-in EVM and SVM handlers.
func Do(ctx context.Context, req *http.Request, x402Client *x402HTTPClient) (*http.Response, error)
Do performs an HTTP request with automatic payment handling
func Get(ctx context.Context, url string, x402Client *x402HTTPClient) (*http.Response, error)
Get performs a GET request with automatic payment handling
func MarshalSettlementOverrides(overrides *x402.SettlementOverrides) string
MarshalSettlementOverrides serializes overrides to the JSON string suitable for the SettlementOverridesHeader value. Returns an empty string on marshal failure (which cannot happen for a well-formed SettlementOverrides value).
func NewClient(client *x402.X402Client) *x402HTTPClient
NewClient creates a new HTTP-aware x402 client
func NewFacilitatorClient(config *FacilitatorConfig) *HTTPFacilitatorClient
NewFacilitatorClient creates a new HTTP facilitator client
func NewHTTPFacilitatorClient(config *FacilitatorConfig) *HTTPFacilitatorClient
Source: http/facilitator_client.go:258
NewHTTPFacilitatorClient creates a new HTTP facilitator client
func NewPaywallBuilder() *PaywallBuilder
NewPaywallBuilder creates a new PaywallBuilder.
func NewServer(routes RoutesConfig, opts ...x402.ResourceServerOption) *x402HTTPResourceServer
NewServer creates a new HTTP resource server
func Newx402HTTPClient(client *x402.X402Client) *x402HTTPClient
Newx402HTTPClient creates a new HTTP-aware x402 client
func Newx402HTTPResourceServer(routes RoutesConfig, opts ...x402.ResourceServerOption) *x402HTTPResourceServer
Newx402HTTPResourceServer creates a new HTTP resource server
func Post(ctx context.Context, url string, body io.Reader, x402Client *x402HTTPClient) (*http.Response, error)
Post performs a POST request with automatic payment handling
func WithPrivateCacheControl(value string) string
WithPrivateCacheControl appends the private directive for 200 responses with PAYMENT-RESPONSE without clobbering existing handler Cache-Control values.
func WrapClient(client *http.Client, x402Client *x402HTTPClient) *http.Client
WrapClient wraps a standard HTTP client with x402 payment handling
func WrapHTTPClientWithPayment(client *http.Client, x402Client *x402HTTPClient) *http.Client
WrapHTTPClientWithPayment returns a new *http.Client whose Transport is wrapped with x402 payment handling. The input client is NEVER mutated - its Transport, Timeout, Jar and CheckRedirect are copied into a fresh *http.Client. Passing http.DefaultClient is safe; the returned client is independent and the global default remains untouched.
func Wrappedx402HTTPResourceServer(routes RoutesConfig, resourceServer *x402.X402ResourceServer) *x402HTTPResourceServer
Wrappedx402HTTPResourceServer wraps an existing resource server with HTTP functionality.
Types
type AuthHeaders
Source: http/facilitator_client.go:39
AuthHeaders contains authentication headers for facilitator endpoints
type AuthHeaders struct {
Verify map[string]string
Settle map[string]string
Supported map[string]string
Bazaar map[string]string
}Fields
Verify map[string]stringSettle map[string]stringSupported map[string]stringBazaar map[string]string
type AuthProvider
Source: http/facilitator_client.go:33
AuthProvider generates authentication headers for facilitator requests
type AuthProvider interface {
// GetAuthHeaders returns authentication headers for each endpoint
GetAuthHeaders(ctx context.Context) (AuthHeaders, error)
}Methods
GetAuthHeaders func(ctx context.Context) (AuthHeaders, error)GetAuthHeaders returns authentication headers for each endpoint
type ClientExtensionPaymentRequiredHookProvider
ClientExtensionPaymentRequiredHookProvider lets registered client extensions expose HTTP auth-style retry hooks.
type ClientExtensionPaymentRequiredHookProvider interface {
PaymentRequiredHook() PaymentRequiredHook
}Methods
PaymentRequiredHook func() PaymentRequiredHook
type CompiledRoute
CompiledRoute is a parsed route ready for matching
type CompiledRoute struct {
Verb string
Regex *regexp.Regexp
Config RouteConfig
Pattern string
}Fields
Verb stringRegex *regexp.RegexpConfig RouteConfigPattern string
type DynamicPayToFunc
DynamicPayToFunc is a function that resolves payTo address dynamically based on request context
type DynamicPayToFunc func(context.Context, HTTPRequestContext) (string, error)type DynamicPriceFunc
DynamicPriceFunc is a function that resolves price dynamically based on request context
type DynamicPriceFunc func(context.Context, HTTPRequestContext) (x402.Price, error)type EVMPaywallHandler
EVMPaywallHandler generates paywall HTML for EVM-compatible networks (eip155:*).
type EVMPaywallHandler struct{}func GenerateHTML(_ types.PaymentRequirements, paymentRequired types.PaymentRequired, config *PaywallConfig) string
GenerateHTML generates paywall HTML using the built-in EVM template.
func Supports(requirement types.PaymentRequirements) bool
Supports returns true for EVM networks (eip155:* CAIP-2 identifiers).
type FacilitatorConfig
Source: http/facilitator_client.go:47
FacilitatorConfig configures the HTTP facilitator client
type FacilitatorConfig struct {
// URL is the base URL of the facilitator service
URL string
// HTTPClient is the HTTP client to use (optional)
HTTPClient *http.Client
// AuthProvider provides authentication headers (optional)
AuthProvider AuthProvider
// Timeout for requests (optional, defaults to 30s)
Timeout time.Duration
// Identifier for this facilitator (optional)
Identifier string
}Fields
URL stringURL is the base URL of the facilitator service
HTTPClient *http.ClientHTTPClient is the HTTP client to use (optional)
AuthProvider AuthProviderAuthProvider provides authentication headers (optional)
Timeout time.DurationTimeout for requests (optional, defaults to 30s)
Identifier stringIdentifier for this facilitator (optional)
type FacilitatorResponseError
Source: http/facilitator_client.go:74
FacilitatorResponseError indicates a facilitator returned malformed success payload data.
type FacilitatorResponseError struct {
// contains filtered or unexported fields
}func Error) Error() string
func Unwrap() error
type HTTPAdapter
HTTPAdapter provides framework-agnostic HTTP operations Implement this for each web framework (Gin, Echo, net/http, etc.)
type HTTPAdapter interface {
GetHeader(name string) string
GetMethod() string
GetPath() string
GetURL() string
GetAcceptHeader() string
GetUserAgent() string
}Methods
GetHeader func(name string) stringGetMethod func() stringGetPath func() stringGetURL func() stringGetAcceptHeader func() stringGetUserAgent func() string
type HTTPClient
HTTPClient is an alias for x402HTTPClient
type HTTPClient = x402HTTPClienttype HTTPFacilitatorClient
Source: http/facilitator_client.go:25
HTTPFacilitatorClient communicates with remote facilitator services over HTTP Implements FacilitatorClient interface (supports both V1 and V2)
type HTTPFacilitatorClient struct {
// contains filtered or unexported fields
}func GetAuthProvider() AuthProvider
Source: http/facilitator_client.go:303
GetAuthProvider returns the authentication provider, or nil if not configured.
func GetSupported(ctx context.Context) (x402.SupportedResponse, error)
Source: http/facilitator_client.go:335
GetSupported gets supported payment kinds (shared by both V1 and V2). Retries up to 3 times with exponential backoff on 429 rate limit errors.
func HTTPClient() *http.Client
Source: http/facilitator_client.go:298
HTTPClient returns the underlying HTTP client.
func Settle(ctx context.Context, payloadBytes []byte, requirementsBytes []byte) (*x402.SettleResponse, error)
Source: http/facilitator_client.go:323
Settle executes a payment (supports both V1 and V2)
func URL() string
Source: http/facilitator_client.go:293
URL returns the base URL of the facilitator service.
func Verify(ctx context.Context, payloadBytes []byte, requirementsBytes []byte) (*x402.VerifyResponse, error)
Source: http/facilitator_client.go:312
Verify checks if a payment is valid (supports both V1 and V2)
type HTTPProcessResult
HTTPProcessResult indicates the result of processing a payment request
type HTTPProcessResult struct {
Type string
Response *HTTPResponseInstructions
PaymentPayload *types.PaymentPayload // V2 only
PaymentRequirements *types.PaymentRequirements // V2 only
// DeclaredExtensions is the route's enriched extension declaration map.
// Carried through verify → settle so per-extension hooks gate on declared
// keys both in the verify and settle phases. Mirrors TS
// `paymentRequiredResponse.extensions` flowing into both calls.
DeclaredExtensions map[string]interface{}
// SkipHandler is set when an AfterVerifyHook signals that the resource handler
// should be bypassed and settlement performed inline.
SkipHandler *x402.SkipHandlerDirective
// CancellationDispatcher fires onVerifiedPaymentCanceled hooks if the resource
// handler errors or returns a non-2xx status before settlement runs. Set when
// Type is ResultPaymentVerified.
CancellationDispatcher *x402.PaymentCancellationDispatcher
}Fields
Type stringResponse *HTTPResponseInstructionsPaymentPayload *types.PaymentPayloadV2 only
PaymentRequirements *types.PaymentRequirementsV2 only
DeclaredExtensions map[string]interface{}DeclaredExtensions is the route's enriched extension declaration map. Carried through verify → settle so per-extension hooks gate on declared keys both in the verify and settle phases. Mirrors TS
paymentRequiredResponse.extensionsflowing into both calls.SkipHandler *x402.SkipHandlerDirectiveSkipHandler is set when an AfterVerifyHook signals that the resource handler should be bypassed and settlement performed inline.
CancellationDispatcher *x402.PaymentCancellationDispatcherCancellationDispatcher fires onVerifiedPaymentCanceled hooks if the resource handler errors or returns a non-2xx status before settlement runs. Set when Type is ResultPaymentVerified.
type HTTPRequestContext
HTTPRequestContext encapsulates an HTTP request
type HTTPRequestContext struct {
Adapter HTTPAdapter
Path string
Method string
PaymentHeader string
RoutePattern string
Requirements []types.PaymentRequirements
}Fields
Adapter HTTPAdapterPath stringMethod stringPaymentHeader stringRoutePattern stringRequirements []types.PaymentRequirements
type HTTPResponseInstructions
HTTPResponseInstructions tells the framework how to respond
type HTTPResponseInstructions struct {
Status int `json:"status"`
Headers map[string]string `json:"headers"`
Body interface{} `json:"body,omitempty"`
IsHTML bool `json:"isHtml,omitempty"`
}Fields
Status int`json:"status"`Headers map[string]string`json:"headers"`Body interface{}`json:"body,omitempty"`IsHTML bool`json:"isHtml,omitempty"`
type HTTPServer
HTTPServer is an alias for x402HTTPResourceServer
type HTTPServer = x402HTTPResourceServertype HTTPTransportContext
HTTPTransportContext carries request and response data through settlement processing. ResponseHeaders must be an http.Header - use Header.Get/Del to preserve canonicalization.
type HTTPTransportContext struct {
Request *HTTPRequestContext
ResponseBody []byte
ResponseHeaders http.Header
}Fields
Request *HTTPRequestContextResponseBody []byteResponseHeaders http.Header
type PaymentOption
PaymentOption represents a single payment option for a route Represents one way a client can pay for access to the resource
type PaymentOption struct {
Scheme string `json:"scheme"`
PayTo interface{} `json:"payTo"` // string or DynamicPayToFunc
Price interface{} `json:"price"` // x402.Price or DynamicPriceFunc
Network x402.Network `json:"network"`
MaxTimeoutSeconds int `json:"maxTimeoutSeconds,omitempty"`
Extra map[string]interface{} `json:"extra,omitempty"`
}Fields
Scheme string`json:"scheme"`PayTo interface{}`json:"payTo"`string or DynamicPayToFunc
Price interface{}`json:"price"`x402.Price or DynamicPriceFunc
Network x402.Network`json:"network"`MaxTimeoutSeconds int`json:"maxTimeoutSeconds,omitempty"`Extra map[string]interface{}`json:"extra,omitempty"`
type PaymentOptions
PaymentOptions is a slice of PaymentOption for convenience
type PaymentOptions = []PaymentOptiontype PaymentRequiredHook
PaymentRequiredHook can respond to a 402 PaymentRequired before payment payload creation.
type PaymentRequiredHook func(ctx context.Context, paymentRequired types.PaymentRequired) (*PaymentRequiredHookResult, error)type PaymentRequiredHookResult
PaymentRequiredHookResult contains headers for an auth-style retry.
type PaymentRequiredHookResult struct {
Headers map[string]string
}Fields
Headers map[string]string
type PaymentRoundTripper
PaymentRoundTripper implements http.RoundTripper with x402 payment handling
type PaymentRoundTripper struct {
Transport http.RoundTripper
// contains filtered or unexported fields
}Fields
Transport http.RoundTripper
func RoundTripper) RoundTrip(req *http.Request) (*http.Response, error)
RoundTrip implements http.RoundTripper with V1/V2 version detection.
V2 flow includes scheme-aware reconciliation: after the payment retry the chosen scheme's PaymentResponseHandler (if implemented) and any user-registered OnPaymentResponse hooks fire automatically. On a corrective 402 + Recovered=true, the transport rebuilds a fresh payload and retries one more time, mirroring the TS @x402/fetch wrapper's recovery behavior. User code never has to call ProcessSettleResponse manually.
type PaywallBuilder
PaywallBuilder composes multiple PaywallNetworkHandlers into a single PaywallProvider. Use NewPaywallBuilder to create a builder, add network handlers, and call Build.
type PaywallBuilder struct {
// contains filtered or unexported fields
}func Builder) Build() PaywallProvider
Build creates a PaywallProvider that dispatches to the first matching network handler.
func WithConfig(config *PaywallConfig) *PaywallBuilder
WithConfig sets default paywall configuration for the builder.
func WithNetwork(handler PaywallNetworkHandler) *PaywallBuilder
WithNetwork adds a network handler to the builder.
type PaywallConfig
PaywallConfig configures the HTML paywall for browser requests.
FaucetURLs is a per-chain override map keyed by CAIP-2 identifier (e.g. "eip155:84532"). When set, the entry for the rendered chain wins over the paywall's curated default. Unmapped chains render "No faucet configured." rather than a fallback link.
type PaywallConfig struct {
AppName string `json:"appName,omitempty"`
AppLogo string `json:"appLogo,omitempty"`
CurrentURL string `json:"currentUrl,omitempty"`
Testnet bool `json:"testnet,omitempty"`
// FaucetURLs is a per-chain override keyed by CAIP-2 identifier.
FaucetURLs map[string]string `json:"faucetUrls,omitempty"`
}Fields
AppName string`json:"appName,omitempty"`AppLogo string`json:"appLogo,omitempty"`CurrentURL string`json:"currentUrl,omitempty"`Testnet bool`json:"testnet,omitempty"`FaucetURLs map[string]string`json:"faucetUrls,omitempty"`FaucetURLs is a per-chain override keyed by CAIP-2 identifier.
type PaywallNetworkHandler
PaywallNetworkHandler handles paywall HTML generation for a specific network family. Used with PaywallBuilder to compose network-specific handlers into a single PaywallProvider.
type PaywallNetworkHandler interface {
// Supports returns true if this handler can generate HTML for the given payment requirement.
Supports(requirement types.PaymentRequirements) bool
// GenerateHTML generates the paywall HTML for the given requirement.
GenerateHTML(requirement types.PaymentRequirements, paymentRequired types.PaymentRequired, config *PaywallConfig) string
}Methods
Supports func(requirement types.PaymentRequirements) boolSupports returns true if this handler can generate HTML for the given payment requirement.
GenerateHTML func(requirement types.PaymentRequirements, paymentRequired types.PaymentRequired, config *PaywallConfig) stringGenerateHTML generates the paywall HTML for the given requirement.
type PaywallProvider
PaywallProvider generates HTML for browser-facing 402 responses. Register a custom implementation via RegisterPaywallProvider to override the built-in EVM/SVM templates.
type PaywallProvider interface {
GenerateHTML(paymentRequired types.PaymentRequired, config *PaywallConfig) string
}Methods
GenerateHTML func(paymentRequired types.PaymentRequired, config *PaywallConfig) string
type ProcessSettleResult
ProcessSettleResult represents the result of settlement processing
type ProcessSettleResult struct {
Success bool
Headers map[string]string
ErrorReason string
Transaction string
Network x402.Network
Payer string
// Response contains HTTP instructions for the failure case (status 402, body, etc).
// Set when Success is false; nil when Success is true.
Response *HTTPResponseInstructions
}Fields
Success boolHeaders map[string]stringErrorReason stringTransaction stringNetwork x402.NetworkPayer stringResponse *HTTPResponseInstructionsResponse contains HTTP instructions for the failure case (status 402, body, etc). Set when Success is false; nil when Success is true.
type ProtectedRequestHook
ProtectedRequestHook is called on every request to a protected route, before payment processing. It receives the request context and the matched route configuration. Return nil to continue to the next hook or payment flow. Return a result with GrantAccess=true to bypass payment. Return a result with Abort=true to deny the request with a 403 status.
type ProtectedRequestHook func(ctx context.Context, reqCtx HTTPRequestContext, routeConfig RouteConfig) (*ProtectedRequestHookResult, error)type ProtectedRequestHookResult
ProtectedRequestHookResult represents the result of a protected request hook. A nil result means the hook has no opinion and the next hook (or payment flow) should proceed.
type ProtectedRequestHookResult struct {
// GrantAccess bypasses payment and grants free access to the resource.
GrantAccess bool
// Abort denies the request with a 403 status and the provided Reason.
Abort bool
Reason string
}Fields
GrantAccess boolGrantAccess bypasses payment and grants free access to the resource.
Abort boolAbort denies the request with a 403 status and the provided Reason.
Reason string
type ResourceServerExtensionProtectedRequestHookProvider
ResourceServerExtensionProtectedRequestHookProvider lets resource server extensions expose HTTP protected request hooks.
type ResourceServerExtensionProtectedRequestHookProvider interface {
ProtectedRequestHook() ProtectedRequestHook
}Methods
ProtectedRequestHook func() ProtectedRequestHook
type RouteConfig
RouteConfig defines payment configuration for an HTTP endpoint
type RouteConfig struct {
// Payment options for this route
Accepts PaymentOptions `json:"accepts"`
// HTTP-specific metadata
Resource string `json:"resource,omitempty"`
Description string `json:"description,omitempty"`
MimeType string `json:"mimeType,omitempty"`
ServiceName string `json:"serviceName,omitempty"`
Tags []string `json:"tags,omitempty"`
IconUrl string `json:"iconUrl,omitempty"`
CustomPaywallHTML string `json:"customPaywallHtml,omitempty"`
Extensions map[string]interface{} `json:"extensions,omitempty"`
// UnpaidResponseBody is an optional callback to generate a custom response for unpaid API requests.
// For browser requests (Accept: text/html), the paywall HTML takes precedence.
// If not provided, defaults to { ContentType: "application/json", Body: nil }.
UnpaidResponseBody UnpaidResponseBodyFunc `json:"-"`
}Fields
Accepts PaymentOptions`json:"accepts"`Payment options for this route
Resource string`json:"resource,omitempty"`HTTP-specific metadata
Description string`json:"description,omitempty"`MimeType string`json:"mimeType,omitempty"`ServiceName string`json:"serviceName,omitempty"`Tags []string`json:"tags,omitempty"`IconUrl string`json:"iconUrl,omitempty"`CustomPaywallHTML string`json:"customPaywallHtml,omitempty"`Extensions map[string]interface{}`json:"extensions,omitempty"`UnpaidResponseBody UnpaidResponseBodyFunc`json:"-"`UnpaidResponseBody is an optional callback to generate a custom response for unpaid API requests. For browser requests (Accept: text/html), the paywall HTML takes precedence. If not provided, defaults to { ContentType: "application/json", Body: nil }.
type RouteConfigurationError
RouteConfigurationError collects all route validation errors
type RouteConfigurationError struct {
// Errors contains all validation failures
Errors []RouteValidationError
}Fields
Errors []RouteValidationErrorErrors contains all validation failures
func Error) Error() string
Error returns a formatted error message listing all validation failures
type RouteValidationError
RouteValidationError represents a single validation failure for a route's payment option
type RouteValidationError struct {
// RoutePattern is the route pattern (e.g., "GET /api/weather")
RoutePattern string
// Scheme is the payment scheme that failed validation
Scheme string
// Network is the network that failed validation
Network x402.Network
// Reason is the type of validation failure: "missing_scheme" or "missing_facilitator"
Reason string
// Message is a human-readable error message
Message string
}Fields
RoutePattern stringRoutePattern is the route pattern (e.g., "GET /api/weather")
Scheme stringScheme is the payment scheme that failed validation
Network x402.NetworkNetwork is the network that failed validation
Reason stringReason is the type of validation failure: "missing_scheme" or "missing_facilitator"
Message stringMessage is a human-readable error message
type RoutesConfig
RoutesConfig maps route patterns to configurations
type RoutesConfig map[string]RouteConfigtype SVMPaywallHandler
SVMPaywallHandler generates paywall HTML for Solana networks (solana:*).
type SVMPaywallHandler struct{}func GenerateHTML(_ types.PaymentRequirements, paymentRequired types.PaymentRequired, config *PaywallConfig) string
GenerateHTML generates paywall HTML using the built-in SVM template.
func Supports(requirement types.PaymentRequirements) bool
Supports returns true for Solana networks (solana:* CAIP-2 identifiers).
type UnpaidResponse
UnpaidResponse represents the custom response for unpaid (402) API requests. This allows servers to return preview data, error messages, or other content when a request lacks payment.
type UnpaidResponse struct {
// ContentType is the content type for the response (e.g., "application/json", "text/plain").
ContentType string
// Body is the response body to include in the 402 response.
Body interface{}
}Fields
ContentType stringContentType is the content type for the response (e.g., "application/json", "text/plain").
Body interface{}Body is the response body to include in the 402 response.
type UnpaidResponseBodyFunc
UnpaidResponseBodyFunc generates a custom response for unpaid API requests. It receives the HTTP request context and returns the content type and body for the 402 response.
For browser requests (Accept: text/html), the paywall HTML takes precedence. This callback is only used for API clients.
Args:
ctx: Context for cancellation
reqCtx: HTTP request contextReturns:
UnpaidResponse with ContentType and Body for the 402 responsetype UnpaidResponseBodyFunc func(ctx context.Context, reqCtx HTTPRequestContext) (*UnpaidResponse, error)