💡

How to test receiving of Stripe webhook with stripity_stripe (Phoenix)

2022/01/15に公開

This is the way to send a webhook with the correct signature added to the request header.

stripe_handler_test.ex
defmodule YourApp.StripeHandlerTest do
  use YourApp.ConnCase

  @valid_payload ~S({"object": "event"})
  @secret "secret" # define same string with :stripe_webhook_secret

  defp generate_signature_header(payload) do
    timestamp = System.system_time(:second)
    code = :crypto.mac(:hmac, :sha256, @secret, "#{timestamp}.#{payload}")

    signature =
      code
      |> Base.encode16(case: :lower)

    "t=#{timestamp},v1=#{signature}"
  end

  test "#webhooks returns a 200", %{conn: conn} do
    signature_header = generate_signature_header(@valid_payload)

    conn =
      conn
      |> put_req_header("content-type", "application/json")
      |> put_req_header("stripe-signature", signature_header)
      |> post("/webhook/stripe", @valid_payload)

    assert response(conn, 200)
  end
end

If you watn to send invoice.paid event. You may create JSON like this.

    payload =
      ~s({
        "id": "example",
        "object": "event",
        "data": {
          "object": {
            "id": "example",
            "object": "invoice",
            "customer": "example",
            "lines": {
              "object": "list",
              "data": [
                {
                  "id": "example",
                  "object": "line_item",
                  "quantity": 1,
                  "subscription": "#{subscription_id}",
                  "subscription_item": "example",
                  "type": "subscription"
                }
              ],
              "has_more": false,
              "total_count": 1,
              "url": "/v1/invoices/example/lines"
            }
          }
        },
        "livemode": false,
        "pending_webhooks": 2,
        "type": "invoice.paid"
      })

参考:stripity_stripe/webhook_plug_test.exs at f0e20ae57effc6425cde8ec5e889c4793e83d1d1 · code-corps/stripity_stripe

Discussion