View Source Stripe.Webhook (stripity_stripe v3.3.1)

Creates a Stripe Event from webhook's payload if signature is valid.

Summary

Functions

Link to this function

construct_event(payload, signature_header, secret, tolerance_or_opts \\ 300, opts \\ [])

View Source
@spec construct_event(
  String.t(),
  String.t(),
  String.t(),
  integer() | Keyword.t(),
  Keyword.t()
) :: {:ok, Stripe.Event.t() | map() | String.t()} | {:error, any()}

Verify webhook payload and return a Stripe event.

payload is the raw, unparsed content body sent by Stripe, which can be retrieved with Plug.Conn.read_body/2. Note that Plug.Parsers will read and discard the body, so you must implement a custom body reader if the plug is located earlier in the pipeline.

signature is the value of Stripe-Signature header, which can be fetched with Plug.Conn.get_req_header/2.

secret is your webhook endpoint's secret from the Stripe Dashboard.

tolerance is the allowed deviation in seconds from the current system time to the timestamp found in signature. Defaults to 300 seconds (5 minutes).

opts is a keyword list of options. Supported options:

  • :response_as - controls the shape of the value returned in the :ok tuple. One of:
    • :struct (default) - returns a Stripe.Event.t().
    • :map - returns the decoded payload as a map with string keys (useful when persisting webhooks for later replay or struct conversion via Stripe.Converter.convert_result/1).
    • :raw - returns the original payload string verbatim.

When tolerance is omitted, opts may be passed directly as the 4th argument:

Stripe.Webhook.construct_event(payload, signature, secret, response_as: :map)

Stripe API reference: https://stripe.com/docs/webhooks/signatures#verify-manually

Example

case Stripe.Webhook.construct_event(payload, signature, secret) do
  {:ok, %Stripe.Event{} = event} ->
    # Return 200 to Stripe and handle event

  {:error, reason} ->
    # Reject webhook by responding with non-2XX
end