example-store-stripe icon indicating copy to clipboard operation
example-store-stripe copied to clipboard

Stripe Webhook Fail When Deployed

Open michaelmcnees opened this issue 3 years ago • 3 comments

When deployed to Netlify (I would assume any Lambda-based implementation will have the same issue) Stripe webhook events fail and report:

No signatures found matching the expected signature for payload

I solved this by updating the handleStripeWebhooks function to check the NODE_ENV value and if it's set to production to use event.rawBody rather than event.body. The local dev server will fail if it's passed the rawBody.

Here is my revised function that solves the issue:

export const handleStripeWebhooks = (event, context, webhooksObj) => {
  let stripeEvent
  let body = process.env.NODE_ENV === 'production' ? event.rawBody : event.body
  try {
    const sig = event.headers['stripe-signature']
    stripeEvent = stripe.webhooks.constructEvent(
      body,
      sig,
      process.env.STRIPE_WEBHOOK_KEY
    )

    let results = null
    if (typeof webhooksObj[stripeEvent.type] !== 'undefined') {
      results = webhooksObj[stripeEvent.type](event, context)
    }
    return results
  } catch (error) {
    console.log(error)
    throw error
  }
}

michaelmcnees avatar May 07 '22 02:05 michaelmcnees

Thanks @BSKnuckles! I'll try to carve out some time for this soon. You're more than welcome to open a PR in the meantime, but no pressure!

jtoar avatar May 11 '22 14:05 jtoar

@jtoar I can probably submit that. Is this how you would expect to solve this sort of issue or is there a better way that I should use instead?

michaelmcnees avatar May 11 '22 14:05 michaelmcnees

That looks ok to me. We had a similar situation with the success and cancel urls in the checkout service. We solved it with an env var at first, but since they're GraphQL resolvers, we ended up with a bit more sophisticated solution that takes deploy previews into account:

https://github.com/redwoodjs/example-store-stripe/blob/cf309b69e2b69f09de584c25029035c0c74a4ded/api/src/services/checkouts/checkouts.js#L23-L24

In the webhook's case, the event's coming from Stripe. Maybe there's something that Stripe gives us, in the event or the context, that we could use to resolve dev vs prod in a similar way?

jtoar avatar May 11 '22 15:05 jtoar