The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
test send webhook
Kiran K3fe920be6cc9
diff --git a/apps/web/lib/actions/test-send-webhook.ts b/apps/web/lib/actions/test-send-webhook.tsnew file mode 100644index 0000000000..b1ba5b45d4--- /dev/null+++ b/apps/web/lib/actions/test-send-webhook.ts@@ -0,0 +1,46 @@+"use server";++import { prisma } from "@/lib/prisma";+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({+ workspaceId: z.string(),+ webhookId: z.string(),+ trigger: z.enum(WEBHOOK_TRIGGERS),+});++// Test send webhook event+export const testSendWebhookEvent = authActionClient+ .schema(schema)+ .action(async ({ ctx, parsedInput }) => {+ const { workspace } = ctx;+ const { webhookId, trigger } = parsedInput;++ const webhook = await prisma.webhook.findUniqueOrThrow({+ where: {+ id: webhookId,+ projectId: workspace.id,+ },+ select: {+ id: true,+ url: true,+ secret: true,+ },+ });++ const payload = samplePayload[trigger] as z.infer<+ typeof webhookPayloadSchema+ >;++ await publishWebhookEventToQStash({+ webhook,+ payload,+ });++ return { ok: true };+ });diff --git a/apps/web/lib/tinybird/record-click.ts b/apps/web/lib/tinybird/record-click.tsindex 47de048361..29e3c44887 100644--- a/apps/web/lib/tinybird/record-click.ts+++ b/apps/web/lib/tinybird/record-click.ts@@ -141,7 +141,8 @@ export async function recordClick({// Send webhook events if link has webhooks enabledif (webhookIds && webhookIds.length > 0) {- sendWebhooks("link.clicked", {+ sendWebhooks({+ trigger: "link.clicked",webhooks: await webhookCache.mget(webhookIds),data: {...clickData,diff --git a/apps/web/lib/webhook/publish-edge.ts b/apps/web/lib/webhook/publish-edge.tsindex 23e8e467b8..88113ce9b4 100644--- a/apps/web/lib/webhook/publish-edge.ts+++ b/apps/web/lib/webhook/publish-edge.ts@@ -31,7 +31,8 @@ export const sendLinkWebhookOnEdge = async (},});- return sendWebhooks(trigger, {+ return sendWebhooks({+ trigger,webhooks: linkWebhooks.map(({ webhook }) => webhook),data,});diff --git a/apps/web/lib/webhook/publish.ts b/apps/web/lib/webhook/publish.tsindex 92c9bd8cf2..d0be4e63e0 100644--- a/apps/web/lib/webhook/publish.ts+++ b/apps/web/lib/webhook/publish.ts@@ -30,7 +30,7 @@ export const sendWorkspaceWebhook = async (},});- return sendWebhooks(trigger, { webhooks, data });+ return sendWebhooks({ trigger, webhooks, data });};// Send link level webhook@@ -63,7 +63,8 @@ export const sendLinkWebhook = async (},});- return sendWebhooks(trigger, {+ return sendWebhooks({+ trigger,webhooks: linkWebhooks.map(({ webhook }) => webhook),data,});diff --git a/apps/web/lib/webhook/qstash.ts b/apps/web/lib/webhook/qstash.tsindex d86dbfcaea..19df07f54a 100644--- a/apps/web/lib/webhook/qstash.ts+++ b/apps/web/lib/webhook/qstash.ts@@ -7,15 +7,16 @@ import { webhookPayloadSchema } from "../zod/schemas/webhooks";import { createWebhookSignature } from "./signature";import { prepareWebhookPayload } from "./transform";-export const sendWebhooks = async (- trigger: WebhookTrigger,- props: {- webhooks: Pick<Webhook, "id" | "url" | "secret">[];- data: any;- },-) => {- const { webhooks, data } = props;-+// Send webhooks to multiple webhooks+export const sendWebhooks = async ({+ webhooks,+ data,+ trigger,+}: {+ webhooks: Pick<Webhook, "id" | "url" | "secret">[];+ data: any;+ trigger: WebhookTrigger;+}) => {if (webhooks.length === 0) {return;}@@ -24,14 +25,12 @@ export const sendWebhooks = async (return await Promise.all(webhooks.map((webhook) =>- publishWebhookEventToQStash({- webhook,- payload,- }),+ publishWebhookEventToQStash({ webhook, payload }),),);};+// Publish webhook event to QStashexport const publishWebhookEventToQStash = async ({webhook,payload,@@ -55,4 +54,6 @@ export const publishWebhookEventToQStash = async ({if (!response.messageId) {console.error("Failed to publish webhook event to QStash", response);}++ return response;};diff --git a/apps/web/lib/webhook/sample-events/click.json b/apps/web/lib/webhook/sample-events/click.jsonnew file mode 100644index 0000000000..ac1f416003--- /dev/null+++ b/apps/web/lib/webhook/sample-events/click.json@@ -0,0 +1,35 @@+{+ "id": "event_0HInCovrWBDmIQBAsCcY1xZlK",+ "event": "link.clicked",+ "createdAt": "2024-08-26T16:37:15.889Z",+ "data": {+ "id": "rgxOhhIKj8CEmyxn",+ "aliasLinkId": "",+ "url": "https://suretriggers.com/docs/how-to-set-up-webhooks-in-postmark/",+ "ip": "63.141.57.109",+ "continent": "NA",+ "country": "US",+ "city": "San Francisco",+ "region": "CA",+ "latitude": "37.7695",+ "longitude": "-122.385",+ "device": "Desktop",+ "deviceVendor": "Apple",+ "deviceModel": "Macintosh",+ "browser": "Chrome",+ "browserVersion": "127.0.0.0",+ "engine": "Blink",+ "engineVersion": "127.0.0.0",+ "os": "Mac OS",+ "osVersion": "10.15.7",+ "cpuArchitecture": "Unknown",+ "ua": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.0.0 Safari/537.36",+ "bot": false,+ "qr": false,+ "referer": "(direct)",+ "refererUrl": "(direct)",+ "timestamp": "2024-08-26T16:37:14.843Z",+ "identityHash": "9922ba24fa6bba66b4a7dda0a5610252e6384be8ae4a88420289e49b14c35770",+ "link": { "id": "cm0aznkw30003139wxprw69nx" }+ }+}diff --git a/apps/web/lib/webhook/sample-events/lead.json b/apps/web/lib/webhook/sample-events/lead.jsonnew file mode 100644index 0000000000..6f830a7be8--- /dev/null+++ b/apps/web/lib/webhook/sample-events/lead.json@@ -0,0 +1,44 @@+{+ "id": "event_LiTGZBn26j8XDpfbVtZyEWOtx",+ "event": "lead.created",+ "createdAt": "2024-08-26T17:50:25.001Z",+ "data": {+ "eventName": "Sign up",+ "customerId": "3",+ "customerName": "Determined Apricot Wombat",+ "customerEmail": null,+ "customerAvatar": null,+ "click": {+ "id": "xCl3mETSm37wndlM",+ "url": "https://github.com/pilcrowOnPaper/astro-email-password-2fa?ref=facebook",+ "ip": "63.141.57.109",+ "continent": "NA",+ "country": "US",+ "city": "San Francisco",+ "region": "CA",+ "latitude": "37.7695",+ "longitude": "-122.385",+ "device": "Desktop",+ "deviceVendor": "Apple",+ "deviceModel": "Macintosh",+ "browser": "Chrome",+ "browserVersion": "127.0.0.0",+ "engine": "Blink",+ "engineVersion": "127.0.0.0",+ "os": "Mac OS",+ "osVersion": "10.15.7",+ "cpuArchitecture": "Unknown",+ "ua": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.0.0 Safari/537.36",+ "bot": false,+ "qr": false,+ "referer": "(direct)",+ "refererUrl": "(direct)"+ },+ "link": {+ "id": "cm0atl8tk0001k15k4691jyga",+ "externalId": null,+ "domain": "dub.sh",+ "key": "DUc7ENl"+ }+ }+}diff --git a/apps/web/lib/webhook/sample-events/link-created.json b/apps/web/lib/webhook/sample-events/link-created.jsonnew file mode 100644index 0000000000..56069b47c3--- /dev/null+++ b/apps/web/lib/webhook/sample-events/link-created.json@@ -0,0 +1,48 @@+{+ "id": "event_KleiO4HBwZFbO1vZLWIPZ2AtX",+ "event": "link.created",+ "createdAt": "2024-08-26T16:41:52.346Z",+ "data": {+ "id": "cm0b87844000dismqhkviju54",+ "domain": "dub.sh",+ "key": "sOvvXDT",+ "externalId": null,+ "url": "https://github.com/stack-auth/stack",+ "trackConversion": false,+ "archived": false,+ "expiresAt": null,+ "expiredUrl": null,+ "password": null,+ "proxy": false,+ "title": null,+ "description": null,+ "image": null,+ "video": null,+ "rewrite": false,+ "doIndex": false,+ "ios": null,+ "android": null,+ "geo": null,+ "publicStats": false,+ "tagId": null,+ "tags": [],+ "comments": null,+ "shortLink": "https://dub.sh/sOvvXDT",+ "qrCode": "https://api.dub.co/qr?url=https://dub.sh/sOvvXDT?qr=1",+ "utm_source": null,+ "utm_medium": null,+ "utm_campaign": null,+ "utm_term": null,+ "utm_content": null,+ "userId": "cm022rkcw0000ikt14mscg9sg",+ "workspaceId": "ws_cm022sis60003ikt1syy7kfhl",+ "clicks": 0,+ "lastClicked": null,+ "leads": 0,+ "sales": 0,+ "saleAmount": 0,+ "createdAt": "2024-08-26T16:41:52.084Z",+ "updatedAt": "2024-08-26T16:41:52.084Z",+ "projectId": "cm022sis60003ikt1syy7kfhl"+ }+}diff --git a/apps/web/lib/webhook/sample-events/link-deleted.json b/apps/web/lib/webhook/sample-events/link-deleted.jsonnew file mode 100644index 0000000000..e302fe9f75--- /dev/null+++ b/apps/web/lib/webhook/sample-events/link-deleted.json@@ -0,0 +1,48 @@+{+ "id": "event_KleiO4HBwZFbO1vZLWIPZ2AtX",+ "event": "link.deleted",+ "createdAt": "2024-08-26T16:41:52.346Z",+ "data": {+ "id": "cm0b87844000dismqhkviju54",+ "domain": "dub.sh",+ "key": "sOvvXDT",+ "externalId": null,+ "url": "https://github.com/stack-auth/stack",+ "trackConversion": false,+ "archived": false,+ "expiresAt": null,+ "expiredUrl": null,+ "password": null,+ "proxy": false,+ "title": null,+ "description": null,+ "image": null,+ "video": null,+ "rewrite": false,+ "doIndex": false,+ "ios": null,+ "android": null,+ "geo": null,+ "publicStats": false,+ "tagId": null,+ "tags": [],+ "comments": null,+ "shortLink": "https://dub.sh/sOvvXDT",+ "qrCode": "https://api.dub.co/qr?url=https://dub.sh/sOvvXDT?qr=1",+ "utm_source": null,+ "utm_medium": null,+ "utm_campaign": null,+ "utm_term": null,+ "utm_content": null,+ "userId": "cm022rkcw0000ikt14mscg9sg",+ "workspaceId": "ws_cm022sis60003ikt1syy7kfhl",+ "clicks": 0,+ "lastClicked": null,+ "leads": 0,+ "sales": 0,+ "saleAmount": 0,+ "createdAt": "2024-08-26T16:41:52.084Z",+ "updatedAt": "2024-08-26T16:41:52.084Z",+ "projectId": "cm022sis60003ikt1syy7kfhl"+ }+}diff --git a/apps/web/lib/webhook/sample-events/link-updated.json b/apps/web/lib/webhook/sample-events/link-updated.jsonnew file mode 100644index 0000000000..247c982491--- /dev/null+++ b/apps/web/lib/webhook/sample-events/link-updated.json@@ -0,0 +1,48 @@+{+ "id": "event_KleiO4HBwZFbO1vZLWIPZ2AtX",+ "event": "link.updated",+ "createdAt": "2024-08-26T16:41:52.346Z",+ "data": {+ "id": "cm0b87844000dismqhkviju54",+ "domain": "dub.sh",+ "key": "sOvvXDT",+ "externalId": null,+ "url": "https://github.com/stack-auth/stack",+ "trackConversion": false,+ "archived": false,+ "expiresAt": null,+ "expiredUrl": null,+ "password": null,+ "proxy": false,+ "title": null,+ "description": null,+ "image": null,+ "video": null,+ "rewrite": false,+ "doIndex": false,+ "ios": null,+ "android": null,+ "geo": null,+ "publicStats": false,+ "tagId": null,+ "tags": [],+ "comments": null,+ "shortLink": "https://dub.sh/sOvvXDT",+ "qrCode": "https://api.dub.co/qr?url=https://dub.sh/sOvvXDT?qr=1",+ "utm_source": null,+ "utm_medium": null,+ "utm_campaign": null,+ "utm_term": null,+ "utm_content": null,+ "userId": "cm022rkcw0000ikt14mscg9sg",+ "workspaceId": "ws_cm022sis60003ikt1syy7kfhl",+ "clicks": 0,+ "lastClicked": null,+ "leads": 0,+ "sales": 0,+ "saleAmount": 0,+ "createdAt": "2024-08-26T16:41:52.084Z",+ "updatedAt": "2024-08-26T16:41:52.084Z",+ "projectId": "cm022sis60003ikt1syy7kfhl"+ }+}diff --git a/apps/web/lib/webhook/sample-events/payload.ts b/apps/web/lib/webhook/sample-events/payload.tsnew file mode 100644index 0000000000..23f5ceff90--- /dev/null+++ b/apps/web/lib/webhook/sample-events/payload.ts@@ -0,0 +1,15 @@+import click from "./click.json";+import lead from "./lead.json";+import linkCreated from "./link-created.json";+import linkDeleted from "./link-deleted.json";+import linkUpdated from "./link-updated.json";+import sale from "./sale.json";++export const samplePayload = {+ "link.created": linkCreated,+ "link.updated": linkUpdated,+ "link.deleted": linkDeleted,+ "link.clicked": click,+ "lead.created": lead,+ "sale.created": sale,+};diff --git a/apps/web/lib/webhook/sample-events/sale.json b/apps/web/lib/webhook/sample-events/sale.jsonnew file mode 100644index 0000000000..736c90faf0--- /dev/null+++ b/apps/web/lib/webhook/sample-events/sale.json@@ -0,0 +1,43 @@+{+ "id": "event_d6QRfbCvrVFcZx2pJ3dUm8Aum",+ "event": "sale.created",+ "createdAt": "2024-08-26T13:30:57.703Z",+ "data": {+ "eventName": "Purchased",+ "customerId": "cm0b0xkle0001qqydqe96vaj3",+ "customerName": "Empty Apricot Hawk",+ "customerEmail": null,+ "customerAvatar": null,+ "amount": 20000,+ "paymentProcessor": "stripe",+ "invoiceId": null,+ "currency": "usd",+ "click": {+ "id": "woQlFnkMQxUyROL3",+ "url": "https://suretriggers.com/docs/how-to-set-up-webhooks-in-postmark/",+ "ip": "63.141.57.109",+ "continent": "NA",+ "country": "US",+ "city": "San Francisco",+ "region": "CA",+ "latitude": "37.7695",+ "longitude": "-122.385",+ "device": "Desktop",+ "deviceVendor": "Apple",+ "deviceModel": "Macintosh",+ "browser": "Chrome",+ "browserVersion": "127.0.0.0",+ "engine": "Blink",+ "engineVersion": "127.0.0.0",+ "os": "Mac OS",+ "osVersion": "10.15.7",+ "cpuArchitecture": "Unknown",+ "ua": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.0.0 Safari/537.36",+ "bot": false,+ "qr": false,+ "referer": "(direct)",+ "refererUrl": "(direct)"+ },+ "link": { "id": "cm0aznkw30003139wxprw69nx" }+ }+}diff --git a/apps/web/ui/modals/test-send-webhook.tsx b/apps/web/ui/modals/test-send-webhook.tsxnew file mode 100644index 0000000000..be53d58f32--- /dev/null+++ b/apps/web/ui/modals/test-send-webhook.tsx@@ -0,0 +1,122 @@+import { testSendWebhookEvent } from "@/lib/actions/test-send-webhook";+import useWorkspace from "@/lib/swr/use-workspace";+import { WebhookProps, WebhookTrigger } from "@/lib/types";+import { WEBHOOK_TRIGGER_DESCRIPTIONS } from "@/lib/webhook/constants";+import {+ Button,+ InputSelect,+ InputSelectItemProps,+ Logo,+ Modal,+} from "@dub/ui";+import { useAction } from "next-safe-action/hooks";+import {+ Dispatch,+ SetStateAction,+ useCallback,+ useMemo,+ useState,+} from "react";+import { toast } from "sonner";++function TestSendWebhookModal({+ showTestSendWebhookModal,+ setShowTestSendWebhookModal,+ webhook,+}: {+ showTestSendWebhookModal: boolean;+ setShowTestSendWebhookModal: Dispatch<SetStateAction<boolean>>;+ webhook: WebhookProps | undefined;+}) {+ const workspace = useWorkspace();+ const [selectedTrigger, setSelectedTrigger] =+ useState<InputSelectItemProps | null>(null);++ const { execute, isExecuting } = useAction(testSendWebhookEvent, {+ onSuccess: () => {+ toast.success("Webhook event sent.");+ setShowTestSendWebhookModal(false);+ },+ onError: ({ error }) => {+ toast.error(error.serverError?.serverError);+ },+ });++ const triggers = Object.entries(WEBHOOK_TRIGGER_DESCRIPTIONS).map(+ ([key, value]) => ({+ id: key,+ value: value,+ }),+ );++ return (+ <Modal+ showModal={showTestSendWebhookModal}+ setShowModal={setShowTestSendWebhookModal}+ >+ <div className="flex flex-col items-center justify-center space-y-3 border-b border-gray-200 px-4 py-4 pt-8 text-center sm:px-16">+ <Logo />+ <h3 className="text-lg font-medium">Test send webhook event</h3>+ <p className="text-center text-sm text-gray-500">{webhook?.url}</p>+ </div>+ <form+ onSubmit={async (e) => {+ e.preventDefault();++ if (!selectedTrigger || !webhook) {+ return;+ }++ execute({+ workspaceId: workspace.id!,+ webhookId: webhook.id,+ trigger: selectedTrigger?.id as WebhookTrigger,+ });+ }}+ >+ <div className="flex flex-col space-y-28 bg-gray-50 px-4 py-8 text-left sm:space-y-3 sm:rounded-b-2xl sm:px-16">+ <InputSelect+ items={triggers}+ selectedItem={selectedTrigger}+ setSelectedItem={setSelectedTrigger}+ inputAttrs={{+ placeholder: "Select a webhook event",+ }}+ />+ <Button+ disabled={!selectedTrigger}+ text="Send test webhook"+ loading={isExecuting}+ />+ </div>+ </form>+ </Modal>+ );+}++export function useTestSendWebhookModal({+ webhook,+}: {+ webhook: WebhookProps | undefined;+}) {+ const [showTestSendWebhookModal, setShowTestSendWebhookModal] =+ useState(false);++ const TestSendWebhookModalCallback = useCallback(() => {+ return (+ <TestSendWebhookModal+ showTestSendWebhookModal={showTestSendWebhookModal}+ setShowTestSendWebhookModal={setShowTestSendWebhookModal}+ webhook={webhook}+ />+ );+ }, [showTestSendWebhookModal, setShowTestSendWebhookModal]);++ return useMemo(+ () => ({+ setShowTestSendWebhookModal,+ TestSendWebhookModal: TestSendWebhookModalCallback,+ }),+ [setShowTestSendWebhookModal, TestSendWebhookModalCallback],+ );+}diff --git a/apps/web/ui/webhooks/webhook-header.tsx b/apps/web/ui/webhooks/webhook-header.tsxindex ab2098e582..828c710ffc 100644--- a/apps/web/ui/webhooks/webhook-header.tsx+++ b/apps/web/ui/webhooks/webhook-header.tsx@@ -6,12 +6,13 @@ import { WebhookProps } from "@/lib/types";import { ThreeDots } from "@/ui/shared/icons";import { Button, MaxWidthWrapper, Popover, TokenAvatar } from "@dub/ui";import { fetcher } from "@dub/utils";-import { ChevronLeft, Edit3, FileStack, Trash } from "lucide-react";+import { ChevronLeft, Edit3, FileStack, Send, Trash } from "lucide-react";import Link from "next/link";import { notFound, useRouter } from "next/navigation";import { useState } from "react";import useSWR from "swr";import { useDeleteWebhookModal } from "../modals/delete-webhook-modal";+import { useTestSendWebhookModal } from "../modals/test-send-webhook";export default function WebhookHeader({webhookId,@@ -33,8 +34,13 @@ export default function WebhookHeader({webhook,});+ const { TestSendWebhookModal, setShowTestSendWebhookModal } =+ useTestSendWebhookModal({+ webhook,+ });+const { error: permissionsError } = clientAccessCheck({- action: "oauth_apps.write",+ action: "webhooks.write",role,});@@ -45,6 +51,7 @@ export default function WebhookHeader({return (<><MaxWidthWrapper className="grid max-w-screen-lg gap-8">+ <TestSendWebhookModal /><DeleteWebhookModal /><Linkhref={`/${slug}/settings/webhooks`}@@ -107,6 +114,16 @@ export default function WebhookHeader({/>)}+ <Button+ text="Send test event"+ variant="outline"+ icon={<Send className="h-4 w-4" />}+ className="h-9 justify-start px-2"+ onClick={() => {+ setShowTestSendWebhookModal(true);+ }}+ />+<Buttontext="Remove webhook"variant="danger-outline"