Skip to content

Instantly share code, notes, and snippets.

@olaronymax
Last active November 10, 2023 19:32
Show Gist options
  • Save olaronymax/e9c551fe479aebbdcddef86ad4844fec to your computer and use it in GitHub Desktop.
Save olaronymax/e9c551fe479aebbdcddef86ad4844fec to your computer and use it in GitHub Desktop.
import { Stripe } from 'stripe';
import type { NextApiRequest, NextApiResponse } from 'next';
import getRawBody from 'raw-body';
export const config = {
api: {
bodyParser: false,
},
};
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
if (req.method !== 'POST') {
res.setHeader('Allow', 'POST');
return res.status(405).end('Method Not Allowed');
}
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!, { apiVersion: '2022-11-15' });
try {
const signature = req.headers['stripe-signature'];
if (!signature) {
console.log('No Stripe signature header');
return res.status(400).end('No Stripe signature header');
}
const rawBody = await getRawBody(req);
const event = stripe.webhooks.constructEvent(
rawBody.toString(),
signature,
process.env.STRIPE_WEBHOOK_SECRET as string,
);
console.log('✅ Success:', event.id);
console.log(`Received event: ${event.type}`);
return res.status(200).json({ received: true });
} catch (err) {
console.error('Error in Stripe webhook:', err);
return res.status(500).json({ message: 'Internal Server Error' });
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment