Attempt to fix Stripe webhooks (#2355)

Split the large transaction so we can debug better what's causing the error from Stripe dashboard
This commit is contained in:
Omar López 2022-04-04 14:39:59 -06:00 committed by GitHub
parent a7f5250b4a
commit ffff59dd00
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -1,3 +1,4 @@
import { Prisma } from "@prisma/client";
import { buffer } from "micro"; import { buffer } from "micro";
import type { NextApiRequest, NextApiResponse } from "next"; import type { NextApiRequest, NextApiResponse } from "next";
import Stripe from "stripe"; import Stripe from "stripe";
@ -22,22 +23,22 @@ export const config = {
async function handlePaymentSuccess(event: Stripe.Event) { async function handlePaymentSuccess(event: Stripe.Event) {
const paymentIntent = event.data.object as Stripe.PaymentIntent; const paymentIntent = event.data.object as Stripe.PaymentIntent;
const payment = await prisma.payment.update({ const payment = await prisma.payment.findFirst({
where: { where: {
externalId: paymentIntent.id, externalId: paymentIntent.id,
}, },
data: {
success: true,
booking: {
update: {
paid: true,
confirmed: true,
},
},
},
select: { select: {
id: true,
bookingId: true, bookingId: true,
booking: { },
});
if (!payment?.bookingId) throw new Error("Payment not found");
const booking = await prisma.booking.findUnique({
where: {
id: payment.bookingId,
},
select: { select: {
title: true, title: true,
description: true, description: true,
@ -63,14 +64,8 @@ async function handlePaymentSuccess(event: Stripe.Event) {
}, },
}, },
}, },
},
},
}); });
if (!payment) throw new Error("No payment found");
const { booking } = payment;
if (!booking) throw new Error("No booking found"); if (!booking) throw new Error("No booking found");
const { user } = booking; const { user } = booking;
@ -111,21 +106,34 @@ async function handlePaymentSuccess(event: Stripe.Event) {
if (booking.location) evt.location = booking.location; if (booking.location) evt.location = booking.location;
let bookingData: Prisma.BookingUpdateInput = {
paid: true,
confirmed: true,
};
if (booking.confirmed) { if (booking.confirmed) {
const eventManager = new EventManager(user); const eventManager = new EventManager(user);
const scheduleResult = await eventManager.create(evt); const scheduleResult = await eventManager.create(evt);
bookingData.references = { create: scheduleResult.referencesToCreate };
}
await prisma.booking.update({ const paymentUpdate = prisma.payment.update({
where: {
id: payment.id,
},
data: {
success: true,
},
});
const bookingUpdate = prisma.booking.update({
where: { where: {
id: booking.id, id: booking.id,
}, },
data: { data: bookingData,
references: {
create: scheduleResult.referencesToCreate,
},
},
}); });
}
await prisma.$transaction([paymentUpdate, bookingUpdate]);
await sendScheduledEmails({ ...evt }); await sendScheduledEmails({ ...evt });