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.WhatsAppHandlerHandler 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
endRaw 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: JSONThen this plug will automatically check conn.assigns[:raw_body] first
before falling back to Plug.Conn.read_body/1.
Summary
Functions
@spec call(Plug.Conn.t(), map()) :: Plug.Conn.t()
Handle incoming webhook requests.
Routes requests based on HTTP method:
GET- Subscription verificationPOST- Event delivery with signature validation- Other methods - Returns 405 Method Not Allowed
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 implementingWhatsApp.WebhookPlug.Handler
Raises KeyError if any required option is missing.