Created
October 15, 2019 18:18
-
-
Save Lucassifoni/5eb46b925f93517f6fab31175b51824d to your computer and use it in GitHub Desktop.
Elixir / Phoenix Stripe Webhook handling
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| plug Plug.Parsers, | |
| parsers: [App.RawBodyPlug, :urlencoded, :multipart, :json], | |
| pass: ["*/*"], | |
| json_decoder: Phoenix.json_library() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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