From 8f0aa7e4b8dac3c839a32b8f2544f55d643b8011 Mon Sep 17 00:00:00 2001 From: SwiichyCode Date: Wed, 31 Jan 2024 08:38:00 +0100 Subject: [PATCH] feat: Implementing idempotency key verification on the webhook to prevent triggering the webhook twice if payment service encounters an error. --- src/app/api/webhooks/checkout/route.ts | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/src/app/api/webhooks/checkout/route.ts b/src/app/api/webhooks/checkout/route.ts index 98e667c..fc55ad3 100644 --- a/src/app/api/webhooks/checkout/route.ts +++ b/src/app/api/webhooks/checkout/route.ts @@ -28,15 +28,11 @@ export async function POST(req: Request) { throw new Error("Payment intent is not defined"); } - // if (event.pending_webhooks > 1) { - // throw new Error("Webhook is already processing"); - // } - const idempotency_key = await CheckoutService.getIdempotencyKey({ sessionId: session.id, }); - if (!idempotency_key?.idempotencyKey) { + if (!idempotency_key?.idempotencyKey || event.pending_webhooks > 1) { // Fix case if not a physical product if (customerDetails?.name && customerDetails?.address) { await CheckoutService.processCheckoutSession({ @@ -49,7 +45,7 @@ export async function POST(req: Request) { }); } } else { - throw new Error("Idempotency key is already defined"); + throw new Error("Webhook is already processing"); } const customerEmail = event.data.object.customer_details?.email;