Ramp.Webhooks.Handler (ramp v1.0.0)

Copy Markdown View Source

A tiny, framework-agnostic builder for registering callbacks per webhook event type and dispatching a verified delivery to the right one -- equivalent to the Go SDK's webhooks.Handler.

Example

handler =
  Ramp.Webhooks.Handler.new(webhook_secret: System.fetch_env!("RAMP_WEBHOOK_SECRET"))
  |> Ramp.Webhooks.Handler.on("card.created", &MyApp.Cards.on_created/1)
  |> Ramp.Webhooks.Handler.on("card.terminated", &MyApp.Cards.on_terminated/1)
  |> Ramp.Webhooks.Handler.on_unmatched(&MyApp.Webhooks.log_unhandled/1)

# in your controller/plug, with the raw request body + headers:
Ramp.Webhooks.Handler.handle(handler, raw_body, signature, timestamp)
#=> :ok | {:error, %Ramp.Error{}} | {:error, term()} (callback crash)

Summary

Functions

Verifies raw_body/signature/timestamp against the handler's secret, decodes it, and invokes the matching registered callback (or the on_unmatched/2 fallback, if any).

Builds a new handler. Requires :webhook_secret; accepts :tolerance_seconds.

Registers callback to run when a verified event's event_type matches exactly.

Registers a fallback callback for any event type without a specific handler.

Types

callback()

@type callback() :: (Ramp.Webhooks.Event.t() -> any())

t()

@type t() :: %Ramp.Webhooks.Handler{
  handlers: %{optional(String.t()) => callback()},
  secret: String.t(),
  tolerance_seconds: non_neg_integer(),
  unmatched: callback() | nil
}

Functions

handle(handler, raw_body, signature, timestamp \\ nil)

@spec handle(t(), binary(), String.t(), String.t() | nil) ::
  :ok | {:ok, :ignored} | {:error, Ramp.Error.t()}

Verifies raw_body/signature/timestamp against the handler's secret, decodes it, and invokes the matching registered callback (or the on_unmatched/2 fallback, if any).

Returns :ok if verification succeeded and a callback ran (regardless of what the callback returned), {:ok, :ignored} if verification succeeded but no callback matched and no fallback was registered, or {:error, %Ramp.Error{}} if verification/decoding failed.

new(opts)

@spec new(keyword()) :: t()

Builds a new handler. Requires :webhook_secret; accepts :tolerance_seconds.

on(handler, event_type, callback)

@spec on(t(), String.t(), callback()) :: t()

Registers callback to run when a verified event's event_type matches exactly.

on_unmatched(handler, callback)

@spec on_unmatched(t(), callback()) :: t()

Registers a fallback callback for any event type without a specific handler.