Skip to content

armgit / dub

Public Imported from GitHub
0

The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.

Idempotency support for payment links webhooks

Steven Teyfbef31bc7d7b
diff --git a/apps/web/app/api/stripe/integration/webhook/checkout-session-completed.ts b/apps/web/app/api/stripe/integration/webhook/checkout-session-completed.ts
index 001af76a3e..871bfee2ac 100644
--- a/apps/web/app/api/stripe/integration/webhook/checkout-session-completed.ts
+++ b/apps/web/app/api/stripe/integration/webhook/checkout-session-completed.ts
@@ -117,19 +117,30 @@ export async function checkoutSessionCompleted(event: Stripe.Event) {
return `Workspace with stripeConnectId ${stripeAccountId} not found, skipping...`;
}
- customer = await prisma.customer.create({
- data: {
+ const payload = {
+ name: stripeCustomerName,
+ email: stripeCustomerEmail,
+ externalId: stripeCustomerEmail, // using Stripe customer email as externalId
+ projectId: workspace.id,
+ projectConnectId: stripeAccountId,
+ stripeCustomerId,
+ clickId: clickEvent.click_id,
+ linkId: clickEvent.link_id,
+ country: clickEvent.country,
+ clickedAt: new Date(clickEvent.timestamp + "Z"),
+ };
+
+ customer = await prisma.customer.upsert({
+ where: {
+ projectId_externalId: {
+ projectId: workspace.id,
+ externalId: clickEvent.click_id,
+ },
+ },
+ update: payload,
+ create: {
id: createId({ prefix: "cus_" }),
- name: stripeCustomerName,
- email: stripeCustomerEmail,
- externalId: stripeCustomerEmail, // using Stripe customer email as externalId
- projectId: workspace.id,
- projectConnectId: stripeAccountId,
- stripeCustomerId,
- clickId: clickEvent.click_id,
- linkId: clickEvent.link_id,
- country: clickEvent.country,
- clickedAt: new Date(clickEvent.timestamp + "Z"),
+ ...payload,
},
});
@@ -141,7 +152,11 @@ export async function checkoutSessionCompleted(event: Stripe.Event) {
metadata: "",
};
- await recordLead(leadEvent);
+ // hacky way to check if upsert was a create or an update
+ // see if customer.createdAt is within the last 10 seconds
+ if (new Date(customer.createdAt).getTime() > Date.now() - 10000) {
+ await recordLead(leadEvent);
+ }
linkId = clickEvent.link_id;
// if it's not either a regular stripe checkout setup or a stripe checkout link,
@@ -273,8 +288,12 @@ export async function checkoutSessionCompleted(event: Stripe.Event) {
waitUntil(
(async () => {
- // if the clickEvent variable exists, it means that a new lead was created
- if (clickEvent) {
+ // if the clickEvent variable exists and the customer was created within the last 10 seconds,
+ // we send a lead.created webhook
+ if (
+ clickEvent &&
+ new Date(customer.createdAt).getTime() > Date.now() - 10000
+ ) {
await sendWorkspaceWebhook({
trigger: "lead.created",
workspace,