X402

Hex.pmDownloadsDocsCILicenseCoverage

The Elixir SDK for the x402 HTTP payment protocol.

x402 is an open standard for internet-native payments built around the HTTP 402 Payment Required status code. This library provides everything you need to accept or make x402 payments in Elixir.

Features

Installation

Add x402 to your list of dependencies in mix.exs:

def deps do
  [
    {:x402, "~> 0.1"},
    {:finch, "~> 0.19"}  # HTTP client (required for facilitator calls)
  ]
end

Quick Start

Accept payments in Phoenix

# In your router or endpoint
plug X402.Plug.PaymentGate,
  facilitator_url: "https://x402.org/facilitator",
  routes: %{
    "GET /api/weather" => %{
      price: "0.005",
      network: "eip155:8453",
      pay_to: "0xYourWalletAddress",
      description: "Weather data API"
    }
  }

That's it. Requests without payment get a 402 response with payment instructions. Requests with a valid PAYMENT-SIGNATURE header are verified and passed through.

Encode/decode headers manually

# Build a PAYMENT-REQUIRED response
{:ok, header} = X402.PaymentRequired.encode(%{
  accepts: [%{
    scheme: "exact",
    network: "eip155:8453",
    price: "0.01",
    pay_to: "0xYourWallet"
  }],
  description: "Premium API access"
})

# Decode an incoming PAYMENT-SIGNATURE
{:ok, payload} = X402.PaymentSignature.decode(signature_header)

# Verify payment via facilitator
{:ok, result} = X402.Facilitator.verify(payload, requirements)

Verify payments programmatically

# Start the facilitator client in your supervision tree
children = [
  {Finch, name: MyApp.Finch},
  {X402.Facilitator, name: MyApp.Facilitator, finch: MyApp.Finch}
]

# Then verify payments
{:ok, %{status: 200}} = X402.Facilitator.verify(
  MyApp.Facilitator,
  payment_payload,
  payment_requirements
)

Documentation

Full documentation is available at HexDocs.

x402 Protocol

x402 is an open standard by Coinbase for HTTP-native payments:

  1. Client requests a paid resource
  2. Server returns 402 Payment Required with pricing info
  3. Client pays (USDC on Base, Solana, etc.)
  4. Client retries with PAYMENT-SIGNATURE header
  5. Server verifies via facilitator and serves the resource

Learn more at x402.org and docs.x402.org.

Related

License

MIT License — see LICENSE for details.