API Reference
Complete reference for the x402-go packages and APIs.
Facilitator Service Endpoints
GET /supported
Returns supported configurations, extensions, and signer addresses.
Response:
{
"kinds": [
{"x402Version": 2, "scheme": "exact", "network": "eip155:8453"},
{"x402Version": 2, "scheme": "exact", "network": "eip155:84532"}
],
"extensions": [],
"signers": {
"eip155:8453": ["0xYourSignerAddress"],
"eip155:84532": ["0xYourSignerAddress"]
}
}
POST /verify
Verifies a payment payload against requirements without settling.
Request:
{
"paymentPayload": {
"x402Version": 2,
"accepted": {
"scheme": "exact",
"network": "eip155:8453",
"amount": "1000000",
"payTo": "0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb",
"asset": "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"
},
"payload": {
"signature": "0x...",
"authorization": {
"from": "0x...",
"to": "0x...",
"value": "1000000",
"validAfter": 1700000000,
"validBefore": 1700003600,
"nonce": "0x..."
}
}
},
"paymentRequirements": {
"scheme": "exact",
"network": "eip155:8453",
"amount": "1000000",
"payTo": "0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb",
"asset": "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"
}
}
Response:
{
"isValid": true,
"payer": "0xPayerAddress"
}
Error Response:
{
"isValid": false,
"invalidReason": "insufficient balance"
}
POST /settle
Executes the payment on-chain via TransferWithAuthorization.
Request: Same structure as /verify.
Response:
{
"success": true,
"transaction": "0xTransactionHash",
"network": "eip155:8453",
"payer": "0xPayerAddress"
}
Error Response:
{
"success": false,
"errorReason": "gas price exceeds maximum"
}
Facilitator Client Package
github.com/vorpalengineering/x402-go/facilitator/client
NewClient
Creates a new facilitator client.
func NewClient(facilitatorURL string) *Client
Parameters:
facilitatorURL- Base URL of the facilitator service (e.g.,http://localhost:4020)
Supported
Queries supported payment schemes, networks, and signers.
func (c *Client) Supported() (*types.SupportedResponse, error)
Returns:
*types.SupportedResponse- Supported configurationserror- Any error that occurred
Verify
Verifies a payment payload against requirements.
func (c *Client) Verify(req *types.VerifyRequest) (*types.VerifyResponse, error)
Parameters:
req- Verify request containing payment payload and requirements
Returns:
*types.VerifyResponse- Verification result withIsValid,InvalidReason, andPayererror- Any error that occurred
Settle
Settles a payment on-chain.
func (c *Client) Settle(req *types.SettleRequest) (*types.SettleResponse, error)
Parameters:
req- Settle request containing payment payload and requirements
Returns:
*types.SettleResponse- Settlement result withSuccess,Transaction,Network, andPayererror- Any error that occurred
Resource Middleware Package
github.com/vorpalengineering/x402-go/resource/middleware
NewX402Middleware
Creates a new x402 middleware instance.
func NewX402Middleware(cfg *MiddlewareConfig) *X402Middleware
Parameters:
cfg- Middleware configuration
Handler
Returns the Gin handler function.
func (m *X402Middleware) Handler() gin.HandlerFunc
MiddlewareConfig
Configuration for the x402 middleware.
type MiddlewareConfig struct {
// FacilitatorURL is the base URL of the x402 facilitator service
FacilitatorURL string
// DefaultRequirements specifies default payment requirements
DefaultRequirements types.PaymentRequirements
// ProtectedPaths is a list of path patterns requiring payment
// Supports glob patterns like "/api/*" or exact paths like "/data"
ProtectedPaths []string
// RouteRequirements maps specific routes to custom payment requirements
RouteRequirements map[string]types.PaymentRequirements
// RouteResources maps specific routes to ResourceInfo metadata
RouteResources map[string]*types.ResourceInfo
// PaymentHeaderName is the HTTP header containing payment
// Defaults to "PAYMENT-SIGNATURE"
PaymentHeaderName string
// MaxBufferSize is the maximum response buffer size in bytes
// If the handler response exceeds this size, the request is aborted
// 0 means unlimited
MaxBufferSize int
// DiscoveryEnabled enables serving the /.well-known/x402 discovery endpoint
DiscoveryEnabled bool
// OwnershipProofs is a list of pre-generated EIP-191 signatures
// proving ownership of the protected resource URLs
OwnershipProofs []string
// Instructions is an optional markdown-formatted string containing
// instructions or information for users of your resources
Instructions string
// BaseURL is the public base URL of the server (e.g., "https://api.example.com")
// Used to construct full endpoint URLs in the discovery response
BaseURL string
// DiscoverableEndpoints is a list of explicit endpoint paths
// to advertise in the discovery response
DiscoverableEndpoints []string
}
Context Values
Values available in handler context after payment verification:
During Handler Execution:
verified, _ := c.Get("x402_payment_verified") // bool
paymentHeader, _ := c.Get("x402_payment_header") // string
requirements, _ := c.Get("x402_payment_requirements") // types.PaymentRequirements
After Settlement:
txHash, _ := c.Get("x402_settlement_tx") // string
network, _ := c.Get("x402_settlement_network") // string (CAIP-2)
payer, _ := c.Get("x402_settlement_payer") // string
Payment Flow
The middleware implements the full x402 v2 payment flow:
- Request without payment — Returns 402 with payment requirements and
PAYMENT-REQUIREDheader - Request with
PAYMENT-SIGNATUREheader — Verifies payment with facilitator - Invalid payment — Returns 402 with error details and
PAYMENT-REQUIREDheader - Valid payment — Handler executes (response is buffered up to
MaxBufferSize) - Handler succeeds (2xx) — Settles payment on-chain via facilitator
- Settlement succeeds — Sends buffered response with
PAYMENT-RESPONSEheader - Settlement fails — Returns error (buffered response is discarded)
Error Handling
| Scenario | Response |
|---|---|
| No payment header | 402 with requirements |
| Invalid/malformed header | 400 Bad Request |
| Payment verification fails | 402 with error |
| Facilitator unreachable | 502 Bad Gateway |
| Response exceeds MaxBufferSize | 500 (payment not settled) |
| Settlement fails | 502 or 402 (response discarded) |
| Settlement succeeds | Original handler response sent |
402 Response Format
{
"x402Version": 2,
"error": "PAYMENT-SIGNATURE header is required",
"resource": {
"url": "/api/data",
"description": "Protected data endpoint",
"mimeType": "application/json"
},
"accepts": [
{
"scheme": "exact",
"network": "eip155:8453",
"amount": "1000000",
"payTo": "0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb",
"asset": "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
"maxTimeoutSeconds": 120
}
]
}
Resource Client Package
github.com/vorpalengineering/x402-go/resource/client
NewResourceClient
Creates a new resource client.
func NewResourceClient(privateKey *ecdsa.PrivateKey) *ResourceClient
Parameters:
privateKey- Ethereum private key for signing payments. Passnilfor read-only usage (checking requirements without paying).
Browse
Fetches the /.well-known/x402 discovery endpoint.
func (c *ResourceClient) Browse(baseURL string) (*types.DiscoveryResponse, error)
Parameters:
baseURL- The base URL of the server (trailing slash is optional)
Returns:
*types.DiscoveryResponse- The discovery document containing protected endpointserror- Any error that occurred
Check
Makes an HTTP request and checks if payment is required.
func (c *ResourceClient) Check(method, url, contentType string, body []byte) (*http.Response, *types.PaymentRequired, error)
Parameters:
method- HTTP method (GET, POST, etc.)url- URL of the resourcecontentType- Content-Type header (empty string if not needed)body- Request body (nil for GET requests)
Returns:
*http.Response- The HTTP response (body is closed if 402)*types.PaymentRequired- Payment requirements if 402, nil otherwiseerror- Any error that occurred
Requirements
Fetches payment requirements from a resource URL.
func (c *ResourceClient) Requirements(method, url, contentType string, body []byte, index int) (*types.PaymentRequirements, error)
Parameters:
method- HTTP methodurl- URL of the resourcecontentType- Content-Type headerbody- Request bodyindex- Index into the accepts array (usually 0)
Returns:
*types.PaymentRequirements- The selected payment requirementserror- If resource doesn't require payment or index is out of bounds
Payload
Generates a signed payment payload for the given requirements.
func (c *ResourceClient) Payload(requirements *types.PaymentRequirements) (*types.PaymentPayload, error)
What it does:
- Validates payment scheme (currently only
exact) - Parses amount, recipient, and token contract addresses
- Creates EIP-3009
TransferWithAuthorization(random nonce, 1-hour validity window) - Signs with EIP-712 typed data
- Returns the
PaymentPayloadstruct
Pay
Generates payment and makes the HTTP request with the PAYMENT-SIGNATURE header.
func (c *ResourceClient) Pay(method, url, contentType string, body []byte, requirements *types.PaymentRequirements) (*http.Response, error)
Parameters:
method- HTTP methodurl- URL of the resourcecontentType- Content-Type headerbody- Request bodyrequirements- Payment requirements to use
Returns:
*http.Response- The HTTP responseerror- Any error that occurred
Types Package
github.com/vorpalengineering/x402-go/types
PaymentPayload
Full signed payment payload sent in PAYMENT-SIGNATURE header.
type PaymentPayload struct {
X402Version int `json:"x402Version"`
Resource *ResourceInfo `json:"resource,omitempty"`
Accepted PaymentRequirements `json:"accepted"`
Payload map[string]any `json:"payload"`
Extensions map[string]any `json:"extensions,omitempty"`
}
PaymentRequirements
Single payment option requirements.
type PaymentRequirements struct {
Scheme string `json:"scheme"`
Network string `json:"network"`
Amount string `json:"amount"`
Asset string `json:"asset"`
PayTo string `json:"payTo"`
MaxTimeoutSeconds int `json:"maxTimeoutSeconds"`
Extra map[string]any `json:"extra,omitempty"`
}
PaymentRequired
402 response with payment options.
type PaymentRequired struct {
X402Version int `json:"x402Version"`
Error string `json:"error,omitempty"`
Resource *ResourceInfo `json:"resource,omitempty"`
Accepts []PaymentRequirements `json:"accepts"`
Extensions map[string]Extension `json:"extensions,omitempty"`
}
ResourceInfo
Endpoint metadata.
type ResourceInfo struct {
URL string `json:"url"`
Description string `json:"description,omitempty"`
MimeType string `json:"mimeType,omitempty"`
}
VerifyRequest
Request to verify payment.
type VerifyRequest struct {
PaymentPayload PaymentPayload `json:"paymentPayload"`
PaymentRequirements PaymentRequirements `json:"paymentRequirements"`
}
VerifyResponse
Response from payment verification.
type VerifyResponse struct {
IsValid bool `json:"isValid"`
InvalidReason string `json:"invalidReason,omitempty"`
Payer string `json:"payer,omitempty"`
}
SettleRequest
Request to settle payment on-chain.
type SettleRequest struct {
PaymentPayload PaymentPayload `json:"paymentPayload"`
PaymentRequirements PaymentRequirements `json:"paymentRequirements"`
}
SettleResponse
Response from payment settlement.
type SettleResponse struct {
Success bool `json:"success"`
ErrorReason string `json:"errorReason,omitempty"`
Payer string `json:"payer,omitempty"`
Transaction string `json:"transaction"`
Network string `json:"network"`
}
SupportedKind
Single supported scheme-network combination.
type SupportedKind struct {
X402Version int `json:"x402Version"`
Scheme string `json:"scheme"`
Network string `json:"network"`
Extra map[string]any `json:"extra,omitempty"`
}
SupportedResponse
Response from /supported endpoint.
type SupportedResponse struct {
Kinds []SupportedKind `json:"kinds"`
Extensions []string `json:"extensions"`
Signers map[string][]string `json:"signers"`
}
DiscoveryResponse
Response from /.well-known/x402 discovery endpoint.
type DiscoveryResponse struct {
Version int `json:"version"`
Resources []string `json:"resources"`
OwnershipProofs []string `json:"ownershipProofs,omitempty"`
Instructions string `json:"instructions,omitempty"`
}
ExactEVMSchemePayload
EIP-3009 payment payload structure.
type ExactEVMSchemePayload struct {
Signature string `json:"signature"`
Authorization ExactEVMSchemeAuthorization `json:"authorization"`
}
ExactEVMSchemeAuthorization
EIP-3009 authorization parameters.
type ExactEVMSchemeAuthorization struct {
From string `json:"from"`
To string `json:"to"`
Value string `json:"value"`
ValidAfter int64 `json:"validAfter"`
ValidBefore int64 `json:"validBefore"`
Nonce string `json:"nonce"`
}
Utilities Package
github.com/vorpalengineering/x402-go/utils
GetChainID
Parse CAIP-2 network identifier to chain ID.
func GetChainID(network string) (*big.Int, error)
Example:
chainID, err := utils.GetChainID("eip155:8453") // Returns 8453
EncodePaymentHeader
Encode PaymentPayload to base64 for the PAYMENT-SIGNATURE header.
func EncodePaymentHeader(payload *types.PaymentPayload) (string, error)
DecodePaymentHeader
Decode base64 header to PaymentPayload.
func DecodePaymentHeader(header string) (*types.PaymentPayload, error)
Transport Headers
| Header | Direction | Format | Purpose |
|---|---|---|---|
PAYMENT-SIGNATURE | Client -> Server | Base64-encoded PaymentPayload | Client sends signed payment |
PAYMENT-REQUIRED | Server -> Client | Base64-encoded PaymentRequired | Server requires payment (402 response) |
PAYMENT-RESPONSE | Server -> Client | Base64-encoded SettleResponse | Server confirms payment settled (success response) |