WhatsApp.WebhookPlug (WhatsApp SDK v0.1.0)

Copy Markdown View Source

Plug for handling WhatsApp webhook requests in Phoenix.

Handles both subscription verification (GET) and event delivery (POST).

Usage in Phoenix Router

forward "/webhook/whatsapp", WhatsApp.WebhookPlug,
  app_secret: "your_app_secret",
  verify_token: "your_verify_token",
  handler: MyApp.WhatsAppHandler

Handler Module

defmodule MyApp.WhatsAppHandler do
  @behaviour WhatsApp.WebhookPlug.Handler

  @impl true
  def handle_event(event) do
    # event is the "value" from each change entry
    :ok
  end
end

Raw Body Access

The plug reads the raw request body via Plug.Conn.read_body/1 for signature validation. In a Phoenix application, the body is typically consumed by the JSON parser before reaching this plug. To work around this, configure a custom body reader that caches the raw body:

# In your endpoint.ex
plug Plug.Parsers,
  parsers: [:json],
  pass: ["application/json"],
  body_reader: {MyApp.CacheBodyReader, :read_body, []},
  json_decoder: JSON

Then this plug will automatically check conn.assigns[:raw_body] first before falling back to Plug.Conn.read_body/1.

Summary

Functions

Handle incoming webhook requests.

Initialize the plug with required options.

Functions

call(conn, config)

@spec call(Plug.Conn.t(), map()) :: Plug.Conn.t()

Handle incoming webhook requests.

Routes requests based on HTTP method:

  • GET - Subscription verification
  • POST - Event delivery with signature validation
  • Other methods - Returns 405 Method Not Allowed

init(opts)

@spec init(keyword()) :: map()

Initialize the plug with required options.

Options

  • :app_secret (required) - Your Facebook App Secret for signature validation
  • :verify_token (required) - The verify token configured in the Meta dashboard
  • :handler (required) - A module implementing WhatsApp.WebhookPlug.Handler

Raises KeyError if any required option is missing.