X402
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
- Protocol primitives — encode/decode
PAYMENT-REQUIRED,PAYMENT-SIGNATURE, andPAYMENT-RESPONSEheaders - Facilitator client — verify and settle payments via any x402 facilitator
- Plug middleware — drop-in payment gate for Phoenix and Plug apps
- Wallet validation — EVM (Ethereum, Base, Polygon) and Solana address validation
- Zero lock-in — works with any facilitator, any chain, any framework
- Fully typed — comprehensive typespecs and Dialyzer-clean
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)
]
endQuick 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:
- Client requests a paid resource
-
Server returns
402 Payment Requiredwith pricing info - Client pays (USDC on Base, Solana, etc.)
-
Client retries with
PAYMENT-SIGNATUREheader - Server verifies via facilitator and serves the resource
Learn more at x402.org and docs.x402.org.
Related
x402_proxy— reverse proxy that adds x402 payment gating to any API- x402 TypeScript SDK — official Coinbase SDK
- x402 Python SDK — Python implementation
License
MIT License — see LICENSE for details.