#Vortex
1 messages · Page 1 of 1 (latest)
import Stripe from 'stripe';
const stripe = new Stripe(process.env.STRIPE_SECRET, {
apiVersion: '2022-08-01',
});
export default async function handler(
req: NextApiRequest,
res: NextApiResponse,
) {
let event = req.body;
const endpointSecret = process.env.STRIPE_ENDPOINT_SECRET;
if (endpointSecret) {
// Get the signature sent by Stripe
const signature = req.headers['stripe-signature'];
if (!signature) {
return res.status(400).send(`Webhook Error: Missing signature`);
}
try {
event = stripe.webhooks.constructEvent(
req.body,
signature,
endpointSecret,
);
} catch (err: unknown) {
if (err instanceof Error) {
console.log(`⚠️ Webhook signature verification failed.`, err.message);
}
return res.status(400).end();
}
}
let subscription;
let status;
let invoice;
// Handle the event
switch (event.type) {
case 'invoice.created':
invoice = event.data.object;
console.log(`Invoice created: ${invoice.id}`);
handleInvoiceCreated(invoice);
break;
case 'invoice.paid':
invoice = event.data.object;
console.log(`Invoice paid: ${invoice.id}`);
handleInvoicePaid(invoice);
break;
case 'customer.subscription.created':
subscription = event.data.object;
status = subscription.status;
console.log(`Subscription created: ${subscription.id}`);
console.log(`Subscription status is ${status}.`);
handleSubscriptionCreated(subscription);
break;
~~ snip other cases ~~
default:
// Unexpected event type
console.log(`Unhandled event type ${event.type}.`);
}
// Return a 200 response to acknowledge receipt of the event
res.status(200).end();
}```
Hi there, it's common to get this error during integration. It usually means the webhook secret is not set correctly.
Makes sense! Although I'm a bit confused 😅 , the secret is given to me by the CLI right?
for testing locally that is
Yes you are right
strange, I'm not sure what my mistake is. I copied that string directly into the .env
OH
@fierce harness i think I logged into my wrong stripe account when logging into the stripe cli
i have 2
oh wait
still no luck
oh wait, I printed out the event and it wasn't encoded at all
not signed
gut tells me this is it
that the body is being parsed before passing to stripe
causing issues
Yes you need to pass the raw body to stripe.webhooks.constructEvent() function

Unhandled event type checkout.session.completed.
Invoice created: in_1M2mpvFPYWVCwPbCxXuUycx5
Subscription created: sub_1M2mpvFPYWVCwPbCidL1WlAF
Subscription status is incomplete.
Unhandled event type invoice.finalized.
Unhandled event type invoice.updated.
Subscription updated: sub_1M2mpvFPYWVCwPbCidL1WlAF
Subscription status is active.
Invoice paid: in_1M2mpvFPYWVCwPbCxXuUycx5
Unhandled event type invoice.payment_succeeded.
Unhandled event type payment_intent.succeeded.
Unhandled event type payment_intent.created.```
Cool, it's working now.