travisf

travisf

I’m working through this tutorial trying to get payments working with Stripe.

I’ve implemented a Stripe webhook handler:

defmodule Postbox.StripeHandler do
  @behaviour Plug

  alias Plug.Conn

  def init(config), do: config

  def call(%{request_path: "/webhook/payments"} = conn, _params) do
    signing_secret = Application.get_env(:stripity_stripe, :webhook_key)
    [stripe_signature] = Plug.Conn.get_req_header(conn, "stripe-signature")

    with {:ok, body, _} = Plug.Conn.read_body(conn),
         {:ok, stripe_event} =
           Stripe.Webhook.construct_event(body, stripe_signature, signing_secret) do
      Plug.Conn.assign(conn, :stripe_event, stripe_event)
    else
      err ->
        conn
        |> Conn.send_resp(:bad_request, err)
        |> Conn.halt()
    end
  end
end

I’ve copied my webhook secret (:webhook_key directly from the signing secret) but I’m still, continuously getting this error from Stripe: ** (MatchError) no match of right hand side value: {:error, "No signatures found matching the expected signature for payload"}.

This is a test account and I’m using Ngrok for the Webhook address.


Initial question aside I’m wondering if I’m just using Stripe.Checkout.Session do I need to even bother with Webhooks? Willl Stripe returning a successful URL be sufficient?

First Post!

al2o3cr

al2o3cr

I don’t believe it’s directly related to your issue, but note that there’s a specific callout in the docs for Plug.Conn.read_body saying NOT to discard the conn:

Like all functions in this module, the conn returned by read_body must be passed to the next stage of your pipeline and should not be ignored.

Most Liked

sorentwo

sorentwo

Oban Core Team

I noticed that the post appears to be deleted earlier this week. Here’s a brief, working example of how to verify stripe webhooks in phoenix.

First, parsed JSON will strip some whitespace and alphabetize keys. To calculate the correct HMAC you need to stash the original unparsed request body. A small body_reader module will do it:

# body_reader.ex
defmodule MyApp.BodyReader do
  def read_body(conn, _opts) do
    # You may want to only do this for certain paths
    with {:ok, raw_body, conn} <- Plug.Conn.read_body(conn) do
      {:ok, raw_body, Plug.Conn.put_private(conn, :raw_body, raw_body)}
    end
  end
end

Configure Plug.Parsers to use the new body_reader module:

  plug Plug.Parsers,
    parsers: [:urlencoded, :multipart, :json],
    pass: ["*/*"],
    json_decoder: Phoenix.json_library(),
    body_reader: {MyApp.BodyReader, :read_body, []}

Then define a private function to verify the signature in your controller:

defmodule MyAppWeb.StripeController do
  use MyAppWeb, :controller

  plug :verify_signature

  # actions go here

  defp verify_signature(conn, _opts) do
    case get_req_header(conn, "stripe-signature") do
      [header] ->
        ["t=" <> time, "v1=" <> sigv | _] = String.split(header, ",")
        signing_secret = Application.fetch_env!(:my_app, :stripe_signing_secret)

        hmac =
          :hmac
          |> :crypto.mac(:sha256, signing_secret, [time, ".", conn.private.raw_body])
          |> Base.encode16(case: :lower)

        if Plug.Crypto.secure_compare(hmac, sigv) do
          conn
        else
          conn
          |> send_resp(400, "Invalid Signature")
          |> halt()
        end

      _ ->
        conn
        |> send_resp(400, "Missing Signature")
        |> halt()
    end
  end
end

That will do it! If you test your webhook controller, which you certainly should, you’ll need to inject a signature as well. The signature below is fake and computed using a test signing key (whsec_test), a fake timestamp, and :raw_body:

  @signature "t=123456789,v1=34e0846d2ae20d2fcde8c391d069223f72d0518eaf511de69f785470938e1505"

  setup %{conn: conn} do
    conn =
      conn
      |> put_req_header("stripe-signature", @signature)
      |> put_private(:raw_body, ~s({"fake":"body"}))

    {:ok, conn: conn}
  end
wojtekmach

wojtekmach

Hex Core Team

This blog post might be helpful: https://dashbit.co/blog/how-we-verify-webhooks.

Lucassifoni

Lucassifoni

You need to access the body before it has been modified by a subsequent Plug.

Here is an example in Plug.Parsers docs that exposes this very use case :slight_smile:

Edit : note that you can also do that with a custom Parser that runs before other Plug.Parsers. You can pattern match on the request path if you wish to avoid copying the raw body for other kind of requests.

@behaviour Plug.Parsers
  alias Plug.Conn

  def parse(%{request_path: "/specific_path"} = conn, _type, _subtype, _headers, opts) do
    case Conn.read_body(conn, opts) do
      {:ok, body, conn} ->
        {:ok, %{raw_body: body}, conn}
      {:more, _data, conn} ->
        {:error, :too_large, conn}
    end
  end

  def parse(conn, _type, _subtype, _headers, _opts), do: {:next, conn}

Check for exhaustiveness with the docs, because I cannot verify it today.

After that, the %{raw_body: r} map gets merged into conn.params. You can access it by pattern matching on conn.params in your controller.

def handle_webhook(%{params: %{raw_body: raw_body}} = conn, params) do

There are many ways to get to the desired result, but the goal is the same : preserve the raw request body.

Last Post!

SteveL

SteveL

Just a quick note about testing the body_reader that took me a while to figure out. I had a hard time just getting the custom body reader to run in controller tests until I realized the following:

  • You must set a content-type header, and
  • You have to send your post request as a string and not a map. Sending as a map will bypass the body reader.

My test ended up looking something like:

    test "invalid hmac signature", %{conn: conn} do
      conn = 
        conn
        |> Plug.Conn.put_req_header("content-type", "application/json")
        |> post(~p"/api/webhooks", "{}")

      assert response(conn, 400) == "Invalid signature"
    end

Hope that helps someone stop banging their head on the desk as much as I did!

Where Next? Top

Trending in Questions Top

RSP87
I’m working on a project that simulates the bumbl example in the programming phoenix book. It acts almost like an email client. We have a...
New
nseaSeb
Hello, I know there is an approach for handling lists that allows for optimized traversal, but I can’t recall the specific method (somet...
New
kpanic
Hi everyone, I am toying with the idea of building a “match maker” for giving personal help to people that wants to start coding. I sta...
New
brecabral
Documentation While reading the Scoped Routes section, I noticed that the documentation currently refers to a problem without explainin...
New
velrest
So my question is quite simple and i have found no conclusive answer on forum, google or AI. Should we use :erlang.float for Integer to ...
New
asweet-confluent
I recently noticed that Elixir’s Logger defaults its primary log level to :debug when no :logger, :level application configuration is pre...
New
apz
I’m new to elixir and just tried to install the elixirLS extension for VScode(ium) and it is throwing some errors that I would like help ...
New

Other Trending Topics Top

GenericJam
Edit: 2026 May 15 - This post is archived. Mob is alive!! Main docs: mob v0.7.11 — Documentation A bit of explanation for the slightly c...
New
JesseHerrick
Hey, I’m Jesse and I’m the main contributor behind Dexter, a full-featured, lightning-fast Elixir LSP optimized for large codebases. It s...
New
mudasobwa
I am happy to introduce the very α version of the new programming language compiled to BEAM. Welcome Cure. It has literally three kille...
New
marciok
Hi there! We created Gust: A task orchestrator inspired by Airflow. For those who have never heard about Aiflow, it’s a Python-based wor...
New
mhanberg
Hi everyone! The first release candidate for the Expert language server project is now available! We’ve published a press release detai...
New
jimsynz
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews