Created
June 29, 2022 16:01
-
-
Save lyzs90/35ce696a8da713c6ba20f026f7cf17a4 to your computer and use it in GitHub Desktop.
Next.js Stripe Webhook Handler
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { NextApiRequest, NextApiResponse } from 'next'; | |
import Stripe from 'stripe'; | |
import { Readable } from 'node:stream'; | |
export const config = { | |
api: { | |
bodyParser: false, | |
}, | |
}; | |
async function buffer(readable: Readable) { | |
const chunks = []; | |
for await (const chunk of readable) { | |
chunks.push(typeof chunk === 'string' ? Buffer.from(chunk) : chunk); | |
} | |
return Buffer.concat(chunks); | |
} | |
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY, { | |
apiVersion: '2020-08-27', | |
}); | |
const relevantEvents = new Set(['customer.subscription.created']); | |
export default async function handler(req: NextApiRequest, res: NextApiResponse) { | |
if (req.method === 'POST') { | |
const buf = await buffer(req); | |
const sig = req.headers['stripe-signature']; | |
const webhookSecret = process.env.STRIPE_WEBHOOK_SECRET; | |
let event: Stripe.Event; | |
try { | |
if (!sig || !webhookSecret) return; | |
event = stripe.webhooks.constructEvent(buf, sig, webhookSecret); | |
} catch (err: any) { | |
console.log(`❌ Error message: ${err.message}`); | |
return res.status(400).send({ message: `Webhook Validation Error: ${err.message}` }); | |
} | |
if (relevantEvents.has(event.type)) { | |
try { | |
switch (event.type) { | |
case 'customer.subscription.created': | |
// TODO: handle event | |
break; | |
default: | |
console.log(`Unhandled event type: ${event.type}`); | |
break; | |
} | |
} catch (error) { | |
console.log(error); | |
return res.status(400).send({ message: `Webhook Handler Error: ${error}` }); | |
} | |
} | |
res.json({ received: true }); | |
} else { | |
res.setHeader('Allow', 'POST'); | |
return res.status(405).end('Method Not Allowed'); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment