Skip to content

Instantly share code, notes, and snippets.

@Lucassifoni
Created October 15, 2019 18:18
Show Gist options
  • Select an option

  • Save Lucassifoni/5eb46b925f93517f6fab31175b51824d to your computer and use it in GitHub Desktop.

Select an option

Save Lucassifoni/5eb46b925f93517f6fab31175b51824d to your computer and use it in GitHub Desktop.
Elixir / Phoenix Stripe Webhook handling
plug Plug.Parsers,
parsers: [App.RawBodyPlug, :urlencoded, :multipart, :json],
pass: ["*/*"],
json_decoder: Phoenix.json_library()
defmodule App.RawBodyPlug do
@behaviour Plug.Parsers
alias Plug.Conn
def parse(%{request_path: "/path/to/your/stripe/hook/endpoint"} = conn, _type, _subtype, _headers, opts) do
do_parse(conn, opts)
end
def parse(conn, _type, _subtype, _headers, _opts) do
{:next, conn}
end
defp do_parse(conn, opts) do
case Conn.read_body(conn, opts) do
{:ok, body, conn} ->
{:ok, %{raw: body}, conn}
{:more, _data, conn} ->
{:error, :too_large, conn}
end
end
end
defmodule AppWeb.StripeController do
use AppWeb, :controller
@hook_secret System.get_env("STRIPE_WEBHOOK_SECRET")
def hook(%{params: %{raw: raw}} = conn, params) do
signature = conn |> Plug.Conn.get_req_header("stripe-signature") |> List.first
secret = @hook_secret
case Stripe.Webhook.construct_event(raw, signature, secret) do
{:ok, %Stripe.Event{} = event} ->
conn |> put_status(200)
{:error, reason} -> conn |> put_status(400)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment