Noizu.WhatsApp.Webhook (Noizu.WhatsApp v0.1.0)

Copy Markdown View Source

Webhook helpers: the Meta subscription challenge, X-Hub-Signature-256 payload verification, and inbound payload parsing.

A receiver service (out of scope for the SDK) calls:

Webhook.verify_challenge(params)     # GET  — subscription handshake
Webhook.valid_signature?(raw, sig)   # POST — HMAC-SHA256 of the RAW body
Webhook.parse(raw_or_map)            #      — inbound message/status structs

Summary

Functions

Parses a webhook payload (raw JSON binary or decoded map) into events: {:ok, [%Webhook.Message{} | %Webhook.Status{} | _]} or {:error, :invalid_payload}. Each struct's Inspect implementation masks phone numbers to the last 4 digits.

Validates X-Hub-Signature-256 against the RAW request body (HMAC-SHA256 with the app secret from opts[:secret] or WHATSAPP_APP_SECRET). Constant-time comparison; the signature header is "sha256=<hex>". Returns true/false (false when no secret is set).

Verifies the subscription challenge. params is the webhook GET query as a string-keyed map ("hub.mode", "hub.verify_token", "hub.challenge"). The expected token comes from opts[:token] or WHATSAPP_VERIFY_TOKEN.

Functions

parse(payload)

@spec parse(binary() | map()) :: {:ok, [struct()]} | {:error, :invalid_payload}

Parses a webhook payload (raw JSON binary or decoded map) into events: {:ok, [%Webhook.Message{} | %Webhook.Status{} | _]} or {:error, :invalid_payload}. Each struct's Inspect implementation masks phone numbers to the last 4 digits.

valid_signature?(raw_body, signature_header, opts \\ [])

@spec valid_signature?(binary(), String.t() | nil, keyword()) :: boolean()

Validates X-Hub-Signature-256 against the RAW request body (HMAC-SHA256 with the app secret from opts[:secret] or WHATSAPP_APP_SECRET). Constant-time comparison; the signature header is "sha256=<hex>". Returns true/false (false when no secret is set).

verify_challenge(params, opts \\ [])

@spec verify_challenge(map(), keyword()) ::
  {:ok, String.t()} | {:error, :forbidden | Noizu.WhatsApp.Error.t()}

Verifies the subscription challenge. params is the webhook GET query as a string-keyed map ("hub.mode", "hub.verify_token", "hub.challenge"). The expected token comes from opts[:token] or WHATSAPP_VERIFY_TOKEN.

Returns {:ok, challenge} (echo back to Meta), {:error, :forbidden} on a mismatch, or a tag: :config error when no verify token is configured.