From 975f98d5ef980fba9ae3a747c280f04c795c4aea Mon Sep 17 00:00:00 2001 From: Franjo Mindek Date: Thu, 1 Oct 2026 14:07:22 +0200 Subject: [PATCH 1/7] Dedupe payment webhook events by processor event id --- .../migration.sql.diff | 15 ++++++ .../app_diff/src/payment/payment.wasp.ts.diff | 2 +- .../src/payment/stripe/webhook.ts.diff | 10 ++-- .../src/content/docs/start/guided-tour.md | 4 +- template/app/schema.prisma | 8 +++ .../app/src/payment/lemonSqueezy/webhook.ts | 14 +++++- .../payment/lemonSqueezy/webhookPayload.ts | 1 + template/app/src/payment/payment.wasp.ts | 2 +- template/app/src/payment/polar/webhook.ts | 49 +++++++++++++++---- .../app/src/payment/processedWebhookEvent.ts | 37 ++++++++++++++ template/app/src/payment/stripe/webhook.ts | 46 ++++++++++------- 11 files changed, 152 insertions(+), 36 deletions(-) create mode 100644 opensaas-sh/app_diff/migrations/20261001120000_add_processed_webhook_event/migration.sql.diff create mode 100644 template/app/src/payment/processedWebhookEvent.ts diff --git a/opensaas-sh/app_diff/migrations/20261001120000_add_processed_webhook_event/migration.sql.diff b/opensaas-sh/app_diff/migrations/20261001120000_add_processed_webhook_event/migration.sql.diff new file mode 100644 index 000000000..a7eb03952 --- /dev/null +++ b/opensaas-sh/app_diff/migrations/20261001120000_add_processed_webhook_event/migration.sql.diff @@ -0,0 +1,15 @@ +--- template/app/migrations/20261001120000_add_processed_webhook_event/migration.sql ++++ opensaas-sh/app/migrations/20261001120000_add_processed_webhook_event/migration.sql +@@ -0,0 +1,12 @@ ++-- CreateTable ++CREATE TABLE "ProcessedWebhookEvent" ( ++ "id" TEXT NOT NULL, ++ "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, ++ "paymentProcessorEventId" TEXT NOT NULL, ++ "eventType" TEXT NOT NULL, ++ ++ CONSTRAINT "ProcessedWebhookEvent_pkey" PRIMARY KEY ("id") ++); ++ ++-- CreateIndex ++CREATE UNIQUE INDEX "ProcessedWebhookEvent_paymentProcessorEventId_key" ON "ProcessedWebhookEvent"("paymentProcessorEventId"); diff --git a/opensaas-sh/app_diff/src/payment/payment.wasp.ts.diff b/opensaas-sh/app_diff/src/payment/payment.wasp.ts.diff index 28b89f6f1..7b34d7334 100644 --- a/opensaas-sh/app_diff/src/payment/payment.wasp.ts.diff +++ b/opensaas-sh/app_diff/src/payment/payment.wasp.ts.diff @@ -19,7 +19,7 @@ action(generateCheckoutSession, { entities: ["User"] }), - api("POST", "/payments-webhook", paymentsWebhook, { + api("POST", "/payments-webhook", stripeWebhook, { - entities: ["User"], + entities: ["User", "ProcessedWebhookEvent"], - middlewareConfigFn: paymentsMiddlewareConfigFn, + middlewareConfigFn: stripeMiddlewareConfigFn, }), diff --git a/opensaas-sh/app_diff/src/payment/stripe/webhook.ts.diff b/opensaas-sh/app_diff/src/payment/stripe/webhook.ts.diff index 36851c1e4..39af5c3e1 100644 --- a/opensaas-sh/app_diff/src/payment/stripe/webhook.ts.diff +++ b/opensaas-sh/app_diff/src/payment/stripe/webhook.ts.diff @@ -9,7 +9,7 @@ import { emailSender } from "wasp/server/email"; import { assertUnreachable } from "../../shared/utils"; import { UnhandledWebhookEventError } from "../errors"; -@@ -25,7 +25,7 @@ +@@ -26,7 +26,7 @@ return middlewareConfig; }; @@ -18,7 +18,7 @@ request, response, context, -@@ -106,7 +106,7 @@ +@@ -118,7 +118,7 @@ case PaymentPlanId.Credits10: await updateUserCredits( { @@ -27,7 +27,7 @@ datePaid: invoicePaidAtDate, numOfCreditsPurchased: paymentPlans[paymentPlanId].effect.amount, }, -@@ -117,7 +117,7 @@ +@@ -129,7 +129,7 @@ case PaymentPlanId.Hobby: await updateUserSubscription( { @@ -36,7 +36,7 @@ datePaid: invoicePaidAtDate, paymentPlanId, subscriptionStatus: SubscriptionStatus.Active, -@@ -164,7 +164,7 @@ +@@ -176,7 +176,7 @@ ); const user = await updateUserSubscription( @@ -45,7 +45,7 @@ prismaUserDelegate, ); -@@ -232,7 +232,7 @@ +@@ -244,7 +244,7 @@ await updateUserSubscription( { diff --git a/opensaas-sh/blog/src/content/docs/start/guided-tour.md b/opensaas-sh/blog/src/content/docs/start/guided-tour.md index f87b0cabe..7c6e468b7 100644 --- a/opensaas-sh/blog/src/content/docs/start/guided-tour.md +++ b/opensaas-sh/blog/src/content/docs/start/guided-tour.md @@ -260,7 +260,7 @@ import { paymentsMiddlewareConfigFn, paymentsWebhook } from "./webhook" with { t export const paymentSpec: Spec = [ // ... api("POST", "/payments-webhook", paymentsWebhook, { - entities: ["User"], + entities: ["User", "ProcessedWebhookEvent"], middlewareConfigFn: paymentsMiddlewareConfigFn, }), ]; @@ -268,6 +268,8 @@ export const paymentSpec: Spec = [ Within the webhook handler, we look for specific events that the payment processor sends us to let us know which payment was completed and for which user. Then we update the user's subscription status in the database. +Payment processors may deliver the same event more than once (e.g. when they retry after a timeout), so the handler records the id of every processed event in the `ProcessedWebhookEvent` entity and skips events it has already seen. This way a retried event can't grant purchased credits twice. See `src/payment/processedWebhookEvent.ts`. + To learn more about configuring the app to handle your products and payments, check out the [Payment Integrations guide](/guides/payment-integrations/). :::tip[Star our Repo on GitHub! 🌟] diff --git a/template/app/schema.prisma b/template/app/schema.prisma index 3c4ff6e98..d8a6f82dd 100644 --- a/template/app/schema.prisma +++ b/template/app/schema.prisma @@ -28,6 +28,14 @@ model User { files File[] } +model ProcessedWebhookEvent { + id String @id @default(uuid()) + createdAt DateTime @default(now()) + + paymentProcessorEventId String @unique + eventType String +} + model GptResponse { id String @id @default(uuid()) createdAt DateTime @default(now()) diff --git a/template/app/src/payment/lemonSqueezy/webhook.ts b/template/app/src/payment/lemonSqueezy/webhook.ts index aabc91307..214eb9530 100644 --- a/template/app/src/payment/lemonSqueezy/webhook.ts +++ b/template/app/src/payment/lemonSqueezy/webhook.ts @@ -8,6 +8,7 @@ import { assertUnreachable } from "../../shared/utils"; import { UnhandledWebhookEventError } from "../errors"; import { getPaymentProcessorPlanId } from "../paymentProcessorPlans"; import { PaymentPlanId, paymentPlans, SubscriptionStatus } from "../plans"; +import { processWebhookEventOnce } from "../processedWebhookEvent"; import { updateUserLemonSqueezyPaymentDetails } from "./paymentDetails"; import { parseWebhookPayload, @@ -29,7 +30,18 @@ export const lemonSqueezyWebhook: PaymentsWebhook = async ( switch (eventName) { case "order_created": - await handleOrderCreated(data, userId, prismaUserDelegate); + // Lemon Squeezy doesn't document a stable event id, so we use the order id + // to make sure a retried `order_created` event doesn't grant credits twice. + // The subscription events below only set absolute values, so handling them + // more than once is harmless. + await processWebhookEventOnce( + { + paymentProcessorEventId: `${eventName}:${data.id}`, + eventType: eventName, + }, + context.entities.ProcessedWebhookEvent, + () => handleOrderCreated(data, userId, prismaUserDelegate), + ); break; case "subscription_created": await handleSubscriptionCreated(data, userId, prismaUserDelegate); diff --git a/template/app/src/payment/lemonSqueezy/webhookPayload.ts b/template/app/src/payment/lemonSqueezy/webhookPayload.ts index a9ff77c0b..edd301cf4 100644 --- a/template/app/src/payment/lemonSqueezy/webhookPayload.ts +++ b/template/app/src/payment/lemonSqueezy/webhookPayload.ts @@ -55,6 +55,7 @@ const genericEventSchema = z.object({ * specifically Order['data']. */ const orderDataSchema = z.object({ + id: z.string(), attributes: z.object({ customer_id: z.number(), status: z.string(), diff --git a/template/app/src/payment/payment.wasp.ts b/template/app/src/payment/payment.wasp.ts index 08b4c80f9..89625590c 100644 --- a/template/app/src/payment/payment.wasp.ts +++ b/template/app/src/payment/payment.wasp.ts @@ -21,7 +21,7 @@ export const paymentSpec: Spec = [ query(getCustomerPortalUrl, { entities: ["User"] }), action(generateCheckoutSession, { entities: ["User"] }), api("POST", "/payments-webhook", paymentsWebhook, { - entities: ["User"], + entities: ["User", "ProcessedWebhookEvent"], middlewareConfigFn: paymentsMiddlewareConfigFn, }), ]; diff --git a/template/app/src/payment/polar/webhook.ts b/template/app/src/payment/polar/webhook.ts index 5cc4eea6d..bf330ac47 100644 --- a/template/app/src/payment/polar/webhook.ts +++ b/template/app/src/payment/polar/webhook.ts @@ -14,8 +14,11 @@ import { PaymentPlanId, paymentPlans, } from "../plans"; +import { processWebhookEventOnce } from "../processedWebhookEvent"; import { updateUserCredits, updateUserSubscription } from "../user"; +type PolarWebhookEvent = ReturnType; + /** * Polar requires a raw request to construct events successfully. */ @@ -44,16 +47,14 @@ export const polarWebhook: PaymentsWebhook = async ( env.POLAR_WEBHOOK_SECRET, ); - switch (event.type) { - case "order.paid": - await handleOrderPaid(event, prismaUserDelegate); - break; - case "subscription.updated": - await handleSubscriptionUpdated(event, prismaUserDelegate); - break; - default: - throw new UnhandledWebhookEventError(event.type); - } + await processWebhookEventOnce( + { + paymentProcessorEventId: getPolarEventId(request), + eventType: event.type, + }, + context.entities.ProcessedWebhookEvent, + () => handlePolarEvent(event, prismaUserDelegate), + ); return response.status(204).send(); } catch (error) { if (error instanceof UnhandledWebhookEventError) { @@ -79,6 +80,34 @@ export const polarWebhook: PaymentsWebhook = async ( } }; +/** + * Polar follows the Standard Webhooks spec: the event id is not part of the payload, + * but is sent in the `webhook-id` header and stays the same across retries. + */ +function getPolarEventId(request: express.Request): string { + const webhookId = request.headers["webhook-id"]; + if (typeof webhookId !== "string") { + throw new Error("Polar webhook id not provided"); + } + return webhookId; +} + +async function handlePolarEvent( + event: PolarWebhookEvent, + userDelegate: PrismaClient["user"], +): Promise { + switch (event.type) { + case "order.paid": + await handleOrderPaid(event, userDelegate); + break; + case "subscription.updated": + await handleSubscriptionUpdated(event, userDelegate); + break; + default: + throw new UnhandledWebhookEventError(event.type); + } +} + async function handleOrderPaid( { data: order }: WebhookOrderPaidPayload, userDelegate: PrismaClient["user"], diff --git a/template/app/src/payment/processedWebhookEvent.ts b/template/app/src/payment/processedWebhookEvent.ts new file mode 100644 index 000000000..16ef6d5c9 --- /dev/null +++ b/template/app/src/payment/processedWebhookEvent.ts @@ -0,0 +1,37 @@ +import { PrismaClient } from "wasp/server"; + +interface WebhookEventIdentity { + paymentProcessorEventId: string; + eventType: string; +} + +/** + * Payment processors deliver webhook events at least once and retry them when our + * endpoint fails or times out, so the same event can reach us more than once. + * Handling it twice would, for example, grant purchased credits twice. + * + * We remember the id of every processed event and skip the ones we have already seen. + * The event is recorded only after it was handled successfully, so a failed attempt + * is still retried by the payment processor. + */ +export async function processWebhookEventOnce( + { paymentProcessorEventId, eventType }: WebhookEventIdentity, + processedWebhookEventDelegate: PrismaClient["processedWebhookEvent"], + handleEvent: () => Promise, +): Promise { + const processedEvent = await processedWebhookEventDelegate.findUnique({ + where: { paymentProcessorEventId }, + }); + if (processedEvent) { + console.info( + `Skipping already processed webhook event ${paymentProcessorEventId} (${eventType})`, + ); + return; + } + + await handleEvent(); + + await processedWebhookEventDelegate.create({ + data: { paymentProcessorEventId, eventType }, + }); +} diff --git a/template/app/src/payment/stripe/webhook.ts b/template/app/src/payment/stripe/webhook.ts index c12a2dfa2..33ff49bf3 100644 --- a/template/app/src/payment/stripe/webhook.ts +++ b/template/app/src/payment/stripe/webhook.ts @@ -8,6 +8,7 @@ import { assertUnreachable } from "../../shared/utils"; import { UnhandledWebhookEventError } from "../errors"; import { getPaymentPlanIdByPaymentProcessorPlanId } from "../paymentProcessorPlans"; import { PaymentPlanId, paymentPlans, SubscriptionStatus } from "../plans"; +import { processWebhookEventOnce } from "../processedWebhookEvent"; import { updateUserCredits, updateUserSubscription } from "../user"; import { stripeClient } from "./stripeClient"; @@ -34,23 +35,11 @@ export const stripeWebhook: PaymentsWebhook = async ( try { const event = constructStripeEvent(request); - // If you'd like to handle more events, you can add more cases below. - // When deploying your app, you configure your webhook in the Stripe dashboard - // to only send the events that you're handling above. - // See: https://docs.opensaas.sh/guides/deploying/#setting-up-your-stripe-webhook - switch (event.type) { - case "invoice.paid": - await handleInvoicePaid(event, prismaUserDelegate); - break; - case "customer.subscription.updated": - await handleCustomerSubscriptionUpdated(event, prismaUserDelegate); - break; - case "customer.subscription.deleted": - await handleCustomerSubscriptionDeleted(event, prismaUserDelegate); - break; - default: - throw new UnhandledWebhookEventError(event.type); - } + await processWebhookEventOnce( + { paymentProcessorEventId: event.id, eventType: event.type }, + context.entities.ProcessedWebhookEvent, + () => handleStripeEvent(event, prismaUserDelegate), + ); return response.status(204).send(); } catch (error) { if (error instanceof UnhandledWebhookEventError) { @@ -91,6 +80,29 @@ function constructStripeEvent(request: express.Request): Stripe.Event { ); } +async function handleStripeEvent( + event: Stripe.Event, + prismaUserDelegate: PrismaClient["user"], +): Promise { + // If you'd like to handle more events, you can add more cases below. + // When deploying your app, you configure your webhook in the Stripe dashboard + // to only send the events that you're handling above. + // See: https://docs.opensaas.sh/guides/deploying/#setting-up-your-stripe-webhook + switch (event.type) { + case "invoice.paid": + await handleInvoicePaid(event, prismaUserDelegate); + break; + case "customer.subscription.updated": + await handleCustomerSubscriptionUpdated(event, prismaUserDelegate); + break; + case "customer.subscription.deleted": + await handleCustomerSubscriptionDeleted(event, prismaUserDelegate); + break; + default: + throw new UnhandledWebhookEventError(event.type); + } +} + async function handleInvoicePaid( event: Stripe.InvoicePaidEvent, prismaUserDelegate: PrismaClient["user"], From 697aacc07844c4a92ac44122d9ab0b50fafd8c8d Mon Sep 17 00:00:00 2001 From: Franjo Mindek Date: Thu, 1 Oct 2026 14:52:00 +0200 Subject: [PATCH 2/7] Reword webhook idempotency comments and docs --- .../docs/guides/payment-integrations/stripe.mdx | 2 +- .../blog/src/content/docs/start/guided-tour.md | 2 +- template/app/schema.prisma | 4 ++-- template/app/src/payment/lemonSqueezy/webhook.ts | 8 ++++---- template/app/src/payment/polar/webhook.ts | 4 ++-- template/app/src/payment/processedWebhookEvent.ts | 12 ++++++------ 6 files changed, 16 insertions(+), 16 deletions(-) diff --git a/opensaas-sh/blog/src/content/docs/guides/payment-integrations/stripe.mdx b/opensaas-sh/blog/src/content/docs/guides/payment-integrations/stripe.mdx index caef90f5a..d0139cb14 100644 --- a/opensaas-sh/blog/src/content/docs/guides/payment-integrations/stripe.mdx +++ b/opensaas-sh/blog/src/content/docs/guides/payment-integrations/stripe.mdx @@ -97,7 +97,7 @@ Start the Stripe CLI webhook forwarding on port 3001 where your Node server is r stripe listen --events invoice.paid,customer.subscription.updated,customer.subscription.deleted --forward-to localhost:3001/payments-webhook ``` -Since Stripe CLI 1.51, `stripe listen` requires you to say which events to forward. The ones above are the events the template's webhook handles. If you handle more events in `src/payment/stripe/webhook.ts`, add them here too. +Since Stripe CLI 1.51, `stripe listen` requires you to list the events to forward. The command above lists the events the template's webhook handles. If you handle more events in `src/payment/stripe/webhook.ts`, add them to the command too. Remember to copy and paste the outputted webhook signing secret (`whsec_...`) into your `.env.server` file under `STRIPE_WEBHOOK_SECRET`. diff --git a/opensaas-sh/blog/src/content/docs/start/guided-tour.md b/opensaas-sh/blog/src/content/docs/start/guided-tour.md index 7c6e468b7..b8622cb4a 100644 --- a/opensaas-sh/blog/src/content/docs/start/guided-tour.md +++ b/opensaas-sh/blog/src/content/docs/start/guided-tour.md @@ -268,7 +268,7 @@ export const paymentSpec: Spec = [ Within the webhook handler, we look for specific events that the payment processor sends us to let us know which payment was completed and for which user. Then we update the user's subscription status in the database. -Payment processors may deliver the same event more than once (e.g. when they retry after a timeout), so the handler records the id of every processed event in the `ProcessedWebhookEvent` entity and skips events it has already seen. This way a retried event can't grant purchased credits twice. See `src/payment/processedWebhookEvent.ts`. +Payment processors can deliver the same event more than once, for example when they retry after a timeout. The webhook handler records the id of every processed event in the `ProcessedWebhookEvent` entity and skips the events it has already seen, so a retried event can't grant purchased credits twice. You can find this logic in `src/payment/processedWebhookEvent.ts`. To learn more about configuring the app to handle your products and payments, check out the [Payment Integrations guide](/guides/payment-integrations/). diff --git a/template/app/schema.prisma b/template/app/schema.prisma index d8a6f82dd..6b1cbc504 100644 --- a/template/app/schema.prisma +++ b/template/app/schema.prisma @@ -32,8 +32,8 @@ model ProcessedWebhookEvent { id String @id @default(uuid()) createdAt DateTime @default(now()) - paymentProcessorEventId String @unique - eventType String + paymentProcessorEventId String @unique // The id the payment processor gave the event, e.g. `evt_...` for Stripe. + eventType String // E.g. `invoice.paid`. Helps you find events in the table. The webhook doesn't read it. } model GptResponse { diff --git a/template/app/src/payment/lemonSqueezy/webhook.ts b/template/app/src/payment/lemonSqueezy/webhook.ts index 214eb9530..ee426ff83 100644 --- a/template/app/src/payment/lemonSqueezy/webhook.ts +++ b/template/app/src/payment/lemonSqueezy/webhook.ts @@ -30,10 +30,10 @@ export const lemonSqueezyWebhook: PaymentsWebhook = async ( switch (eventName) { case "order_created": - // Lemon Squeezy doesn't document a stable event id, so we use the order id - // to make sure a retried `order_created` event doesn't grant credits twice. - // The subscription events below only set absolute values, so handling them - // more than once is harmless. + // Lemon Squeezy doesn't document a stable event id, so the order id serves + // as the key here. That stops a retried `order_created` event from granting + // credits twice. The subscription events below only set absolute values, + // so handling them more than once is harmless. await processWebhookEventOnce( { paymentProcessorEventId: `${eventName}:${data.id}`, diff --git a/template/app/src/payment/polar/webhook.ts b/template/app/src/payment/polar/webhook.ts index bf330ac47..c84bb1a5e 100644 --- a/template/app/src/payment/polar/webhook.ts +++ b/template/app/src/payment/polar/webhook.ts @@ -81,8 +81,8 @@ export const polarWebhook: PaymentsWebhook = async ( }; /** - * Polar follows the Standard Webhooks spec: the event id is not part of the payload, - * but is sent in the `webhook-id` header and stays the same across retries. + * Polar follows the Standard Webhooks spec. It sends the event id in the + * `webhook-id` header instead of the payload, and the id stays the same across retries. */ function getPolarEventId(request: express.Request): string { const webhookId = request.headers["webhook-id"]; diff --git a/template/app/src/payment/processedWebhookEvent.ts b/template/app/src/payment/processedWebhookEvent.ts index 16ef6d5c9..fdb1a3e49 100644 --- a/template/app/src/payment/processedWebhookEvent.ts +++ b/template/app/src/payment/processedWebhookEvent.ts @@ -6,13 +6,13 @@ interface WebhookEventIdentity { } /** - * Payment processors deliver webhook events at least once and retry them when our - * endpoint fails or times out, so the same event can reach us more than once. - * Handling it twice would, for example, grant purchased credits twice. + * Payment processors deliver each webhook event at least once. They retry when + * your endpoint fails or times out, so the same event can reach your app twice. + * Handling a "paid" event twice would grant purchased credits twice. * - * We remember the id of every processed event and skip the ones we have already seen. - * The event is recorded only after it was handled successfully, so a failed attempt - * is still retried by the payment processor. + * This function remembers the id of every processed event and skips the ones it + * has already seen. It records the event only after `handleEvent` succeeds, so + * the payment processor still retries a failed attempt. */ export async function processWebhookEventOnce( { paymentProcessorEventId, eventType }: WebhookEventIdentity, From 483a12db989a00c22d9f0b7a8a682187132d5a1c Mon Sep 17 00:00:00 2001 From: Franjo Mindek Date: Thu, 1 Oct 2026 15:02:25 +0200 Subject: [PATCH 3/7] Trim webhook idempotency comments --- template/app/schema.prisma | 4 ++-- template/app/src/payment/lemonSqueezy/webhook.ts | 5 ++--- template/app/src/payment/polar/webhook.ts | 3 +-- 3 files changed, 5 insertions(+), 7 deletions(-) diff --git a/template/app/schema.prisma b/template/app/schema.prisma index 6b1cbc504..f72a783a8 100644 --- a/template/app/schema.prisma +++ b/template/app/schema.prisma @@ -32,8 +32,8 @@ model ProcessedWebhookEvent { id String @id @default(uuid()) createdAt DateTime @default(now()) - paymentProcessorEventId String @unique // The id the payment processor gave the event, e.g. `evt_...` for Stripe. - eventType String // E.g. `invoice.paid`. Helps you find events in the table. The webhook doesn't read it. + paymentProcessorEventId String @unique // The payment processor's event id, e.g. `evt_...` for Stripe. + eventType String // The payment processor's event type, e.g. `invoice.paid`. } model GptResponse { diff --git a/template/app/src/payment/lemonSqueezy/webhook.ts b/template/app/src/payment/lemonSqueezy/webhook.ts index ee426ff83..4bae48c48 100644 --- a/template/app/src/payment/lemonSqueezy/webhook.ts +++ b/template/app/src/payment/lemonSqueezy/webhook.ts @@ -31,9 +31,8 @@ export const lemonSqueezyWebhook: PaymentsWebhook = async ( switch (eventName) { case "order_created": // Lemon Squeezy doesn't document a stable event id, so the order id serves - // as the key here. That stops a retried `order_created` event from granting - // credits twice. The subscription events below only set absolute values, - // so handling them more than once is harmless. + // as the key here. The subscription events below only set absolute values + // and don't need deduplication. await processWebhookEventOnce( { paymentProcessorEventId: `${eventName}:${data.id}`, diff --git a/template/app/src/payment/polar/webhook.ts b/template/app/src/payment/polar/webhook.ts index c84bb1a5e..33aaeed7d 100644 --- a/template/app/src/payment/polar/webhook.ts +++ b/template/app/src/payment/polar/webhook.ts @@ -81,8 +81,7 @@ export const polarWebhook: PaymentsWebhook = async ( }; /** - * Polar follows the Standard Webhooks spec. It sends the event id in the - * `webhook-id` header instead of the payload, and the id stays the same across retries. + * Polar uses the `webhook-id` header as the stable webhook event id. */ function getPolarEventId(request: express.Request): string { const webhookId = request.headers["webhook-id"]; From 4c9a8393898ab01e72b9c0e67c773b564b0539b9 Mon Sep 17 00:00:00 2001 From: Franjo Mindek Date: Thu, 1 Oct 2026 15:05:53 +0200 Subject: [PATCH 4/7] Explain why Lemon Squeezy subscription events skip deduplication --- template/app/src/payment/lemonSqueezy/webhook.ts | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/template/app/src/payment/lemonSqueezy/webhook.ts b/template/app/src/payment/lemonSqueezy/webhook.ts index 4bae48c48..50aaf227f 100644 --- a/template/app/src/payment/lemonSqueezy/webhook.ts +++ b/template/app/src/payment/lemonSqueezy/webhook.ts @@ -30,9 +30,11 @@ export const lemonSqueezyWebhook: PaymentsWebhook = async ( switch (eventName) { case "order_created": - // Lemon Squeezy doesn't document a stable event id, so the order id serves - // as the key here. The subscription events below only set absolute values - // and don't need deduplication. + // Lemon Squeezy doesn't document a stable event id. Real payloads carry + // `meta.webhook_id`, but nothing guarantees it stays the same across retries, + // so it can't serve as a deduplication key. Orders have their own id, so this + // event uses it instead. The subscription events below have no such id, and + // they only set absolute values, so processing them more than once is harmless. await processWebhookEventOnce( { paymentProcessorEventId: `${eventName}:${data.id}`, From 8ef859acb063ff04169561384f84de0ce7bbdb5c Mon Sep 17 00:00:00 2001 From: Franjo Mindek Date: Thu, 1 Oct 2026 15:29:03 +0200 Subject: [PATCH 5/7] Record webhook event before handling it to block concurrent duplicates --- .../app/src/payment/processedWebhookEvent.ts | 57 ++++++++++++++----- 1 file changed, 44 insertions(+), 13 deletions(-) diff --git a/template/app/src/payment/processedWebhookEvent.ts b/template/app/src/payment/processedWebhookEvent.ts index fdb1a3e49..57b5194e6 100644 --- a/template/app/src/payment/processedWebhookEvent.ts +++ b/template/app/src/payment/processedWebhookEvent.ts @@ -1,3 +1,4 @@ +import { Prisma } from "@prisma/client"; import { PrismaClient } from "wasp/server"; interface WebhookEventIdentity { @@ -10,28 +11,58 @@ interface WebhookEventIdentity { * your endpoint fails or times out, so the same event can reach your app twice. * Handling a "paid" event twice would grant purchased credits twice. * - * This function remembers the id of every processed event and skips the ones it - * has already seen. It records the event only after `handleEvent` succeeds, so - * the payment processor still retries a failed attempt. + * This function records the event id before it runs `handleEvent`, so a retry + * that arrives while the first attempt is still running finds the record and + * skips the event. If `handleEvent` throws, it removes the record again, so the + * payment processor's next retry can process the event. */ export async function processWebhookEventOnce( - { paymentProcessorEventId, eventType }: WebhookEventIdentity, + webhookEvent: WebhookEventIdentity, processedWebhookEventDelegate: PrismaClient["processedWebhookEvent"], handleEvent: () => Promise, ): Promise { - const processedEvent = await processedWebhookEventDelegate.findUnique({ - where: { paymentProcessorEventId }, - }); - if (processedEvent) { + const isNewEvent = await recordWebhookEvent( + webhookEvent, + processedWebhookEventDelegate, + ); + if (!isNewEvent) { console.info( - `Skipping already processed webhook event ${paymentProcessorEventId} (${eventType})`, + `Skipping already processed webhook event ${webhookEvent.paymentProcessorEventId} (${webhookEvent.eventType})`, ); return; } - await handleEvent(); + try { + await handleEvent(); + } catch (error) { + await processedWebhookEventDelegate.delete({ + where: { paymentProcessorEventId: webhookEvent.paymentProcessorEventId }, + }); + throw error; + } +} + +/** + * Returns `false` if the event was already recorded. + */ +async function recordWebhookEvent( + webhookEvent: WebhookEventIdentity, + processedWebhookEventDelegate: PrismaClient["processedWebhookEvent"], +): Promise { + try { + await processedWebhookEventDelegate.create({ data: webhookEvent }); + return true; + } catch (error) { + if (isUniqueConstraintError(error)) { + return false; + } + throw error; + } +} - await processedWebhookEventDelegate.create({ - data: { paymentProcessorEventId, eventType }, - }); +function isUniqueConstraintError(error: unknown): boolean { + return ( + error instanceof Prisma.PrismaClientKnownRequestError && + error.code === "P2002" + ); } From 16c90ce53f803d184f07cf299b548eaa52cfc7b8 Mon Sep 17 00:00:00 2001 From: Franjo Mindek Date: Thu, 1 Oct 2026 15:39:01 +0200 Subject: [PATCH 6/7] Reword processWebhookEventOnce doc comment --- template/app/src/payment/processedWebhookEvent.ts | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/template/app/src/payment/processedWebhookEvent.ts b/template/app/src/payment/processedWebhookEvent.ts index 57b5194e6..8fb4f509b 100644 --- a/template/app/src/payment/processedWebhookEvent.ts +++ b/template/app/src/payment/processedWebhookEvent.ts @@ -11,10 +11,12 @@ interface WebhookEventIdentity { * your endpoint fails or times out, so the same event can reach your app twice. * Handling a "paid" event twice would grant purchased credits twice. * - * This function records the event id before it runs `handleEvent`, so a retry - * that arrives while the first attempt is still running finds the record and - * skips the event. If `handleEvent` throws, it removes the record again, so the - * payment processor's next retry can process the event. + * This function records the event id first and runs `handleEvent` second. + * Recording first matters because a retry can arrive while the first attempt + * is still running. + * + * If `handleEvent` throws, the function removes the record so the payment + * processor can retry the event. */ export async function processWebhookEventOnce( webhookEvent: WebhookEventIdentity, From 925602ceafb5a0988a3b2ba72d754f022f121699 Mon Sep 17 00:00:00 2001 From: Franjo Mindek Date: Thu, 1 Oct 2026 16:01:15 +0200 Subject: [PATCH 7/7] Generate the demo app migration with Prisma --- .../migration.sql.diff | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) rename opensaas-sh/app_diff/migrations/{20261001120000_add_processed_webhook_event => 20261001140050_add_processed_webhook_event}/migration.sql.diff (79%) diff --git a/opensaas-sh/app_diff/migrations/20261001120000_add_processed_webhook_event/migration.sql.diff b/opensaas-sh/app_diff/migrations/20261001140050_add_processed_webhook_event/migration.sql.diff similarity index 79% rename from opensaas-sh/app_diff/migrations/20261001120000_add_processed_webhook_event/migration.sql.diff rename to opensaas-sh/app_diff/migrations/20261001140050_add_processed_webhook_event/migration.sql.diff index a7eb03952..92ee7797f 100644 --- a/opensaas-sh/app_diff/migrations/20261001120000_add_processed_webhook_event/migration.sql.diff +++ b/opensaas-sh/app_diff/migrations/20261001140050_add_processed_webhook_event/migration.sql.diff @@ -1,5 +1,5 @@ ---- template/app/migrations/20261001120000_add_processed_webhook_event/migration.sql -+++ opensaas-sh/app/migrations/20261001120000_add_processed_webhook_event/migration.sql +--- template/app/migrations/20261001140050_add_processed_webhook_event/migration.sql ++++ opensaas-sh/app/migrations/20261001140050_add_processed_webhook_event/migration.sql @@ -0,0 +1,12 @@ +-- CreateTable +CREATE TABLE "ProcessedWebhookEvent" (