The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
tranform webhook data
Kiran K5390a613db54
diff --git a/apps/web/app/api/stripe/connect/webhook/checkout-session-completed.ts b/apps/web/app/api/stripe/connect/webhook/checkout-session-completed.tsindex 68e219937c..ca7f7cdeba 100644--- a/apps/web/app/api/stripe/connect/webhook/checkout-session-completed.ts+++ b/apps/web/app/api/stripe/connect/webhook/checkout-session-completed.ts@@ -2,6 +2,7 @@ import { prisma } from "@/lib/prisma";import { getLeadEvent, recordSale } from "@/lib/tinybird";import { redis } from "@/lib/upstash";import { sendLinkWebhook } from "@/lib/webhook/publish";+import { transformSaleEventData } from "@/lib/webhook/transform";import { nanoid } from "@dub/utils";import { Customer } from "@prisma/client";import { waitUntil } from "@vercel/functions";@@ -74,7 +75,17 @@ export async function checkoutSessionCompleted(event: Stripe.Event) {}),};+ // Find linkconst linkId = leadEvent.data[0].link_id;+ const link = await prisma.link.findUnique({+ where: {+ id: linkId,+ },+ });++ if (!link) {+ return `Link with ID ${linkId} not found, skipping...`;+ }await Promise.all([recordSale(saleData),@@ -111,15 +122,17 @@ export async function checkoutSessionCompleted(event: Stripe.Event) {waitUntil((async () => {- sendLinkWebhook("sale.created", {+ sendLinkWebhook({+ trigger: "sale.created",linkId,- data: {+ data: transformSaleEventData({...saleData,+ ...link,customerId: customer.id,customerName: customer.name,customerEmail: customer.email,customerAvatar: customer.avatar,- },+ }),});})(),);diff --git a/apps/web/app/api/stripe/connect/webhook/customer-created.ts b/apps/web/app/api/stripe/connect/webhook/customer-created.tsindex 370e45afaa..043e3edd59 100644--- a/apps/web/app/api/stripe/connect/webhook/customer-created.ts+++ b/apps/web/app/api/stripe/connect/webhook/customer-created.ts@@ -1,6 +1,7 @@import { prisma } from "@/lib/prisma";import { getClickEvent, recordCustomer, recordLead } from "@/lib/tinybird";import { sendLinkWebhook } from "@/lib/webhook/publish";+import { transformLeadEventData } from "@/lib/webhook/transform";import { clickEventSchemaTB } from "@/lib/zod/schemas/clicks";import { nanoid } from "@dub/utils";import { waitUntil } from "@vercel/functions";@@ -106,16 +107,17 @@ export async function customerCreated(event: Stripe.Event) {waitUntil((async () => {- sendLinkWebhook("lead.created", {+ sendLinkWebhook({+ trigger: "lead.created",linkId,- data: {+ data: transformLeadEventData({...leadData,...link,customerId: customer.id,customerName: customer.name,customerEmail: customer.email,customerAvatar: customer.avatar,- },+ }),});})(),);diff --git a/apps/web/app/api/stripe/connect/webhook/invoice-paid.ts b/apps/web/app/api/stripe/connect/webhook/invoice-paid.tsindex 5001eee39d..f08ff205e1 100644--- a/apps/web/app/api/stripe/connect/webhook/invoice-paid.ts+++ b/apps/web/app/api/stripe/connect/webhook/invoice-paid.ts@@ -2,6 +2,7 @@ import { prisma } from "@/lib/prisma";import { getLeadEvent, recordSale } from "@/lib/tinybird";import { redis } from "@/lib/upstash";import { sendLinkWebhook } from "@/lib/webhook/publish";+import { transformSaleEventData } from "@/lib/webhook/transform";import { nanoid } from "@dub/utils";import { waitUntil } from "@vercel/functions";import type Stripe from "stripe";@@ -59,6 +60,15 @@ export async function invoicePaid(event: Stripe.Event) {};const linkId = leadEvent.data[0].link_id;+ const link = await prisma.link.findUnique({+ where: {+ id: linkId,+ },+ });++ if (!link) {+ return `Link with ID ${linkId} not found, skipping...`;+ }await Promise.all([recordSale(saleData),@@ -95,15 +105,17 @@ export async function invoicePaid(event: Stripe.Event) {waitUntil((async () => {- sendLinkWebhook("sale.created", {+ sendLinkWebhook({+ trigger: "sale.created",linkId,- data: {+ data: transformSaleEventData({...saleData,+ ...link,customerId: customer.id,customerName: customer.name,customerEmail: customer.email,customerAvatar: customer.avatar,- },+ }),});})(),);diff --git a/apps/web/app/api/track/lead/route.ts b/apps/web/app/api/track/lead/route.tsindex 5192b37623..2330172544 100644--- a/apps/web/app/api/track/lead/route.ts+++ b/apps/web/app/api/track/lead/route.ts@@ -6,6 +6,7 @@ import { prismaEdge } from "@/lib/prisma/edge";import { getClickEvent, recordCustomer, recordLead } from "@/lib/tinybird";import { ratelimit } from "@/lib/upstash";import { sendLinkWebhookOnEdge } from "@/lib/webhook/publish-edge";+import { transformLeadEventData } from "@/lib/webhook/transform";import { clickEventSchemaTB } from "@/lib/zod/schemas/clicks";import {trackLeadRequestSchema,@@ -154,14 +155,17 @@ export const POST = withWorkspaceEdge(});waitUntil(- sendLinkWebhookOnEdge("lead.created", {- linkId,- data: {- ...response,- ...clickData,- ...link,- },- }),+ (async () => {+ sendLinkWebhookOnEdge({+ trigger: "lead.created",+ linkId,+ data: transformLeadEventData({+ ...response,+ ...clickData,+ ...link,+ }),+ });+ })(),);return NextResponse.json(response);diff --git a/apps/web/app/api/track/sale/route.ts b/apps/web/app/api/track/sale/route.tsindex 883fbaff03..cfcd78fdef 100644--- a/apps/web/app/api/track/sale/route.ts+++ b/apps/web/app/api/track/sale/route.ts@@ -4,6 +4,7 @@ import { withWorkspaceEdge } from "@/lib/auth/workspace-edge";import { prismaEdge } from "@/lib/prisma/edge";import { getLeadEvent, recordSale } from "@/lib/tinybird";import { sendLinkWebhookOnEdge } from "@/lib/webhook/publish-edge";+import { transformSaleEventData } from "@/lib/webhook/transform";import { clickEventSchemaTB } from "@/lib/zod/schemas/clicks";import {trackSaleRequestSchema,@@ -59,6 +60,21 @@ export const POST = withWorkspaceEdge(.omit({ timestamp: true }).parse(leadEvent.data[0]);+ // Find link+ const linkId = clickData.link_id;+ const link = await prismaEdge.link.findUnique({+ where: {+ id: linkId,+ },+ });++ if (!link) {+ throw new DubApiError({+ code: "not_found",+ message: `Link with ID ${linkId} not found, skipping...`,+ });+ }+await Promise.all([recordSale({...clickData,@@ -74,7 +90,7 @@ export const POST = withWorkspaceEdge(// update link sales countprismaEdge.link.update({where: {- id: leadEvent.data[0].link_id,+ id: linkId,},data: {sales: {@@ -112,16 +128,18 @@ export const POST = withWorkspaceEdge(});waitUntil(- sendLinkWebhookOnEdge("sale.created", {- linkId: clickData.link_id,- data: {+ sendLinkWebhookOnEdge({+ trigger: "sale.created",+ linkId,+ data: transformSaleEventData({...response,...clickData,+ ...link,customerId: customer.id,customerName: customer.name,customerEmail: customer.email,customerAvatar: customer.avatar,- },+ }),}),);diff --git a/apps/web/app/api/webhooks/callback/route.ts b/apps/web/app/api/webhooks/callback/route.tsindex 53c07a2ea8..c630ad2190 100644--- a/apps/web/app/api/webhooks/callback/route.ts+++ b/apps/web/app/api/webhooks/callback/route.ts@@ -1,9 +1,7 @@import { verifyQstashSignature } from "@/lib/cron/verify-qstash";import { recordWebhookEvent } from "@/lib/tinybird/record-webhook-event";-import {- webhookCallbackSchema,- webhookPayloadSchema,-} from "@/lib/zod/schemas/webhooks";+import { webhookPayloadSchema } from "@/lib/webhook/schemas";+import { webhookCallbackSchema } from "@/lib/zod/schemas/webhooks";import { getSearchParams } from "@dub/utils";// POST /api/webhooks/callback – listen to webhooks status from QStashdiff --git a/apps/web/app/api/webhooks/receive/route.ts b/apps/web/app/api/webhooks/receive/route.tsindex bf2b1a5fff..2cd4a228bc 100644--- a/apps/web/app/api/webhooks/receive/route.ts+++ b/apps/web/app/api/webhooks/receive/route.ts@@ -1,6 +1,6 @@import { prisma } from "@/lib/prisma";-import { LeadEventData } from "@/lib/webhook/types";-import { webhookPayloadSchema } from "@/lib/zod/schemas/webhooks";+import { webhookPayloadSchema } from "@/lib/webhook/schemas";+import { LeadEventDataProps } from "@/lib/webhook/types";import crypto from "crypto";// POST /api/webhooks/receive - receive link-level webhooks from Dub@@ -25,7 +25,7 @@ export const POST = async (req: Request) => {// A new lead was created on Dubif (event === "lead.created") {- const lead = data as LeadEventData;+ const lead = data as LeadEventDataProps;const workspaceId = lead.link.externalId?.replace("ws_", "");if (!workspaceId) {diff --git a/apps/web/lib/actions/test-send-webhook.ts b/apps/web/lib/actions/test-send-webhook.tsindex b1ba5b45d4..c504669954 100644--- a/apps/web/lib/actions/test-send-webhook.ts+++ b/apps/web/lib/actions/test-send-webhook.ts@@ -1,11 +1,11 @@"use server";import { prisma } from "@/lib/prisma";+import { webhookPayloadSchema } from "@/lib/webhook/schemas";import { WEBHOOK_TRIGGERS } from "../webhook/constants";import { publishWebhookEventToQStash } from "../webhook/qstash";import { samplePayload } from "../webhook/sample-events/payload";import z from "../zod";-import { webhookPayloadSchema } from "../zod/schemas/webhooks";import { authActionClient } from "./safe-action";const schema = z.object({diff --git a/apps/web/lib/tinybird/record-click.ts b/apps/web/lib/tinybird/record-click.tsindex 29e3c44887..93dd0e784b 100644--- a/apps/web/lib/tinybird/record-click.ts+++ b/apps/web/lib/tinybird/record-click.ts@@ -18,6 +18,7 @@ import { conn } from "../planetscale";import { ratelimit } from "../upstash";import { webhookCache } from "../webhook/cache";import { sendWebhooks } from "../webhook/qstash";+import { transformClickEventData } from "../webhook/transform";/*** Recording clicks with geo, ua, referer and timestamp data@@ -60,7 +61,7 @@ export async function recordClick({);if (!success) {- return null;+ // return null;}const isQr = detectQr(req);@@ -141,13 +142,11 @@ export async function recordClick({// Send webhook events if link has webhooks enabledif (webhookIds && webhookIds.length > 0) {- sendWebhooks({+ await sendWebhooks({trigger: "link.clicked",webhooks: await webhookCache.mget(webhookIds),- data: {- ...clickData,- url,- },+ // @ts-ignore+ data: transformClickEventData(clickData),});}}diff --git a/apps/web/lib/webhook/qstash.ts b/apps/web/lib/webhook/qstash.tsindex a82becf443..6fa18782c8 100644--- a/apps/web/lib/webhook/qstash.ts+++ b/apps/web/lib/webhook/qstash.ts@@ -1,31 +1,22 @@import { qstash } from "@/lib/cron";+import { webhookPayloadSchema } from "@/lib/webhook/schemas";import { APP_DOMAIN_WITH_NGROK } from "@dub/utils";import { Webhook } from "@prisma/client";import { WebhookTrigger } from "../types";import z from "../zod";-import { webhookPayloadSchema } from "../zod/schemas/webhooks";import { createWebhookSignature } from "./signature";import { prepareWebhookPayload } from "./transform";-import {- ClickEventDataProps,- LeadEventDataProps,- LinkEventDataProps,- SaleEventDataProps,-} from "./types";+import { EventDataProps } from "./types";// Send webhooks to multiple webhooksexport const sendWebhooks = async ({webhooks,- data,trigger,+ data,}: {webhooks: Pick<Webhook, "id" | "url" | "secret">[];- data:- | LinkEventDataProps- | ClickEventDataProps- | LeadEventDataProps- | SaleEventDataProps;trigger: WebhookTrigger;+ data: EventDataProps;}) => {if (webhooks.length === 0) {return;diff --git a/apps/web/lib/webhook/schemas.ts b/apps/web/lib/webhook/schemas.tsindex 86ad76beaf..c0d150a130 100644--- a/apps/web/lib/webhook/schemas.ts+++ b/apps/web/lib/webhook/schemas.ts@@ -1,14 +1,8 @@import z from "@/lib/zod";import { LinkSchema } from "../zod/schemas/links";+import { WEBHOOK_TRIGGERS } from "./constants";-export const linkEventSchema = LinkSchema---// .extend({-// expiresAt: z.string().nullable(),-// createdAt: z.string(),-// updatedAt: z.string(),-// });+export const linkEventSchema = LinkSchema;export const clickEventSchema = z.object({id: z.string(),@@ -67,5 +61,27 @@ export const saleEventSchema = z.object({invoiceId: z.string().nullable(),currency: z.string(),click: clickEventSchema.partial(),- link: z.object({ id: z.string() }),+ link: z.object({+ id: z.string(),+ externalId: z.string().nullable(),+ domain: z.string(),+ key: z.string(),+ }),+});++// Schema of the payload sent to the webhook endpoint by Dub+export const webhookPayloadSchema = z.object({+ id: z.string().describe("Unique identifier for the event."),+ event: z+ .enum(WEBHOOK_TRIGGERS)+ .describe("The type of event that triggered the webhook."),+ createdAt: z+ .string()+ .describe("The date and time when the event was created."),+ data: z.union([+ linkEventSchema,+ clickEventSchema,+ leadEventSchema,+ saleEventSchema,+ ]),});diff --git a/apps/web/lib/webhook/transform.ts b/apps/web/lib/webhook/transform.tsindex 2c6b5e00ba..e6db3a1ac2 100644--- a/apps/web/lib/webhook/transform.ts+++ b/apps/web/lib/webhook/transform.ts@@ -1,8 +1,10 @@+import { webhookPayloadSchema } from "@/lib/webhook/schemas";import { nanoid, toCamelCase } from "@dub/utils";import type { Link, Webhook } from "@prisma/client";import { WebhookTrigger } from "../types";+import z from "../zod";+import { clickEventSchemaTB } from "../zod/schemas/clicks";import { LinkSchema } from "../zod/schemas/links";-import { webhookPayloadSchema } from "../zod/schemas/webhooks";import { WEBHOOK_EVENT_ID_PREFIX } from "./constants";import { clickEventSchema, leadEventSchema, saleEventSchema } from "./schemas";@@ -33,7 +35,9 @@ export const transformLinkEventData = (data: Link) => {});};-export const transformClickEventData = (data: any) => {+export const transformClickEventData = (+ data: z.infer<typeof clickEventSchemaTB>,+) => {const click = Object.fromEntries(Object.entries(data).map(([key, value]) => [toCamelCase(key), value]),);@@ -43,7 +47,6 @@ export const transformClickEventData = (data: any) => {id: click.clickId,link: {id: click.linkId,- url: click.url,},});};@@ -85,6 +88,9 @@ export const transformSaleEventData = (data: any) => {},link: {id: sale.linkId,+ externalId: sale.externalId,+ domain: sale.domain,+ key: sale.key,},});};diff --git a/apps/web/lib/webhook/types.ts b/apps/web/lib/webhook/types.tsindex e928b24e1f..467e10e4f8 100644--- a/apps/web/lib/webhook/types.ts+++ b/apps/web/lib/webhook/types.ts@@ -13,3 +13,9 @@ export type ClickEventDataProps = z.infer<typeof clickEventSchema>;export type LeadEventDataProps = z.infer<typeof leadEventSchema>;export type SaleEventDataProps = z.infer<typeof saleEventSchema>;++export type EventDataProps =+ | LinkEventDataProps+ | ClickEventDataProps+ | LeadEventDataProps+ | SaleEventDataProps;diff --git a/apps/web/lib/zod/schemas/webhooks.ts b/apps/web/lib/zod/schemas/webhooks.tsindex 2e1f91046c..9542d2c1e3 100644--- a/apps/web/lib/zod/schemas/webhooks.ts+++ b/apps/web/lib/zod/schemas/webhooks.ts@@ -44,16 +44,4 @@ export const webhookEventSchemaTB = z.object({request_body: z.string(),response_body: z.string(),timestamp: z.string(),-});--// Schema of the payload sent to the webhook endpoint by Dub-export const webhookPayloadSchema = z.object({- id: z.string().describe("Unique identifier for the event."),- event: z- .enum(WEBHOOK_TRIGGERS)- .describe("The type of event that triggered the webhook."),- createdAt: z- .string()- .describe("The date and time when the event was created."),- data: z.any().describe("The data associated with the event."),-});+});\ No newline at end of file