my avatar Bahaa Zidan
Search
/

Stripe Webhook in Cloudflare Workers

Published on Stripe Webhook in Cloudflare Workers hero image

I spent a good 4 hours trying to get Stripe's webhook to work inside a Cloudflare worker. I had everything written as per Stripe's documentation. In the end someone in the Stripe discord server led me to the solution:

import Stripe from 'stripe';
 
import { env } from '$env/dynamic/private';
 
import { getStripeInstance } from '$lib/server/stripe';
 
export const POST: RequestHandler = async ({ request, platform }) => {
	const payload = Buffer.from(await request.arrayBuffer());
	const signature = request.headers.get('stripe-signature');
	if (!signature) return new Response('Missing signature', { status: 400 });
 
	const stripe = getStripeInstance();
 
	let event: Stripe.Event;
	try {
		event = await stripe.webhooks.constructEventAsync(
			payload,
			signature,
			env.SECRET_STRIPE_WEBHOOK
		);
	} catch (error) {
		return new Response(error as BodyInit, { status: 400, statusText: 'Bad signature' });
	}
 
	if (event.type === 'checkout.session.completed') {
		// DO WHAT YOU NEED WITH {event.data}
	}
 
	return new Response(undefined, { status: 200 });
};

Did you see it ? it's to use constructEventAsync instead of constructEvent. Yeah, that's it.