Skip to main content

API Reference

Reference for the public packages and HTTP endpoints in x402-go. JSON examples illustrate the structure; replace sample addresses, timestamps, nonces, and signatures before submitting requests.

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": "0x1111111111111111111111111111111111111111",
"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": "0x1111111111111111111111111111111111111111",
"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

NewFacilitatorClient​

Creates a new facilitator client.

func NewFacilitatorClient(facilitatorURL string) *FacilitatorClient

Parameters:

  • facilitatorURL - Base URL of the facilitator service (e.g., http://localhost:4020)

Supported​

Queries supported payment schemes, networks, and signers.

func (c *FacilitatorClient) Supported() (*types.SupportedResponse, error)

Returns:

  • *types.SupportedResponse - Supported configurations
  • error - Any error that occurred

Verify​

Verifies a payment payload against requirements.

func (c *FacilitatorClient) Verify(req *types.VerifyRequest) (*types.VerifyResponse, error)

Parameters:

  • req - Verify request containing payment payload and requirements

Returns:

  • *types.VerifyResponse - Verification result with IsValid, InvalidReason, and Payer
  • error - Any error that occurred

Settle​

Settles a payment on-chain.

func (c *FacilitatorClient) Settle(req *types.SettleRequest) (*types.SettleResponse, error)

Parameters:

  • req - Settle request containing payment payload and requirements

Returns:

  • *types.SettleResponse - Settlement result with Success, Transaction, Network, and Payer
  • error - 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: These values are set after the protected handler returns. They are unavailable inside that handler; an outer middleware can inspect them after its own c.Next() returns.

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:

  1. Request without payment — Returns 402 with payment requirements and PAYMENT-REQUIRED header
  2. Request with PAYMENT-SIGNATURE header — Verifies payment with facilitator
  3. Invalid payment — Returns 402 with error details and PAYMENT-REQUIRED header
  4. Valid payment — Handler executes (response is buffered up to MaxBufferSize)
  5. Handler succeeds (2xx) — Settles payment on-chain via facilitator
  6. Settlement succeeds — Sends buffered response with PAYMENT-RESPONSE header
  7. Settlement fails — Returns an error (buffered response is discarded)

Non-2xx handler responses are returned without settlement. Buffering does not roll back handler side effects if settlement fails.


Error Handling​

ScenarioResponse
No payment header402 with requirements
Invalid/malformed header400 Bad Request
Payment verification fails402 with error
Facilitator unreachable502 Bad Gateway
Response exceeds MaxBufferSize500 (payment not settled)
Settlement fails502 or 402 (response discarded)
Settlement succeedsOriginal 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": "0x1111111111111111111111111111111111111111",
"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. Pass nil for 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 endpoints
  • error - 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 resource
  • contentType - 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 otherwise
  • error - 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 method
  • url - URL of the resource
  • contentType - Content-Type header
  • body - Request body
  • index - Index into the accepts array (usually 0)

Returns:

  • *types.PaymentRequirements - The selected payment requirements
  • error - 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:

  1. Validates payment scheme (currently only exact)
  2. Parses amount, recipient, and token contract addresses
  3. Creates EIP-3009 TransferWithAuthorization (random nonce, valid from one hour before signing until one hour after signing)
  4. Signs with EIP-712 typed data
  5. Returns the PaymentPayload struct

The current implementation uses the fixed EIP-712 domain name USDC and version 2, ignoring requirements.Extra for signing. Tokens with a different domain require a different signing implementation or the CLI’s --name and --version options.


Pay​

Generates a payment payload and makes the HTTP request with the PAYMENT-SIGNATURE header. A nil error does not mean payment succeeded: inspect the HTTP status and PAYMENT-RESPONSE header. Pay does not validate settlement. The caller must close the response body.

func (c *ResourceClient) Pay(method, url, contentType string, body []byte, requirements *types.PaymentRequirements) (*http.Response, error)

Parameters:

  • method - HTTP method
  • url - URL of the resource
  • contentType - Content-Type header
  • body - Request body
  • requirements - Payment requirements to use

Returns:

  • *http.Response - The HTTP response
  • error - 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​

A single payment option. Amount is an integer string in the token’s smallest unit, and MaxTimeoutSeconds is expressed in seconds.

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​

HeaderDirectionFormatPurpose
PAYMENT-SIGNATUREClient -> ServerBase64-encoded PaymentPayloadClient sends signed payment
PAYMENT-REQUIREDServer -> ClientBase64-encoded PaymentRequiredServer requires payment (402 response)
PAYMENT-RESPONSEServer -> ClientBase64-encoded SettleResponseServer confirms payment settled (success response)