UNPKG

@redwoodjs-stripe/api

Version:

API-side code for RedwoodJS-Stripe projects

53 lines (52 loc) 1.53 kB
import { stripe } from "./stripe"; import { nonNilAssertionError } from "./nonNilAssertionError"; const handleStripeWebhooks = async ({ event, context, webhooks = {}, secure = true }) => { if (secure) { const endpointSecret = process.env.STRIPE_WEBHOOK_KEY; if (!endpointSecret) { throw nonNilAssertionError("handleStripeWebhooks:webhookKey", { endpointSecret }); } const signature = event.headers["stripe-signature"]; if (!signature) { throw nonNilAssertionError("handleStripeWebhooks:signature", { signature }); } const parsedBody = event.isBase64Encoded ? Buffer.from(event.body ?? "", "base64").toString("utf-8") : event.body; const stripeEvent = stripe.webhooks.constructEvent( parsedBody ?? "", signature, endpointSecret ); if (typeof webhooks[stripeEvent.type] !== "undefined") { await webhooks[stripeEvent.type](stripeEvent, context); } return { statusCode: 200, results: stripeEvent }; } else { if (process.env.NODE_ENV === "production") { throw new Error("Stripe webhooks must be secure in production"); } const unverifiedStripeEvent = JSON.parse(event.body ?? ""); const eventType = unverifiedStripeEvent.type; if (typeof webhooks[eventType] !== "undefined") { await webhooks[eventType](unverifiedStripeEvent, context); } return { statusCode: 200, results: unverifiedStripeEvent }; } }; export { handleStripeWebhooks };