Question about sending response and executing code after

Hey i have a little question

  def webhook(conn, _) do
    complete_purchase(conn.assigns.event.data.object)

    conn
    |> send_resp(200, "OK")
  end

I am using stripe webhooks, and in their docs they say to execute business logic after sending them a 200 response, so in this case, when we execute code like this in elixir, the result of the complete_purchase is not waited for before sending the response right?

otherwise with simple thinking this would make sense

  def webhook(conn, _) do
    conn
    |> send_resp(200, "OK")

    complete_purchase(conn.assigns.event.data.object)
  end

but in this case the complete_purchase is not getting called.
so the question is that is this ok like this(1st) or is there a way to send the response and then call the function?

Hi @benonymus,

Once, you send a response, the connection is halted, so you need to execute the complete purchase, before sending the response.

Your first option is correct, but if you want handle some errors, try using with clause or try catch.

Thanks.

Thanks for the response, but im asking in the aspect fo this:

To acknowledge receipt of a event, your endpoint must return a 2xx HTTP status code. Acknowledge events prior to any logic that needs to take place to prevent timeouts. Your endpoint is disabled if it fails to acknowledge events over consecutive days.

this is from the stripe docs, and they don’t need to know in the response of this that the purchase failed of not

so here I am not sending a response to my client

2 Likes

Hi @benonymus,

I got the point, you want to immediately respond to stripe that you have received the hook and then perform the business logic.

I followed the link, thanks for that. You can always use Tasks or Agent or some kind of genserver to handle these kind of webhooks.

Thanks.

3 Likes
    Task.start(__MODULE__, :complete_purchase, [conn.assigns.event.data.object])

this seems to do the trick, the response to stripe is sent instantly

3 Likes

@benonymus Glad you found it! Have a great day!

1 Like

you too @pmangalakader