Encodes and decodes the x402 PAYMENT-REQUIRED header value.
The header value is Base64-encoded JSON. This module provides safe conversion
functions that return tagged tuples instead of raising. x402 v2 payloads use
x402Version, resource, accepts, and extensions; legacy standalone
requirement maps remain supported for backwards compatibility.
Summary
Header Encoding
Decodes a Base64 PAYMENT-REQUIRED value to a map.
Encodes a payment requirement payload to a Base64 header value.
Returns the canonical x402 header name.
Header Encoding
@spec decode(String.t()) :: {:ok, map()} | {:error, decode_error()}
Decodes a Base64 PAYMENT-REQUIRED value to a map.
Returns {:error, :payload_too_large} when the encoded value exceeds 8 KB.
Returns {:error, :invalid_base64} when the value cannot be Base64-decoded.
Returns {:error, :invalid_json} when JSON cannot be decoded to a map.
Examples
iex> {:ok, encoded} = X402.PaymentRequired.encode(%{"x402Version" => 2, "accepts" => []})
iex> X402.PaymentRequired.decode(encoded)
{:ok, %{"accepts" => [], "x402Version" => 2}}
iex> X402.PaymentRequired.decode("%%%")
{:error, :invalid_base64}
@spec encode(map()) :: {:ok, String.t()} | {:error, encode_error()}
Encodes a payment requirement payload to a Base64 header value.
Examples
iex> payload = %{"x402Version" => 2, "resource" => %{"url" => "https://example.com/data"}, "accepts" => [], "extensions" => %{}}
iex> {:ok, value} = X402.PaymentRequired.encode(payload)
iex> {:ok, decoded} = X402.PaymentRequired.decode(value)
iex> decoded["x402Version"]
2
iex> X402.PaymentRequired.encode(nil)
{:error, :invalid_payload}
@spec header_name() :: String.t()
Returns the canonical x402 header name.
Examples
iex> X402.PaymentRequired.header_name()
"PAYMENT-REQUIRED"
Types
@type decode_error() :: :invalid_base64 | :invalid_json | :payload_too_large
@type encode_error() :: :invalid_payload | :invalid_json
@type scheme() :: String.t()