Chris Packett
07/21/2021, 3:11 AMChris Packett
07/21/2021, 3:13 AM<http://webhookRouter.post|webhookRouter.post>('/webhook', async (req: Request, res: Response) => {
const data = req.body.data;
const eventType = req.body.type;
switch (eventType) {
case 'checkout.session.completed': {
const stripeCustomer = await stripeClient.customers.retrieve(data.object.customer);
if (stripeCustomer.deleted) {
break;
}
const customerId = (await prismaClient.customer.findFirst({
where: {
stripeCustomerId: stripeCustomer.id
}
}))?.id;
const customerData = {
companyName: data.object.metadata.companyName,
primaryEmail: stripeCustomer.email,
primaryPhone: stripeCustomer.phone,
mondayAccountName: data.object.metadata.accountName,
stripeCustomerId: stripeCustomer.id
};
const customer = await prismaClient.customer.upsert({
where: {
// We default to -1 because we know this id doesn't exist in the DB
// and Prisma's upsert method, although it says it accepts number | undefined,
// will throw an error if the id resolves to undefined.
id: customerId || -1
},
create: customerData,
update: customerData
});
console.log(`Created Customer with ID: ${customer.id}`);
break;
}
case 'invoice.paid': {
let customer = await prismaClient.customer.findFirst({
where: {
stripeCustomerId: data.object.customer
}
});
console.log(customer);
if (!customer) {
customer = await prismaClient.customer.create({
data: {
companyName: '',
stripeCustomerId: data.object.customer
}
});
}
const payment = await prismaClient.payment.create({
data: {
amountDue: data.object.amount_due / 100,
amountPaid: data.object.amount_paid / 100,
paymentDate: new Date(data.object.created * 1000),
customerId: customer.id,
stripeCustomerId: customer.stripeCustomerId,
stripeInvoiceId: data.object.id,
stripeSubscriptionId: data.object.subscription,
stripeProductId: data.object.lines.data[0].price.product
}
});
console.log(`Created Payment with ID: ${payment.id}`);
break;
}
case 'invoice.payment_failed':
break;
default:
break;
}
res.sendStatus(200);
});