Skip to main content

Getting Started

This guide will help you set up and integrate x402-go into your Go applications.

Prerequisites

  • Go 1.20 or later
  • An Ethereum wallet with private key for the facilitator
  • Familiarity with the Gin HTTP framework (for middleware usage)

Installation

Import the packages you need in your Go project:

import (
"github.com/vorpalengineering/x402-go/facilitator"
"github.com/vorpalengineering/x402-go/facilitator/client"
"github.com/vorpalengineering/x402-go/middleware"
"github.com/vorpalengineering/x402-go/client"
)

Running the Facilitator Service

The facilitator service processes payment verification and settlement requests.

1. Set Environment Variables

export X402_FACILITATOR_PRIVATE_KEY=0x[your_private_key]

2. Create Configuration

Copy the example configuration:

cp config.example.yaml config.facilitator.yaml

3. Start the Service

go run ./cmd/facilitator

The facilitator will start and expose the following endpoints:

EndpointMethodDescription
/supportedGETList supported payment schemes and networks
/verifyPOSTVerify a payment payload
/settlePOSTSettle a payment on-chain

Protecting APIs with Middleware

Add payment requirements to your Gin routes:

package main

import (
"github.com/gin-gonic/gin"
"github.com/vorpalengineering/x402-go/middleware"
)

func main() {
r := gin.Default()

// Configure x402 middleware
x402Config := middleware.Config{
FacilitatorURL: "http://localhost:8080",
PaymentAmount: "1000000", // Amount in smallest unit
PaymentAsset: "ETH",
PaymentNetwork: "base",
}

// Apply middleware to protected routes
protected := r.Group("/api")
protected.Use(middleware.X402(x402Config))
{
protected.GET("/premium", premiumHandler)
protected.POST("/data", dataHandler)
}

r.Run(":3000")
}

Using the Client Library

For services that need to pay for resources:

package main

import (
"github.com/vorpalengineering/x402-go/client"
)

func main() {
// Load your Ethereum private key
privateKey := loadPrivateKey()

// Create client
c := client.New(privateKey)

// Make a request to a protected resource
// The client handles payment negotiation automatically
resp, err := c.Get("http://example.com/api/premium")
if err != nil {
// Handle error
}

// Process response
}

Next Steps

  • Review the API Reference for detailed documentation
  • Check the repository for complete example applications
  • Read the x402 specification for protocol details