View Source LemonEx.Webhooks.Plug (lemon_ex v0.2.2)

A plug that receives, verifies, and handles Webhook Events sent by LemonSqueezy.

If you want to handle Webhook Events, you must do two things:

1-create-an-event-handler

1. Create an event handler

Create a new module that implements the callback:

handle_event(%LemonEx.Webhooks.Event{}) :: :ok | {:error, binary()}

The handler module should call your application logic and return either :ok or {:error, message}.

For example:

defmodule MyAppWeb.MyWebhookHandler do
  @behaviour LemonEx.Webhooks.Handler

  @impl true
  def handle_event(%LemonEx.Webhooks.Event{name: "order_created"} = event) do
    # The event.data holds the object of the event,
    # like e.g. an `LemonEx.Orders.Order{}`.
    new_order = event.data

    # do something with the new order

    # Return either :ok or {:error, error_message}
    :ok
  end

  # You need to handle all incoming events. So, better have a
  # catch-all handler for events that you don't want to handle,
  # but only want to acknowledge.
  @impl true
  def handle_event(_unhandled_event), do: :ok
end

2-add-the-lemonex-webhooks-plug-to-your-endpoint

2. Add the LemonEx.Webhooks.Plug to your Endpoint

In your endpoint.ex, add the LemonEx.Webhooks.Plug before the Plug.Parsers-plug.

# In your endpoint.ex
plug LemonEx.Webhooks.Plug,
  at: "/webhook/lemonsqueezy",
  handler: MyAppWeb.MyHandler

# Make sure that this plug comes after the LemonEx plug.
plug Plug.Parsers