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.
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(%{"scheme" => "exact"})
iex> X402.PaymentRequired.decode(encoded)
{:ok, %{"scheme" => "exact"}}
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> {:ok, value} = X402.PaymentRequired.encode(%{"scheme" => "exact", "maxAmountRequired" => "10"})
iex> {:ok, decoded} = X402.PaymentRequired.decode(value)
iex> decoded["maxAmountRequired"]
"10"
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()