The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
Partner postbacks (#3467)
Kiran K9c93481cfbb1
diff --git a/apps/web/app/(ee)/api/partner-profile/postbacks/[postbackId]/events/route.ts b/apps/web/app/(ee)/api/partner-profile/postbacks/[postbackId]/events/route.tsnew file mode 100644index 0000000000..1231e2c1a9--- /dev/null+++ b/apps/web/app/(ee)/api/partner-profile/postbacks/[postbackId]/events/route.ts@@ -0,0 +1,26 @@+import { getPostbackOrThrow } from "@/lib/api/postbacks/get-postback-or-throw";+import { withPartnerProfile } from "@/lib/auth/partner";+import { getPostbackEvents } from "@/lib/postback/api/get-postback-events";+import { NextResponse } from "next/server";++// GET /api/partner-profile/postbacks/[postbackId]/events+export const GET = withPartnerProfile(+ async ({ partner, params }) => {+ const { postbackId } = params;++ await getPostbackOrThrow({+ postbackId,+ partnerId: partner.id,+ });++ const events = await getPostbackEvents({+ postbackId,+ });++ return NextResponse.json(events.data);+ },+ {+ requiredPermission: "postbacks.read",+ featureFlag: "postbacks",+ },+);diff --git a/apps/web/app/(ee)/api/partner-profile/postbacks/[postbackId]/rotate-secret/route.ts b/apps/web/app/(ee)/api/partner-profile/postbacks/[postbackId]/rotate-secret/route.tsnew file mode 100644index 0000000000..5a63450327--- /dev/null+++ b/apps/web/app/(ee)/api/partner-profile/postbacks/[postbackId]/rotate-secret/route.ts@@ -0,0 +1,41 @@+import { createToken } from "@/lib/api/oauth/utils";+import { getPostbackOrThrow } from "@/lib/api/postbacks/get-postback-or-throw";+import { withPartnerProfile } from "@/lib/auth/partner";+import {+ POSTBACK_SECRET_LENGTH,+ POSTBACK_SECRET_PREFIX,+} from "@/lib/postback/constants";+import { prisma } from "@dub/prisma";+import { NextResponse } from "next/server";++// POST /api/partner-profile/postbacks/[postbackId]/rotate-secret+export const POST = withPartnerProfile(+ async ({ partner, params }) => {+ const { postbackId } = params;++ await getPostbackOrThrow({+ postbackId,+ partnerId: partner.id,+ });++ const secret = createToken({+ prefix: POSTBACK_SECRET_PREFIX,+ length: POSTBACK_SECRET_LENGTH,+ });++ await prisma.postback.update({+ where: {+ id: postbackId,+ },+ data: {+ secret,+ },+ });++ return NextResponse.json({ secret });+ },+ {+ requiredPermission: "postbacks.write",+ featureFlag: "postbacks",+ },+);diff --git a/apps/web/app/(ee)/api/partner-profile/postbacks/[postbackId]/route.ts b/apps/web/app/(ee)/api/partner-profile/postbacks/[postbackId]/route.tsnew file mode 100644index 0000000000..0e29517e86--- /dev/null+++ b/apps/web/app/(ee)/api/partner-profile/postbacks/[postbackId]/route.ts@@ -0,0 +1,87 @@+import { getPostbackOrThrow } from "@/lib/api/postbacks/get-postback-or-throw";+import { parseRequestBody } from "@/lib/api/utils";+import { withPartnerProfile } from "@/lib/auth/partner";+import {+ postbackSchema,+ updatePostbackInputSchema,+} from "@/lib/postback/schemas";+import { prisma } from "@dub/prisma";+import { NextResponse } from "next/server";++// GET /api/partner-profile/postbacks/[postbackId]+export const GET = withPartnerProfile(+ async ({ partner, params }) => {+ const { postbackId } = params;++ const postback = await getPostbackOrThrow({+ postbackId,+ partnerId: partner.id,+ });++ return NextResponse.json(postbackSchema.parse(postback));+ },+ {+ requiredPermission: "postbacks.read",+ featureFlag: "postbacks",+ },+);++// PATCH /api/partner-profile/postbacks/[postbackId]+export const PATCH = withPartnerProfile(+ async ({ partner, params, req }) => {+ const { postbackId } = params;++ let postback = await getPostbackOrThrow({+ postbackId,+ partnerId: partner.id,+ });++ const { name, url, triggers, disabled } = updatePostbackInputSchema.parse(+ await parseRequestBody(req),+ );++ postback = await prisma.postback.update({+ where: {+ id: postbackId,+ },+ data: {+ ...(name !== undefined && { name }),+ ...(url !== undefined && { url }),+ ...(triggers !== undefined && { triggers }),+ ...(disabled !== undefined && {+ disabledAt: disabled ? new Date() : null,+ }),+ },+ });++ return NextResponse.json(postbackSchema.parse(postback));+ },+ {+ requiredPermission: "postbacks.write",+ featureFlag: "postbacks",+ },+);++// DELETE /api/partner-profile/postbacks/[postbackId]+export const DELETE = withPartnerProfile(+ async ({ partner, params }) => {+ const { postbackId } = params;++ await getPostbackOrThrow({+ postbackId,+ partnerId: partner.id,+ });++ await prisma.postback.delete({+ where: {+ id: postbackId,+ },+ });++ return NextResponse.json({ id: postbackId });+ },+ {+ requiredPermission: "postbacks.write",+ featureFlag: "postbacks",+ },+);diff --git a/apps/web/app/(ee)/api/partner-profile/postbacks/[postbackId]/send-test/route.ts b/apps/web/app/(ee)/api/partner-profile/postbacks/[postbackId]/send-test/route.tsnew file mode 100644index 0000000000..3626b2a1ba--- /dev/null+++ b/apps/web/app/(ee)/api/partner-profile/postbacks/[postbackId]/send-test/route.ts@@ -0,0 +1,55 @@+import { DubApiError } from "@/lib/api/errors";+import { getPostbackOrThrow } from "@/lib/api/postbacks/get-postback-or-throw";+import { parseRequestBody } from "@/lib/api/utils";+import { withPartnerProfile } from "@/lib/auth/partner";+import { sendPartnerPostback } from "@/lib/postback/api/send-partner-postback";+import commissionCreated from "@/lib/postback/sample-events/commission-created.json";+import leadCreated from "@/lib/postback/sample-events/lead-created.json";+import saleCreated from "@/lib/postback/sample-events/sale-created.json";+import { sendTestPostbackInputSchema } from "@/lib/postback/schemas";+import { PostbackTrigger } from "@/lib/types";+import { NextResponse } from "next/server";++const samplePayloads: Record<PostbackTrigger, Record<string, unknown>> = {+ "lead.created": leadCreated,+ "sale.created": saleCreated,+ "commission.created": commissionCreated,+};++// POST /api/partner-profile/postbacks/[postbackId]/send-test+export const POST = withPartnerProfile(+ async ({ partner, params, req }) => {+ const { postbackId } = params;++ const { event } = sendTestPostbackInputSchema.parse(+ await parseRequestBody(req),+ );++ const postback = await getPostbackOrThrow({+ postbackId,+ partnerId: partner.id,+ });++ const triggers = postback.triggers as string[];++ if (!triggers.includes(event)) {+ throw new DubApiError({+ code: "bad_request",+ message: "The selected event is not configured for this postback.",+ });+ }++ await sendPartnerPostback({+ partnerId: partner.id,+ event,+ data: samplePayloads[event],+ skipEnrichment: true,+ });++ return NextResponse.json({});+ },+ {+ requiredPermission: "postbacks.write",+ featureFlag: "postbacks",+ },+);diff --git a/apps/web/app/(ee)/api/partner-profile/postbacks/route.ts b/apps/web/app/(ee)/api/partner-profile/postbacks/route.tsnew file mode 100644index 0000000000..b8019cbb63--- /dev/null+++ b/apps/web/app/(ee)/api/partner-profile/postbacks/route.ts@@ -0,0 +1,86 @@+import { createId } from "@/lib/api/create-id";+import { DubApiError } from "@/lib/api/errors";+import { createToken } from "@/lib/api/oauth/utils";+import { parseRequestBody } from "@/lib/api/utils";+import { withPartnerProfile } from "@/lib/auth/partner";+import { identifyPostbackChannel } from "@/lib/postback/api/utils";+import {+ MAX_POSTBACKS,+ POSTBACK_SECRET_LENGTH,+ POSTBACK_SECRET_PREFIX,+} from "@/lib/postback/constants";+import {+ createPostbackInputSchema,+ createPostbackOutputSchema,+ postbackSchema,+} from "@/lib/postback/schemas";+import { prisma } from "@dub/prisma";+import { NextResponse } from "next/server";+import * as z from "zod/v4";++// GET /api/partner-profile/postbacks+export const GET = withPartnerProfile(+ async ({ partner }) => {+ const postbacks = await prisma.postback.findMany({+ where: {+ partnerId: partner.id,+ },+ orderBy: {+ createdAt: "desc",+ },+ });++ return NextResponse.json(z.array(postbackSchema).parse(postbacks));+ },+ {+ requiredPermission: "postbacks.read",+ featureFlag: "postbacks",+ },+);++// POST /api/partner-profile/postbacks+export const POST = withPartnerProfile(+ async ({ partner, req }) => {+ const { name, url, triggers } = createPostbackInputSchema.parse(+ await parseRequestBody(req),+ );++ const postbackCount = await prisma.postback.count({+ where: {+ partnerId: partner.id,+ },+ });++ if (postbackCount >= MAX_POSTBACKS) {+ throw new DubApiError({+ code: "exceeded_limit",+ message: `Maximum number of postbacks (${MAX_POSTBACKS}) reached.`,+ });+ }++ const secret = createToken({+ prefix: POSTBACK_SECRET_PREFIX,+ length: POSTBACK_SECRET_LENGTH,+ });++ const postback = await prisma.postback.create({+ data: {+ id: createId({ prefix: "pb_" }),+ partnerId: partner.id,+ name,+ url,+ secret,+ triggers,+ receiver: identifyPostbackChannel(url),+ },+ });++ return NextResponse.json(createPostbackOutputSchema.parse(postback), {+ status: 201,+ });+ },+ {+ requiredPermission: "postbacks.write",+ featureFlag: "postbacks",+ },+);diff --git a/apps/web/app/(ee)/api/partner-profile/route.ts b/apps/web/app/(ee)/api/partner-profile/route.tsindex 34ad813a1f..bd582dd686 100644--- a/apps/web/app/(ee)/api/partner-profile/route.ts+++ b/apps/web/app/(ee)/api/partner-profile/route.ts@@ -1,10 +1,14 @@import { withPartnerProfile } from "@/lib/auth/partner";+import { getPartnerFeatureFlags } from "@/lib/edge-config";import { NextResponse } from "next/server";// GET /api/partner-profile - get a partner profileexport const GET = withPartnerProfile(async ({ partner, partnerUser }) => {+ const featureFlags = await getPartnerFeatureFlags(partner.id);+return NextResponse.json({...partnerUser,...partner,+ featureFlags,});});diff --git a/apps/web/app/(ee)/api/partners/analytics/route.ts b/apps/web/app/(ee)/api/partners/analytics/route.tsindex 976ca0de9f..49e41c29fe 100644--- a/apps/web/app/(ee)/api/partners/analytics/route.ts+++ b/apps/web/app/(ee)/api/partners/analytics/route.ts@@ -1,6 +1,5 @@import { getAnalytics } from "@/lib/analytics/get-analytics";import { getStartEndDates } from "@/lib/analytics/utils/get-start-end-dates";-import { parseFilterValue } from "@dub/utils";import { DubApiError } from "@/lib/api/errors";import { getDefaultProgramIdOrThrow } from "@/lib/api/programs/get-default-program-id-or-throw";import { withWorkspace } from "@/lib/auth";@@ -11,6 +10,7 @@ import {partnersTopLinksSchema,} from "@/lib/zod/schemas/partners";import { prisma } from "@dub/prisma";+import { parseFilterValue } from "@dub/utils";import { format } from "date-fns";import { NextResponse } from "next/server";diff --git a/apps/web/app/(ee)/api/stripe/integration/webhook/checkout-session-completed.ts b/apps/web/app/(ee)/api/stripe/integration/webhook/checkout-session-completed.tsindex ad27d8625a..d87a8068d7 100644--- a/apps/web/app/(ee)/api/stripe/integration/webhook/checkout-session-completed.ts+++ b/apps/web/app/(ee)/api/stripe/integration/webhook/checkout-session-completed.ts@@ -7,6 +7,7 @@ import { syncPartnerLinksStats } from "@/lib/api/partners/sync-partner-links-staimport { executeWorkflows } from "@/lib/api/workflows/execute-workflows";import { generateRandomName } from "@/lib/names";import { createPartnerCommission } from "@/lib/partners/create-partner-commission";+import { sendPartnerPostback } from "@/lib/postback/api/send-partner-postback";import {getClickEvent,getLeadEvent,@@ -512,20 +513,36 @@ export async function checkoutSessionCompleted();}- // send workspace webhookwaitUntil(- sendWorkspaceWebhook({- trigger: "sale.created",- workspace,- data: transformSaleEventData({- ...saleData,- clickedAt: customer.clickedAt || customer.createdAt,- link: linkUpdated,- customer,- partner: createdCommission?.webhookPartner,- metadata: null,+ Promise.allSettled([+ sendWorkspaceWebhook({+ trigger: "sale.created",+ workspace,+ data: transformSaleEventData({+ ...saleData,+ clickedAt: customer.clickedAt || customer.createdAt,+ link: linkUpdated,+ customer,+ partner: createdCommission?.webhookPartner,+ metadata: null,+ }),}),- }),++ ...(link?.partnerId+ ? [+ sendPartnerPostback({+ partnerId: link.partnerId,+ event: "sale.created",+ data: {+ ...saleData,+ clickedAt: customer.clickedAt || customer.createdAt,+ link: linkUpdated,+ customer,+ },+ }),+ ]+ : []),+ ]),);return `Checkout session completed for customer with external ID ${dubCustomerExternalId} and invoice ID ${invoiceId}`;@@ -685,18 +702,35 @@ async function attributeViaPromoCode({]);}- await sendWorkspaceWebhook({- trigger: "lead.created",- workspace,- data: transformLeadEventData({- ...leadEvent,- eventName: "Checkout session completed",- link: linkUpdated,- customer,- partner: createdCommission?.webhookPartner,- metadata: null,+ await Promise.allSettled([+ sendWorkspaceWebhook({+ trigger: "lead.created",+ workspace,+ data: transformLeadEventData({+ ...leadEvent,+ eventName: "Checkout session completed",+ link: linkUpdated,+ customer,+ partner: createdCommission?.webhookPartner,+ metadata: null,+ }),}),- });++ ...(link.partnerId+ ? [+ sendPartnerPostback({+ partnerId: link.partnerId,+ event: "lead.created",+ data: {+ ...leadEvent,+ eventName: "Checkout session completed",+ link: linkUpdated,+ customer,+ },+ }),+ ]+ : []),+ ]);})(),);diff --git a/apps/web/app/(ee)/api/stripe/integration/webhook/invoice-paid.ts b/apps/web/app/(ee)/api/stripe/integration/webhook/invoice-paid.tsindex 600a2e1076..6a527da2b4 100644--- a/apps/web/app/(ee)/api/stripe/integration/webhook/invoice-paid.ts+++ b/apps/web/app/(ee)/api/stripe/integration/webhook/invoice-paid.ts@@ -5,6 +5,7 @@ import { includeTags } from "@/lib/api/links/include-tags";import { syncPartnerLinksStats } from "@/lib/api/partners/sync-partner-links-stats";import { executeWorkflows } from "@/lib/api/workflows/execute-workflows";import { createPartnerCommission } from "@/lib/partners/create-partner-commission";+import { sendPartnerPostback } from "@/lib/postback/api/send-partner-postback";import { getLeadEvent, recordSale } from "@/lib/tinybird";import { StripeMode } from "@/lib/types";import { redis } from "@/lib/upstash";@@ -280,20 +281,36 @@ export async function invoicePaid(event: Stripe.Event, mode: StripeMode) {);}- // send workspace webhookwaitUntil(- sendWorkspaceWebhook({- trigger: "sale.created",- workspace,- data: transformSaleEventData({- ...saleData,- clickedAt: customer.clickedAt || customer.createdAt,- link: linkUpdated,- customer,- partner: createdCommission?.webhookPartner,- metadata: null,+ Promise.allSettled([+ sendWorkspaceWebhook({+ trigger: "sale.created",+ workspace,+ data: transformSaleEventData({+ ...saleData,+ clickedAt: customer.clickedAt || customer.createdAt,+ link: linkUpdated,+ customer,+ partner: createdCommission?.webhookPartner,+ metadata: null,+ }),}),- }),++ ...(link?.partnerId+ ? [+ sendPartnerPostback({+ partnerId: link.partnerId,+ event: "sale.created",+ data: {+ ...saleData,+ clickedAt: customer.clickedAt || customer.createdAt,+ link: linkUpdated,+ customer,+ },+ }),+ ]+ : []),+ ]),);return `Sale recorded for customer ID ${customer.id} and invoice ID ${invoiceId}`;diff --git a/apps/web/app/(ee)/api/stripe/integration/webhook/utils/create-new-customer.ts b/apps/web/app/(ee)/api/stripe/integration/webhook/utils/create-new-customer.tsindex ff244a534b..2740aab740 100644--- a/apps/web/app/(ee)/api/stripe/integration/webhook/utils/create-new-customer.ts+++ b/apps/web/app/(ee)/api/stripe/integration/webhook/utils/create-new-customer.ts@@ -3,6 +3,7 @@ import { includeTags } from "@/lib/api/links/include-tags";import { syncPartnerLinksStats } from "@/lib/api/partners/sync-partner-links-stats";import { executeWorkflows } from "@/lib/api/workflows/execute-workflows";import { generateRandomName } from "@/lib/names";+import { sendPartnerPostback } from "@/lib/postback/api/send-partner-postback";import { getClickEvent, recordLead } from "@/lib/tinybird";import { redis } from "@/lib/upstash";import { sendWorkspaceWebhook } from "@/lib/webhook/publish";@@ -137,17 +138,34 @@ export async function createNewCustomer(event: Stripe.Event) {// send workspace webhookwaitUntil(- sendWorkspaceWebhook({- trigger: "lead.created",- workspace,- data: transformLeadEventData({- ...clickData,- eventName,- link: linkUpdated,- customer,- metadata: null,+ Promise.allSettled([+ sendWorkspaceWebhook({+ trigger: "lead.created",+ workspace,+ data: transformLeadEventData({+ ...clickData,+ eventName,+ link: linkUpdated,+ customer,+ metadata: null,+ }),}),- }),++ ...(link.partnerId+ ? [+ sendPartnerPostback({+ partnerId: link.partnerId,+ event: "lead.created",+ data: {+ ...clickData,+ eventName,+ link: linkUpdated,+ customer,+ },+ }),+ ]+ : []),+ ]),);return `New Dub customer created: ${customer.id}. Lead event recorded: ${leadData.event_id}`;diff --git a/apps/web/app/(ee)/partners.dub.co/(dashboard)/profile/postbacks/[id]/page-client.tsx b/apps/web/app/(ee)/partners.dub.co/(dashboard)/profile/postbacks/[id]/page-client.tsxnew file mode 100644index 0000000000..4b8addc180--- /dev/null+++ b/apps/web/app/(ee)/partners.dub.co/(dashboard)/profile/postbacks/[id]/page-client.tsx@@ -0,0 +1,162 @@+"use client";++import { PostbackEventProps, PostbackProps } from "@/lib/types";+import { PageContent } from "@/ui/layout/page-content";+import { PageWidthWrapper } from "@/ui/layout/page-width-wrapper";+import { useAddEditPostbackModal } from "@/ui/postbacks/add-edit-postback-modal";+import { PostbackActions } from "@/ui/postbacks/partner-postback-actions";+import { PostbackDetailSkeleton } from "@/ui/postbacks/postback-detail-skeleton";+import { usePostbackEventDetailsSheet } from "@/ui/postbacks/postback-event-details-sheet";+import { PostbackEventList } from "@/ui/postbacks/postback-event-list";+import { PostbackEventListSkeleton } from "@/ui/postbacks/postback-event-list-skeleton";+import { usePostbackSecretModal } from "@/ui/postbacks/postback-secret-modal";+import { PostbackStatus } from "@/ui/postbacks/postback-status";+import { BackLink } from "@/ui/shared/back-link";+import { EmptyState, TokenAvatar, Webhook } from "@dub/ui";+import { fetcher } from "@dub/utils";+import { redirect, useRouter } from "next/navigation";+import { useState } from "react";+import useSWR from "swr";++interface PostbackDetailPageClientProps {+ postbackId: string;+}++export function PostbackDetailPageClient({+ postbackId,+}: PostbackDetailPageClientProps) {+ const router = useRouter();+ const [openPopover, setOpenPopover] = useState(false);++ const {+ data: postback,+ error,+ isLoading,+ mutate,+ } = useSWR<PostbackProps>(+ postbackId ? `/api/partner-profile/postbacks/${postbackId}` : null,+ fetcher,+ );++ const {+ data: events,+ error: eventsError,+ isLoading: isEventsLoading,+ } = useSWR<PostbackEventProps[]>(+ postbackId ? `/api/partner-profile/postbacks/${postbackId}/events` : null,+ fetcher,+ { keepPreviousData: true },+ );++ const { postbackEventDetailsSheet, openWithEvent } =+ usePostbackEventDetailsSheet();++ const { openPostbackSecretModal, PostbackSecretModal } =+ usePostbackSecretModal();++ const { openEditPostbackModal, AddEditPostbackModal } =+ useAddEditPostbackModal(() => mutate(), openPostbackSecretModal);++ if (Boolean(error && (error as { status?: number }).status === 404)) {+ redirect("/profile/postbacks");+ }++ return (+ <>+ {AddEditPostbackModal}+ <PostbackSecretModal />+ {postbackEventDetailsSheet}+ <PageContent+ title="Postbacks"+ titleInfo={{+ title:+ "Receive HTTP requests when events like leads, sales, or commissions occur in your partner programs.",+ href: "https://dub.co/help",+ }}+ >+ <PageWidthWrapper className="grid max-w-screen-lg gap-8 pb-10">+ <BackLink href="/profile/postbacks">Back to postbacks</BackLink>+ {isLoading && !postback ? (+ <PostbackDetailSkeleton />+ ) : error || !postback ? (+ <div className="rounded-xl border border-neutral-200 py-10 text-center">+ <p className="text-sm text-red-600">+ {error instanceof Error ? error.message : "Postback not found"}+ </p>+ <button+ type="button"+ onClick={() => router.push("/profile/postbacks")}+ className="mt-2 text-sm font-medium text-neutral-700 underline"+ >+ Back to postbacks+ </button>+ </div>+ ) : (+ <>+ <div className="flex justify-between gap-8 sm:items-center">+ <div className="flex min-w-0 flex-col gap-3 sm:flex-row sm:items-center">+ <div className="w-fit flex-none rounded-md border border-neutral-200 bg-gradient-to-t from-neutral-100 p-2">+ <TokenAvatar id={postback.id} className="size-8" />+ </div>+ <div className="min-w-0">+ <div className="flex flex-wrap items-center gap-1">+ <span className="font-semibold text-neutral-700">+ {postback.name}+ </span>+ <PostbackStatus disabledAt={postback.disabledAt} />+ </div>+ <a+ href={postback.url}+ target="_blank"+ rel="noopener noreferrer"+ className="line-clamp-1 text-pretty break-all text-sm text-neutral-500 underline-offset-4 hover:text-neutral-700 hover:underline"+ >+ {postback.url}+ </a>+ </div>+ </div>++ <PostbackActions+ postback={postback}+ openPopover={openPopover}+ setOpenPopover={setOpenPopover}+ onEditPostback={openEditPostbackModal}+ onMutate={() => mutate()}+ />+ </div>++ <div className="space-y-4">+ <h2 className="text-sm font-medium">Events</h2>++ {isEventsLoading ? (+ <PostbackEventListSkeleton />+ ) : eventsError ? (+ <div className="rounded-xl border border-neutral-200 py-10 text-center">+ <p className="text-sm text-red-600">+ {eventsError instanceof Error+ ? eventsError.message+ : "Failed to load events"}+ </p>+ </div>+ ) : events && events.length === 0 ? (+ <div className="rounded-xl border border-neutral-200 py-10">+ <EmptyState+ icon={Webhook}+ title="No events"+ description="No events have been logged for this postback. Events will appear as they are logged."+ />+ </div>+ ) : (+ <PostbackEventList+ events={events || []}+ onEventClick={openWithEvent}+ />+ )}+ </div>+ </>+ )}+ </PageWidthWrapper>+ </PageContent>+ </>+ );+}diff --git a/apps/web/app/(ee)/partners.dub.co/(dashboard)/profile/postbacks/[id]/page.tsx b/apps/web/app/(ee)/partners.dub.co/(dashboard)/profile/postbacks/[id]/page.tsxnew file mode 100644index 0000000000..1058c9b72b--- /dev/null+++ b/apps/web/app/(ee)/partners.dub.co/(dashboard)/profile/postbacks/[id]/page.tsx@@ -0,0 +1,9 @@+import { PostbackDetailPageClient } from "./page-client";++export default async function PostbackDetailPage(props: {+ params: Promise<{ id: string }>;+}) {+ const { id } = await props.params;++ return <PostbackDetailPageClient postbackId={id} />;+}diff --git a/apps/web/app/(ee)/partners.dub.co/(dashboard)/profile/postbacks/add-postback-button.tsx b/apps/web/app/(ee)/partners.dub.co/(dashboard)/profile/postbacks/add-postback-button.tsxnew file mode 100644index 0000000000..8e3f5962b4--- /dev/null+++ b/apps/web/app/(ee)/partners.dub.co/(dashboard)/profile/postbacks/add-postback-button.tsx@@ -0,0 +1,14 @@+"use client";++import { Button } from "@dub/ui";++export function AddPostbackButton({ onClick }: { onClick: () => void }) {+ return (+ <Button+ className="flex h-10 items-center justify-center whitespace-nowrap rounded-lg border px-4 text-sm"+ text="Add Postback"+ onClick={onClick}+ aria-label="Add postback"+ />+ );+}diff --git a/apps/web/app/(ee)/partners.dub.co/(dashboard)/profile/postbacks/page-client.tsx b/apps/web/app/(ee)/partners.dub.co/(dashboard)/profile/postbacks/page-client.tsxnew file mode 100644index 0000000000..d82bd0306e--- /dev/null+++ b/apps/web/app/(ee)/partners.dub.co/(dashboard)/profile/postbacks/page-client.tsx@@ -0,0 +1,97 @@+"use client";++import { PostbackProps } from "@/lib/types";+import { PageContent } from "@/ui/layout/page-content";+import { PageWidthWrapper } from "@/ui/layout/page-width-wrapper";+import { useAddEditPostbackModal } from "@/ui/postbacks/add-edit-postback-modal";+import { PostbackCard } from "@/ui/postbacks/postback-card";+import { PostbackPlaceholder } from "@/ui/postbacks/postback-placeholder";+import { usePostbackSecretModal } from "@/ui/postbacks/postback-secret-modal";+import EmptyState from "@/ui/shared/empty-state";+import { EmptyState as EmptyStateBlock } from "@dub/ui";+import { fetcher } from "@dub/utils";+import { AlertCircle, Webhook } from "lucide-react";+import useSWR from "swr";+import { AddPostbackButton } from "./add-postback-button";++export function PostbacksPageClient() {+ const {+ data: postbacks,+ error,+ isLoading,+ mutate,+ } = useSWR<PostbackProps[]>("/api/partner-profile/postbacks", fetcher, {+ keepPreviousData: true,+ });++ const { openPostbackSecretModal, PostbackSecretModal } =+ usePostbackSecretModal();++ const { openAddPostbackModal, AddEditPostbackModal } =+ useAddEditPostbackModal(() => mutate(), openPostbackSecretModal);++ return (+ <>+ <PageContent+ title="Postbacks"+ titleInfo={{+ title:+ "Receive HTTP requests when events like leads, sales, or commissions occur in your partner programs.",+ href: "https://dub.co/help",+ }}+ controls={<AddPostbackButton onClick={openAddPostbackModal} />}+ >+ <PageWidthWrapper>+ <div className="grid gap-5">+ <div className="animate-fade-in">+ {isLoading ? (+ <div className="grid grid-cols-1 gap-3">+ {Array.from({ length: 3 }).map((_, idx) => (+ <PostbackPlaceholder key={idx} />+ ))}+ </div>+ ) : error ? (+ <div className="flex flex-col items-center gap-4 rounded-xl border border-neutral-200 py-10">+ <EmptyStateBlock+ icon={AlertCircle}+ title="Failed to load postbacks"+ description={+ error instanceof Error+ ? error.message+ : "Something went wrong. Please try again."+ }+ >+ <button+ type="button"+ onClick={() => mutate()}+ className="flex h-8 items-center justify-center gap-2 rounded-md border border-neutral-200 bg-white px-4 text-sm font-medium text-neutral-700 transition-colors hover:bg-neutral-50"+ >+ Try again+ </button>+ </EmptyStateBlock>+ </div>+ ) : postbacks && postbacks.length > 0 ? (+ <div className="grid grid-cols-1 gap-3">+ {postbacks.map((postback) => (+ <PostbackCard key={postback.id} {...postback} />+ ))}+ </div>+ ) : (+ <div className="flex flex-col items-center gap-4 rounded-xl border border-neutral-200 py-10">+ <EmptyState+ icon={Webhook}+ title="You haven't set up any postbacks yet."+ description="Postbacks allow you to receive HTTP requests when events like leads, sales, or commissions occur in your partner programs."+ learnMore="https://d.to/postbacks"+ />+ </div>+ )}+ </div>+ </div>+ </PageWidthWrapper>+ </PageContent>+ {AddEditPostbackModal}+ <PostbackSecretModal />+ </>+ );+}diff --git a/apps/web/app/(ee)/partners.dub.co/(dashboard)/profile/postbacks/page.tsx b/apps/web/app/(ee)/partners.dub.co/(dashboard)/profile/postbacks/page.tsxnew file mode 100644index 0000000000..379a1b6940--- /dev/null+++ b/apps/web/app/(ee)/partners.dub.co/(dashboard)/profile/postbacks/page.tsx@@ -0,0 +1,5 @@+import { PostbacksPageClient } from "./page-client";++export default function PostbacksPage() {+ return <PostbacksPageClient />;+}diff --git a/apps/web/app/api/postbacks/callback/route.ts b/apps/web/app/api/postbacks/callback/route.tsnew file mode 100644index 0000000000..c250cdb4fd--- /dev/null+++ b/apps/web/app/api/postbacks/callback/route.ts@@ -0,0 +1,67 @@+import { verifyQstashSignature } from "@/lib/cron/verify-qstash";+import { recordPostbackEvent } from "@/lib/postback/api/record-postback-event";+import {+ postbackCallbackBodySchema,+ postbackCallbackParamsSchema,+} from "@/lib/postback/schemas";+import { prisma } from "@dub/prisma";+import { getSearchParams } from "@dub/utils";+import { logAndRespond } from "app/(ee)/api/cron/utils";++// POST /api/postbacks/callback - callback from QStash+export const POST = async (req: Request) => {+ const rawBody = await req.text();++ await verifyQstashSignature({+ req,+ rawBody,+ });++ const { status, url, sourceMessageId, body, sourceBody, retried } =+ postbackCallbackBodySchema.parse(JSON.parse(rawBody));++ const { postbackId, eventId, event } = postbackCallbackParamsSchema.parse(+ getSearchParams(req.url),+ );++ const postback = await prisma.postback.findUnique({+ where: {+ id: postbackId,+ },+ select: {+ id: true,+ },+ });++ if (!postback) {+ return logAndRespond(`Postback ${postbackId} not found.`);+ }++ const request = Buffer.from(sourceBody, "base64").toString("utf-8");+ const response = Buffer.from(body, "base64").toString("utf-8");++ const tbResponse = await recordPostbackEvent({+ event_id: eventId,+ postback_id: postbackId,+ message_id: sourceMessageId,+ event,+ url,+ response_status: status === -1 ? 503 : status,+ request_body: request,+ response_body: response,+ retry_attempt: retried,+ });++ if (tbResponse.successful_rows === 0) {+ return logAndRespond(+ `Failed to record event ${eventId} for postback ${postbackId}.`,+ {+ status: 400,+ },+ );+ }++ return logAndRespond(+ `Event ${eventId} for postback ${postbackId} processed.`,+ );+};diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/webhooks/[webhookId]/page-client.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/webhooks/[webhookId]/page-client.tsxindex 9849fafd4b..831be196c0 100644--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/webhooks/[webhookId]/page-client.tsx+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/webhooks/[webhookId]/page-client.tsx@@ -3,10 +3,11 @@import { clientAccessCheck } from "@/lib/client-access-check";import useWorkspace from "@/lib/swr/use-workspace";import { WebhookEventProps } from "@/lib/types";+import { PageWidthWrapper } from "@/ui/layout/page-width-wrapper";import { WebhookEventListSkeleton } from "@/ui/webhooks/loading-events-skelton";import { NoEventsPlaceholder } from "@/ui/webhooks/no-events-placeholder";-import { WebhookEventList } from "@/ui/webhooks/webhook-events";-import { MaxWidthWrapper } from "@dub/ui";+import { useWebhookEventDetailsSheet } from "@/ui/webhooks/webhook-event-details-sheet";+import { WebhookEventList } from "@/ui/webhooks/webhook-event-list";import { fetcher } from "@dub/utils";import { redirect } from "next/navigation";import useSWR from "swr";@@ -36,15 +37,19 @@ export default function WebhookLogsPageClient({},);+ const { webhookEventDetailsSheet, openWithEvent } =+ useWebhookEventDetailsSheet();+return (- <MaxWidthWrapper className="max-w-screen-lg space-y-6">+ <PageWidthWrapper className="grid max-w-screen-lg gap-8 pb-10">+ {webhookEventDetailsSheet}{isLoading ? (<WebhookEventListSkeleton />) : events && events.length === 0 ? (<NoEventsPlaceholder />) : (- <WebhookEventList events={events || []} />+ <WebhookEventList events={events || []} onEventClick={openWithEvent} />)}- </MaxWidthWrapper>+ </PageWidthWrapper>);}diff --git a/apps/web/lib/api/conversions/track-lead.ts b/apps/web/lib/api/conversions/track-lead.tsindex c3c9e005ec..11c8beee3d 100644--- a/apps/web/lib/api/conversions/track-lead.ts+++ b/apps/web/lib/api/conversions/track-lead.ts@@ -4,6 +4,7 @@ import { detectAndRecordFraudEvent } from "@/lib/api/fraud/detect-record-fraud-eimport { includeTags } from "@/lib/api/links/include-tags";import { generateRandomName } from "@/lib/names";import { createPartnerCommission } from "@/lib/partners/create-partner-commission";+import { sendPartnerPostback } from "@/lib/postback/api/send-partner-postback";import { isStored, storage } from "@/lib/storage";import { getClickEvent, recordLead } from "@/lib/tinybird";import { logConversionEvent } from "@/lib/tinybird/log-conversion-events";@@ -359,18 +360,35 @@ export const trackLead = async ({]);}- await sendWorkspaceWebhook({- trigger: "lead.created",- data: transformLeadEventData({- ...clickData,- eventName,- link,- customer,- partner: createdCommission?.webhookPartner,- metadata,+ await Promise.allSettled([+ sendWorkspaceWebhook({+ trigger: "lead.created",+ data: transformLeadEventData({+ ...clickData,+ eventName,+ link,+ customer,+ partner: createdCommission?.webhookPartner,+ metadata,+ }),+ workspace,}),- workspace,- });++ ...(link.partnerId+ ? [+ sendPartnerPostback({+ partnerId: link.partnerId,+ event: "lead.created",+ data: {+ ...clickData,+ eventName,+ link,+ customer,+ },+ }),+ ]+ : []),+ ]);}})(),);diff --git a/apps/web/lib/api/conversions/track-sale.ts b/apps/web/lib/api/conversions/track-sale.tsindex c7264a344c..31b4562ab0 100644--- a/apps/web/lib/api/conversions/track-sale.ts+++ b/apps/web/lib/api/conversions/track-sale.ts@@ -5,6 +5,7 @@ import { detectAndRecordFraudEvent } from "@/lib/api/fraud/detect-record-fraud-eimport { includeTags } from "@/lib/api/links/include-tags";import { generateRandomName } from "@/lib/names";import { createPartnerCommission } from "@/lib/partners/create-partner-commission";+import { sendPartnerPostback } from "@/lib/postback/api/send-partner-postback";import { isStored, storage } from "@/lib/storage";import {getClickEvent,@@ -378,18 +379,31 @@ const _trackLead = async ({]);}- // Send workspace webhook- const webhookPayload = transformLeadEventData({- ...leadEventData,- link,- customer,- });+ await Promise.allSettled([+ sendWorkspaceWebhook({+ trigger: "lead.created",+ data: transformLeadEventData({+ ...leadEventData,+ link,+ customer,+ }),+ workspace,+ }),- await sendWorkspaceWebhook({- trigger: "lead.created",- data: webhookPayload,- workspace,- });+ ...(link.partnerId+ ? [+ sendPartnerPostback({+ partnerId: link.partnerId,+ event: "lead.created",+ data: {+ ...leadEventData,+ link,+ customer,+ },+ }),+ ]+ : []),+ ]);})(),);};@@ -460,7 +474,6 @@ const _trackSale = async ({currency,invoice_id: invoiceId || "",metadata: metadata ? JSON.stringify(metadata) : "",- timestamp: undefined,};const firstConversionFlag = isFirstConversion({@@ -472,7 +485,10 @@ const _trackSale = async ({(async () => {const [_sale, link] = await Promise.all([// Record sale event- recordSale(saleData),+ recordSale({+ ...saleData,+ timestamp: undefined,+ }),// Update link conversions, sales, and saleAmountprisma.link.update({@@ -584,21 +600,35 @@ const _trackSale = async ({]);}- // Send workspace webhook- const webhookPayload = transformSaleEventData({- ...saleData,- clickedAt: customer.clickedAt || customer.createdAt,- link,- customer,- partner: createdCommission?.webhookPartner,- metadata,- });+ await Promise.allSettled([+ sendWorkspaceWebhook({+ trigger: "sale.created",+ data: transformSaleEventData({+ ...saleData,+ clickedAt: customer.clickedAt || customer.createdAt,+ link,+ customer,+ partner: createdCommission?.webhookPartner,+ metadata,+ }),+ workspace,+ }),- await sendWorkspaceWebhook({- trigger: "sale.created",- data: webhookPayload,- workspace,- });+ ...(link.partnerId+ ? [+ sendPartnerPostback({+ partnerId: link.partnerId,+ event: "sale.created",+ data: {+ ...saleData,+ clickedAt: customer.clickedAt || customer.createdAt,+ link,+ customer,+ },+ }),+ ]+ : []),+ ]);// Update customer stats + program/partner associationsawait prisma.customer.update({diff --git a/apps/web/lib/api/create-id.ts b/apps/web/lib/api/create-id.tsindex 9ad67fa22f..1931d5c55c 100644--- a/apps/web/lib/api/create-id.ts+++ b/apps/web/lib/api/create-id.ts@@ -42,6 +42,7 @@ const prefixes = ["fre_", // fraud event"frg_", // fraud event group"ref_", // referral+ "pb_", // partner postback] as const;// ULID uses base32 encodingdiff --git a/apps/web/lib/api/partner-profile/client.ts b/apps/web/lib/api/partner-profile/client.tsnew file mode 100644index 0000000000..1e13f6fa4f--- /dev/null+++ b/apps/web/lib/api/partner-profile/client.ts@@ -0,0 +1,73 @@+import {+ createPostbackInputSchema,+ createPostbackOutputSchema,+ postbackSchema,+ sendTestPostbackInputSchema,+ updatePostbackInputSchema,+} from "@/lib/postback/schemas";+import { createFetch, createSchema } from "@better-fetch/fetch";+import * as z from "zod/v4";++export const partnerProfileFetch = createFetch({+ baseURL: "",+ credentials: "include",+ schema: createSchema(+ {+ // Create postback+ "/api/partner-profile/postbacks": {+ method: "post",+ body: createPostbackInputSchema,+ output: createPostbackOutputSchema,+ },++ // Get postback+ "@get/api/partner-profile/postbacks/:postbackId": {+ params: z.object({+ postbackId: z.string(),+ }),+ output: postbackSchema,+ },++ // Update postback+ "@patch/api/partner-profile/postbacks/:postbackId": {+ params: z.object({+ postbackId: z.string(),+ }),+ body: updatePostbackInputSchema,+ output: postbackSchema,+ },++ // Delete postback+ "@delete/api/partner-profile/postbacks/:postbackId": {+ params: z.object({+ postbackId: z.string(),+ }),+ output: z.object({+ id: z.string(),+ }),+ },++ // Rotate postback secret+ "@post/api/partner-profile/postbacks/:postbackId/rotate-secret": {+ params: z.object({+ postbackId: z.string(),+ }),+ output: z.object({+ secret: z.string(),+ }),+ },++ // Send test postback event+ "@post/api/partner-profile/postbacks/:postbackId/send-test": {+ params: z.object({+ postbackId: z.string(),+ }),+ body: sendTestPostbackInputSchema,+ output: z.object({}),+ },+ },+ {+ strict: true,+ },+ ),+});diff --git a/apps/web/lib/api/postbacks/get-postback-or-throw.ts b/apps/web/lib/api/postbacks/get-postback-or-throw.tsnew file mode 100644index 0000000000..541d97eb06--- /dev/null+++ b/apps/web/lib/api/postbacks/get-postback-or-throw.ts@@ -0,0 +1,34 @@+import { prisma } from "@dub/prisma";+import { DubApiError } from "../errors";++interface GetPostbackOrThrowParams {+ postbackId: string;+ partnerId: string;+}++export const getPostbackOrThrow = async ({+ postbackId,+ partnerId,+}: GetPostbackOrThrowParams) => {+ const postback = await prisma.postback.findUnique({+ where: {+ id: postbackId,+ },+ });++ if (!postback) {+ throw new DubApiError({+ code: "not_found",+ message: "Postback not found.",+ });+ }++ if (postback.partnerId !== partnerId) {+ throw new DubApiError({+ code: "forbidden",+ message: "Postback does not belong to your partner profile.",+ });+ }++ return postback;+};diff --git a/apps/web/lib/auth/partner-users/partner-user-permissions.ts b/apps/web/lib/auth/partner-users/partner-user-permissions.tsindex b453d7eb02..e271af335e 100644--- a/apps/web/lib/auth/partner-users/partner-user-permissions.ts+++ b/apps/web/lib/auth/partner-users/partner-user-permissions.ts@@ -10,6 +10,8 @@ const PERMISSIONS = ["user_invites.update","partner_profile.update","payout_settings.update",+ "postbacks.read",+ "postbacks.write",] as const;const ROLE_PERMISSIONS: Record<PartnerRole, Permission[]> = {@@ -21,6 +23,8 @@ const ROLE_PERMISSIONS: Record<PartnerRole, Permission[]> = {"user_invites.update","partner_profile.update","payout_settings.update",+ "postbacks.read",+ "postbacks.write",],member: [],} as const;diff --git a/apps/web/lib/auth/partner.ts b/apps/web/lib/auth/partner.tsindex 493505e819..e80ae2f2f7 100644--- a/apps/web/lib/auth/partner.ts+++ b/apps/web/lib/auth/partner.ts@@ -1,11 +1,12 @@import { DubApiError, handleAndReturnErrorResponse } from "@/lib/api/errors";import { withAxiom } from "@/lib/axiom/server";-import { PartnerProps } from "@/lib/types";+import { PartnerBetaFeatures, PartnerProps } from "@/lib/types";import { prisma } from "@dub/prisma";import { PartnerUser } from "@dub/prisma/client";import { getSearchParams, PARTNERS_DOMAIN } from "@dub/utils";import { waitUntil } from "@vercel/functions";import { headers } from "next/headers";+import { getPartnerFeatureFlags } from "../edge-config";import { ratelimit } from "../upstash";import { partnerPlatformSchema } from "../zod/schemas/partners";import { hashToken } from "./hash-token";@@ -37,6 +38,7 @@ interface WithPartnerProfileHandler {interface WithPartnerProfileOptions {requiredPermission?: Permission;+ featureFlag?: PartnerBetaFeatures;}const RATE_LIMIT_FOR_PARTNERS = {@@ -52,7 +54,7 @@ const RATE_LIMIT_FOR_PARTNERS = {export const withPartnerProfile = (handler: WithPartnerProfileHandler,- { requiredPermission }: WithPartnerProfileOptions = {},+ { requiredPermission, featureFlag }: WithPartnerProfileOptions = {},) => {return withAxiom(async (@@ -240,6 +242,18 @@ export const withPartnerProfile = (});}+ // Beta feature checks+ if (featureFlag) {+ const flags = await getPartnerFeatureFlags(partnerUser.partner.id);++ if (!flags[featureFlag]) {+ throw new DubApiError({+ code: "forbidden",+ message: "Unauthorized: Beta feature.",+ });+ }+ }+const {industryInterests,preferredEarningStructures,diff --git a/apps/web/lib/auth/workspace.ts b/apps/web/lib/auth/workspace.tsindex d119a39f84..11ff92f775 100644--- a/apps/web/lib/auth/workspace.ts+++ b/apps/web/lib/auth/workspace.ts@@ -431,7 +431,7 @@ export const withWorkspace = (// beta feature checksif (featureFlag) {- let flags = await getFeatureFlags({+ const flags = await getFeatureFlags({workspaceId: workspace.id,});diff --git a/apps/web/lib/edge-config/get-partner-feature-flags.ts b/apps/web/lib/edge-config/get-partner-feature-flags.tsnew file mode 100644index 0000000000..93ca991a6c--- /dev/null+++ b/apps/web/lib/edge-config/get-partner-feature-flags.ts@@ -0,0 +1,38 @@+import { get } from "@vercel/edge-config";+import { PartnerBetaFeatures } from "../types";++type PartnerBetaFeaturesRecord = Record<PartnerBetaFeatures, string[]>;++export const getPartnerFeatureFlags = async (partnerId: string) => {+ const partnerFeatures: Record<PartnerBetaFeatures, boolean> = {+ postbacks: false,+ };++ // Return all features as true if edge config is not available+ if (!process.env.EDGE_CONFIG) {+ return Object.fromEntries(+ Object.entries(partnerFeatures).map(([key, _v]) => [key, true]),+ );+ }++ let betaFeatures: PartnerBetaFeaturesRecord | undefined = undefined;++ try {+ betaFeatures = await get("partnerBetaFeatures");+ } catch (e) {+ console.error(`Error getting partner beta features: ${e}`);+ }++ if (!betaFeatures) {+ return partnerFeatures;+ }++ // It should be in the format of { postbacks: ["pn_1", "pn_2"] }+ for (const [featureFlag, partnerIds] of Object.entries(betaFeatures)) {+ if (partnerIds.includes(partnerId)) {+ partnerFeatures[featureFlag] = true;+ }+ }++ return partnerFeatures;+};diff --git a/apps/web/lib/edge-config/index.ts b/apps/web/lib/edge-config/index.tsindex 7627038a03..1b77e1d99d 100644--- a/apps/web/lib/edge-config/index.ts+++ b/apps/web/lib/edge-config/index.ts@@ -1,4 +1,5 @@export * from "./get-feature-flags";+export * from "./get-partner-feature-flags";export * from "./is-blacklisted-domain";export * from "./is-blacklisted-email";export * from "./is-blacklisted-key";diff --git a/apps/web/lib/integrations/shopify/create-lead.ts b/apps/web/lib/integrations/shopify/create-lead.tsindex de652f464d..298322e944 100644--- a/apps/web/lib/integrations/shopify/create-lead.ts+++ b/apps/web/lib/integrations/shopify/create-lead.ts@@ -3,6 +3,7 @@ import { DubApiError } from "@/lib/api/errors";import { includeTags } from "@/lib/api/links/include-tags";import { syncPartnerLinksStats } from "@/lib/api/partners/sync-partner-links-stats";import { generateRandomName } from "@/lib/names";+import { sendPartnerPostback } from "@/lib/postback/api/send-partner-postback";import { getClickEvent, recordLead } from "@/lib/tinybird";import { sendWorkspaceWebhook } from "@/lib/webhook/publish";import { transformLeadEventData } from "@/lib/webhook/transform";@@ -116,6 +117,22 @@ export async function createShopifyLead({metadata: null,}),}),++ ...(link.partnerId+ ? [+ sendPartnerPostback({+ partnerId: link.partnerId,+ event: "lead.created",+ data: {+ ...clickData,+ eventName,+ link,+ customer,+ },+ }),+ ]+ : []),+...(link.programId && link.partnerId? [syncPartnerLinksStats({diff --git a/apps/web/lib/integrations/shopify/create-sale.ts b/apps/web/lib/integrations/shopify/create-sale.tsindex b06d39ad95..5120a8e501 100644--- a/apps/web/lib/integrations/shopify/create-sale.ts+++ b/apps/web/lib/integrations/shopify/create-sale.ts@@ -4,6 +4,7 @@ import { includeTags } from "@/lib/api/links/include-tags";import { syncPartnerLinksStats } from "@/lib/api/partners/sync-partner-links-stats";import { executeWorkflows } from "@/lib/api/workflows/execute-workflows";import { createPartnerCommission } from "@/lib/partners/create-partner-commission";+import { sendPartnerPostback } from "@/lib/postback/api/send-partner-postback";import { recordSale } from "@/lib/tinybird";import { LeadEventTB } from "@/lib/types";import { redis } from "@/lib/upstash";@@ -198,17 +199,34 @@ export async function createShopifySale({}waitUntil(- sendWorkspaceWebhook({- trigger: "sale.created",- workspace,- data: transformSaleEventData({- ...saleData,- link,- clickedAt: customer.clickedAt || customer.createdAt,- customer,- partner: createdCommission?.webhookPartner,- metadata: null,+ Promise.allSettled([+ sendWorkspaceWebhook({+ trigger: "sale.created",+ workspace,+ data: transformSaleEventData({+ ...saleData,+ link,+ clickedAt: customer.clickedAt || customer.createdAt,+ customer,+ partner: createdCommission?.webhookPartner,+ metadata: null,+ }),}),- }),++ ...(link?.partnerId+ ? [+ sendPartnerPostback({+ partnerId: link.partnerId,+ event: "sale.created",+ data: {+ ...saleData,+ clickedAt: customer.clickedAt || customer.createdAt,+ link,+ customer,+ },+ }),+ ]+ : []),+ ]),);}diff --git a/apps/web/lib/partners/create-partner-commission.ts b/apps/web/lib/partners/create-partner-commission.tsindex dfd6f7d94d..6fa55dbdef 100644--- a/apps/web/lib/partners/create-partner-commission.ts+++ b/apps/web/lib/partners/create-partner-commission.ts@@ -18,6 +18,7 @@ import { getProgramEnrollmentOrThrow } from "../api/programs/get-program-enrollmimport { calculateSaleEarnings } from "../api/sales/calculate-sale-earnings";import { executeWorkflows } from "../api/workflows/execute-workflows";import { Session } from "../auth";+import { sendPartnerPostback } from "../postback/api/send-partner-postback";import { RewardContext, RewardProps } from "../types";import { sendWorkspaceWebhook } from "../webhook/publish";import { CommissionWebhookSchema } from "../zod/schemas/commissions";@@ -357,6 +358,15 @@ export const createPartnerCommission = async ({}),}),+ sendPartnerPostback({+ partnerId,+ event: "commission.created",+ data: {+ ...commission,+ customer: commission.customer,+ },+ }),+syncTotalCommissions({partnerId,programId,diff --git a/apps/web/lib/partnerstack/update-stripe-customers.ts b/apps/web/lib/partnerstack/update-stripe-customers.tsindex b5579a67f8..20cb9fa492 100644--- a/apps/web/lib/partnerstack/update-stripe-customers.ts+++ b/apps/web/lib/partnerstack/update-stripe-customers.ts@@ -182,8 +182,7 @@ async function searchStripeAndUpdateCustomer({} else {// look for the one with subscriptionsconst customerWithSubcription = stripeCustomers.data.find(- ({ subscriptions }) =>- subscriptions && subscriptions.data.length > 0,+ ({ subscriptions }) => subscriptions && subscriptions.data.length > 0,);if (customerWithSubcription) {diff --git a/apps/web/lib/postback/api/get-postback-events.ts b/apps/web/lib/postback/api/get-postback-events.tsnew file mode 100644index 0000000000..6340d49b8d--- /dev/null+++ b/apps/web/lib/postback/api/get-postback-events.ts@@ -0,0 +1,11 @@+import { postbackEventOutputSchemaTB } from "@/lib/postback/schemas";+import * as z from "zod/v4";+import { tb } from "../../tinybird/client";++export const getPostbackEvents = tb.buildPipe({+ pipe: "get_postback_events",+ parameters: z.object({+ postbackId: z.string(),+ }),+ data: postbackEventOutputSchemaTB,+});diff --git a/apps/web/lib/postback/api/postback-adapter-custom.ts b/apps/web/lib/postback/api/postback-adapter-custom.tsnew file mode 100644index 0000000000..122d346b3c--- /dev/null+++ b/apps/web/lib/postback/api/postback-adapter-custom.ts@@ -0,0 +1,31 @@+import { Postback } from "@dub/prisma/client";+import { PostbackAdapter, PostbackPayload } from "./postback-adapters";++export class PostbackCustomAdapter extends PostbackAdapter {+ constructor(postback: Postback) {+ super(postback);+ }++ protected registerEventTransformers() {+ this.eventTransformers.register("lead.created", {+ transform: (payload) => this.formatPayload(payload),+ });++ this.eventTransformers.register("sale.created", {+ transform: (payload) => this.formatPayload(payload),+ });++ this.eventTransformers.register("commission.created", {+ transform: (payload) => this.formatPayload(payload),+ });+ }++ private formatPayload(payload: PostbackPayload) {+ return {+ id: payload.eventId,+ event: payload.event,+ createdAt: payload.createdAt,+ data: payload.data,+ };+ }+}diff --git a/apps/web/lib/postback/api/postback-adapter-slack.ts b/apps/web/lib/postback/api/postback-adapter-slack.tsnew file mode 100644index 0000000000..9f04e2986f--- /dev/null+++ b/apps/web/lib/postback/api/postback-adapter-slack.ts@@ -0,0 +1,57 @@+import { PostbackTrigger } from "@/lib/types";+import { Postback } from "@dub/prisma/client";+import type { z } from "zod/v4";+import {+ commissionEventPostbackSchema,+ leadEventPostbackSchema,+ saleEventPostbackSchema,+} from "../schemas";+import { PostbackAdapter } from "./postback-adapters";++type LeadEventPostback = z.infer<typeof leadEventPostbackSchema>;+type SaleEventPostback = z.infer<typeof saleEventPostbackSchema>;+type CommissionEventPostback = z.infer<typeof commissionEventPostbackSchema>;++interface PostbackPayload<T extends Record<string, unknown>> {+ eventId: string;+ event: PostbackTrigger;+ createdAt: string;+ data: T;+}++export class PostbackSlackAdapter extends PostbackAdapter {+ constructor(postback: Postback) {+ super(postback);+ }++ protected registerEventTransformers() {+ this.eventTransformers.register("lead.created", {+ transform: ({ data }: PostbackPayload<LeadEventPostback>) => {+ throw Error("Not implemented.");+ },+ });++ this.eventTransformers.register("sale.created", {+ transform: ({ data }: PostbackPayload<SaleEventPostback>) => {+ throw Error("Not implemented.");+ },+ });++ this.eventTransformers.register("commission.created", {+ transform: ({ data }: PostbackPayload<CommissionEventPostback>) => {+ throw Error("Not implemented.");+ },+ });+ }+}++function escapeSlackText(value: string | null | undefined) {+ if (value == null) {+ return "";+ }++ return value+ .replace(/&/g, "&")+ .replace(/</g, "<")+ .replace(/>/g, ">");+}diff --git a/apps/web/lib/postback/api/postback-adapters.ts b/apps/web/lib/postback/api/postback-adapters.tsnew file mode 100644index 0000000000..f29f2da417--- /dev/null+++ b/apps/web/lib/postback/api/postback-adapters.ts@@ -0,0 +1,79 @@+import { qstash } from "@/lib/cron";+import { PostbackTrigger } from "@/lib/types";+import { createWebhookSignature } from "@/lib/webhook/signature";+import { Postback } from "@dub/prisma/client";+import { APP_DOMAIN_WITH_NGROK } from "@dub/utils";+import { PostbackEventTransformers } from "./postback-event-transformers";++export interface PostbackPayload {+ eventId: string;+ event: PostbackTrigger;+ createdAt: string;+ data: unknown;+}++export abstract class PostbackAdapter {+ protected eventTransformers = new PostbackEventTransformers();++ constructor(protected postback: Postback) {+ this.registerEventTransformers();+ }++ protected abstract registerEventTransformers(): void;++ async execute(payload: PostbackPayload) {+ const transformedPayload = this.eventTransformers.transform(payload);++ if (!transformedPayload) {+ return;+ }++ const searchParams = {+ postbackId: this.postback.id,+ eventId: payload.eventId,+ event: payload.event,+ };++ const callbackUrl = buildCallbackUrl(+ `${APP_DOMAIN_WITH_NGROK}/api/postbacks/callback`,+ searchParams,+ );++ const signature = await createWebhookSignature(+ this.postback.secret,+ transformedPayload,+ );++ const response = await qstash.publishJSON({+ callback: callbackUrl.href,+ failureCallback: callbackUrl.href,+ url: this.postback.url,+ body: transformedPayload,+ headers: {+ "Dub-Signature": signature,+ "Upstash-Hide-Headers": "true",+ },+ });++ if (!response.messageId) {+ console.error("Failed to publish postback event to QStash", response);+ }++ if (process.env.NODE_ENV === "development") {+ console.debug("Published postback event to QStash", {+ ...response,+ payload: transformedPayload,+ });+ }+ }+}++function buildCallbackUrl(base: string, params: Record<string, string>): URL {+ const url = new URL(base);++ Object.entries(params).forEach(([key, value]) => {+ url.searchParams.append(key, value);+ });++ return url;+}diff --git a/apps/web/lib/postback/api/postback-event-enrichers.ts b/apps/web/lib/postback/api/postback-event-enrichers.tsnew file mode 100644index 0000000000..6e6b5db91d--- /dev/null+++ b/apps/web/lib/postback/api/postback-event-enrichers.ts@@ -0,0 +1,93 @@+import { transformLink } from "@/lib/api/links";+import { PostbackTrigger } from "@/lib/types";+import { toCamelCase } from "@dub/utils";+import {+ commissionEventPostbackSchema,+ leadEventPostbackSchema,+ saleEventPostbackSchema,+} from "../schemas";++interface PostbackEventEnricher {+ enrich(data: Record<string, unknown>): Record<string, unknown>;+}++class PostbackEventEnrichers {+ private enrichers = new Map<PostbackTrigger, PostbackEventEnricher>();++ register(event: PostbackTrigger, enricher: PostbackEventEnricher) {+ if (this.enrichers.has(event)) {+ console.warn(+ `[PostbackEventEnrichers] Overwriting enricher for event ${event}.`,+ );+ }++ this.enrichers.set(event, enricher);++ return this;+ }++ enrich(event: PostbackTrigger, data: Record<string, unknown>) {+ const enricher = this.enrichers.get(event);++ if (!enricher) {+ throw new Error(+ `[PostbackEventEnrichers] No enricher registered for event ${event}.`,+ );+ }++ return enricher.enrich(data);+ }++ has(event: PostbackTrigger) {+ return this.enrichers.has(event);+ }+}++// Register event enrichers for each event type+export const postbackEventEnrichers = new PostbackEventEnrichers();++postbackEventEnrichers.register("lead.created", {+ enrich: (data) => {+ const lead: any = Object.fromEntries(+ Object.entries(data).map(([key, value]) => [toCamelCase(key), value]),+ );++ return leadEventPostbackSchema.parse({+ ...lead,+ link: transformLink(lead.link),+ click: {+ ...lead,+ id: lead.clickId,+ timestamp: new Date(lead.timestamp + "Z"),+ },+ customer: lead.customer,+ });+ },+});++postbackEventEnrichers.register("sale.created", {+ enrich: (data) => {+ const sale: any = Object.fromEntries(+ Object.entries(data).map(([key, value]) => [toCamelCase(key), value]),+ );++ return saleEventPostbackSchema.parse({+ ...sale,+ link: transformLink(sale.link),+ click: {+ ...sale,+ id: sale.clickId,+ timestamp: new Date(sale.clickedAt + "Z"),+ },+ customer: sale.customer,+ sale: {+ amount: sale.amount,+ currency: sale.currency,+ },+ });+ },+});++postbackEventEnrichers.register("commission.created", {+ enrich: (data) => commissionEventPostbackSchema.parse(data),+});diff --git a/apps/web/lib/postback/api/postback-event-transformers.ts b/apps/web/lib/postback/api/postback-event-transformers.tsnew file mode 100644index 0000000000..2df2c683b9--- /dev/null+++ b/apps/web/lib/postback/api/postback-event-transformers.ts@@ -0,0 +1,42 @@+import { PostbackTrigger } from "@/lib/types";++interface PostbackPayload {+ eventId: string;+ event: PostbackTrigger;+ createdAt: string;+ data: unknown;+}++interface PostbackEventTransformer {+ transform(payload: PostbackPayload): unknown;+}++export class PostbackEventTransformers {+ private transformers = new Map<PostbackTrigger, PostbackEventTransformer>();++ register(event: PostbackTrigger, transformer: PostbackEventTransformer) {+ if (this.transformers.has(event)) {+ console.warn(+ `[PostbackEventTransformers] Overwriting transformer for event ${event}.`,+ );+ }++ this.transformers.set(event, transformer);++ return this;+ }++ transform(payload: PostbackPayload) {+ const transformer = this.transformers.get(payload.event);++ if (!transformer) {+ console.warn(+ `[PostbackEventTransformers] No transformer found for event ${payload.event}.`,+ );++ return null;+ }++ return transformer.transform(payload);+ }+}diff --git a/apps/web/lib/postback/api/record-postback-event.ts b/apps/web/lib/postback/api/record-postback-event.tsnew file mode 100644index 0000000000..7dac12df7c--- /dev/null+++ b/apps/web/lib/postback/api/record-postback-event.ts@@ -0,0 +1,7 @@+import { postbackEventInputSchemaTB } from "@/lib/postback/schemas";+import { tb } from "../../tinybird/client";++export const recordPostbackEvent = tb.buildIngestEndpoint({+ datasource: "dub_postback_events",+ event: postbackEventInputSchemaTB.omit({ timestamp: true }),+});diff --git a/apps/web/lib/postback/api/send-partner-postback.ts b/apps/web/lib/postback/api/send-partner-postback.tsnew file mode 100644index 0000000000..7eb03fc25a--- /dev/null+++ b/apps/web/lib/postback/api/send-partner-postback.ts@@ -0,0 +1,76 @@+import { POSTBACK_EVENT_ID_PREFIX } from "@/lib/postback/constants";+import { PostbackTrigger } from "@/lib/types";+import { prisma } from "@dub/prisma";+import { nanoid } from "@dub/utils";+import { PostbackCustomAdapter } from "./postback-adapter-custom";+import { PostbackSlackAdapter } from "./postback-adapter-slack";+import { postbackEventEnrichers } from "./postback-event-enrichers";++interface SendPartnerPostbackParams {+ partnerId: string;+ event: PostbackTrigger;+ data: Record<string, unknown>;+ skipEnrichment?: boolean; // Skip enrichment if the data is already enriched when sending a test event+ isTest?: boolean;+}++export const sendPartnerPostback = async ({+ partnerId,+ event,+ data,+ skipEnrichment = false,+ isTest = false,+}: SendPartnerPostbackParams) => {+ const postbacks = await prisma.postback.findMany({+ where: {+ partnerId,+ ...(isTest+ ? {} // include disabled+ : { disabledAt: null }),+ triggers: {+ array_contains: [event],+ },+ },+ });++ if (postbacks.length === 0) {+ console.log(+ `[sendPartnerPostback] No postbacks found for partner ${partnerId} for the event ${event}.`,+ );+ return;+ }++ let enrichedData: Record<string, unknown> | undefined;++ try {+ enrichedData =+ !skipEnrichment && postbackEventEnrichers.has(event)+ ? postbackEventEnrichers.enrich(event, data)+ : data;+ } catch (error) {+ console.error("[sendPartnerPostback] Error enriching data", error);+ return;+ }++ const adapters = postbacks.map((postback) => {+ switch (postback.receiver) {+ case "custom":+ return new PostbackCustomAdapter(postback);+ case "slack":+ return new PostbackSlackAdapter(postback);+ default:+ throw new Error(`Unknown postback receiver ${postback.receiver}`);+ }+ });++ await Promise.allSettled(+ adapters.map((adapter) =>+ adapter.execute({+ event,+ eventId: `${POSTBACK_EVENT_ID_PREFIX}${nanoid(25)}`,+ createdAt: new Date().toISOString(),+ data: enrichedData,+ }),+ ),+ );+};diff --git a/apps/web/lib/postback/api/utils.ts b/apps/web/lib/postback/api/utils.tsnew file mode 100644index 0000000000..82f790ebfe--- /dev/null+++ b/apps/web/lib/postback/api/utils.ts@@ -0,0 +1,12 @@+const POSTBACK_URL_RECEIVERS: Record<string, "slack" | "custom"> = {+ "hooks.slack.com": "slack",+};++export const identifyPostbackChannel = (url: string) => {+ try {+ const { hostname } = new URL(url);+ return POSTBACK_URL_RECEIVERS[hostname] ?? "custom";+ } catch {+ return "custom";+ }+};diff --git a/apps/web/lib/postback/constants.ts b/apps/web/lib/postback/constants.tsnew file mode 100644index 0000000000..c8887829b5--- /dev/null+++ b/apps/web/lib/postback/constants.ts@@ -0,0 +1,19 @@+export const POSTBACK_SECRET_LENGTH = 16;++export const POSTBACK_SECRET_PREFIX = "pbsec_";++export const POSTBACK_EVENT_ID_PREFIX = "evt_";++export const POSTBACK_TRIGGERS = [+ "lead.created",+ "sale.created",+ "commission.created",+] as const;++export const POSTBACK_TRIGGER_DESCRIPTIONS: Record<string, string> = {+ "lead.created": "Lead created",+ "sale.created": "Sale created",+ "commission.created": "Commission created",+};++export const MAX_POSTBACKS = 5;diff --git a/apps/web/lib/postback/sample-events/commission-created.json b/apps/web/lib/postback/sample-events/commission-created.jsonnew file mode 100644index 0000000000..ca153a9c69--- /dev/null+++ b/apps/web/lib/postback/sample-events/commission-created.json@@ -0,0 +1,24 @@+{+ "id": "cm_1K09DJTBCRT24P6BRD515CK29",+ "type": "sale",+ "amount": 50000,+ "earnings": 10000,+ "currency": "usd",+ "status": "pending",+ "description": null,+ "quantity": 1,+ "createdAt": "2025-07-16T10:48:14.722Z",+ "link": {+ "id": "cm0lcuvtz000xcutmqw4a7wi3",+ "shortLink": "https://dub.sh/track-test",+ "domain": "dub.sh",+ "key": "track-test"+ },+ "customer": {+ "id": "cus_1K09DJDEACR47NPYC93RM43WF",+ "country": "US",+ "createdAt": "2025-07-16T10:48:01.739Z",+ "firstSaleAt": "2025-07-18T10:48:01.739Z",+ "subscriptionCanceledAt": null+ }+}diff --git a/apps/web/lib/postback/sample-events/lead-created.json b/apps/web/lib/postback/sample-events/lead-created.jsonnew file mode 100644index 0000000000..2e5b375b22--- /dev/null+++ b/apps/web/lib/postback/sample-events/lead-created.json@@ -0,0 +1,32 @@+{+ "eventName": "Signup",+ "click": {+ "id": "GWGrkftJdYlZD2mq",+ "timestamp": "2025-02-03T09:35:57.926Z",+ "url": "https://github.com/dubinc/dub",+ "country": "US",+ "city": "San Jose",+ "region": "sfo1",+ "continent": "NA",+ "device": "Desktop",+ "browser": "Chrome",+ "os": "Mac OS",+ "referer": "(direct)",+ "refererUrl": "(direct)",+ "qr": false,+ "ip": "185.211.32.242"+ },+ "link": {+ "id": "cm0lcuvtz000xcutmqw4a7wi3",+ "shortLink": "https://dub.sh/track-test",+ "domain": "dub.sh",+ "key": "track-test"+ },+ "customer": {+ "id": "cus_1K09DJDEACR47NPYC93RM43WF",+ "country": "US",+ "createdAt": "2025-07-16T10:48:01.739Z",+ "firstSaleAt": "2025-07-18T10:48:01.739Z",+ "subscriptionCanceledAt": null+ }+}diff --git a/apps/web/lib/postback/sample-events/sale-created.json b/apps/web/lib/postback/sample-events/sale-created.jsonnew file mode 100644index 0000000000..7d160ae32b--- /dev/null+++ b/apps/web/lib/postback/sample-events/sale-created.json@@ -0,0 +1,36 @@+{+ "eventName": "Subscription",+ "click": {+ "id": "GWGrkftJdYlZD2mq",+ "timestamp": "2025-02-03T09:35:57.926Z",+ "url": "https://github.com/dubinc/dub",+ "country": "US",+ "city": "San Jose",+ "region": "sfo1",+ "continent": "NA",+ "device": "Desktop",+ "browser": "Chrome",+ "os": "Mac OS",+ "referer": "(direct)",+ "refererUrl": "(direct)",+ "qr": false,+ "ip": "185.211.32.242"+ },+ "link": {+ "id": "cm0lcuvtz000xcutmqw4a7wi3",+ "shortLink": "https://dub.sh/track-test",+ "domain": "dub.sh",+ "key": "track-test"+ },+ "customer": {+ "id": "cus_1K09DJDEACR47NPYC93RM43WF",+ "country": "US",+ "createdAt": "2025-07-16T10:48:01.739Z",+ "firstSaleAt": "2025-07-18T10:48:01.739Z",+ "subscriptionCanceledAt": null+ },+ "sale": {+ "amount": 100,+ "currency": "usd"+ }+}diff --git a/apps/web/lib/postback/schemas.ts b/apps/web/lib/postback/schemas.tsnew file mode 100644index 0000000000..2dd0a2864f--- /dev/null+++ b/apps/web/lib/postback/schemas.ts@@ -0,0 +1,129 @@+import { parseUrlSchema } from "@/lib/zod/schemas/utils";+import { PostbackReceiver } from "@dub/prisma/client";+import * as z from "zod/v4";+import { clickEventSchema } from "../zod/schemas/clicks";+import { CommissionSchema } from "../zod/schemas/commissions";+import { CustomerEnrichedSchema } from "../zod/schemas/customers";+import { LinkSchema } from "../zod/schemas/links";+import { POSTBACK_TRIGGERS } from "./constants";++export const postbackSchema = z.object({+ id: z.string(),+ name: z.string(),+ url: z.string(),+ triggers: z.array(z.enum(POSTBACK_TRIGGERS)),+ receiver: z.enum(PostbackReceiver),+ disabledAt: z.coerce.date().nullable(),+ createdAt: z.coerce.date(),+ updatedAt: z.coerce.date(),+});++export const createPostbackInputSchema = z.object({+ name: z+ .string()+ .min(1, "Name is required")+ .max(40, "Name must be less than 40 characters"),+ url: parseUrlSchema.refine((u) => u.startsWith("https://"), {+ message: "URL must use HTTPS",+ }),+ triggers: z+ .array(z.enum(POSTBACK_TRIGGERS))+ .min(1, "At least one trigger is required"),+});++export const createPostbackOutputSchema = z.object({+ ...postbackSchema.shape,+ secret: z.string(),+});++export const updatePostbackInputSchema = createPostbackInputSchema+ .partial()+ .extend({+ disabled: z.boolean().optional(),+ });++export const sendTestPostbackInputSchema = z.object({+ event: z.enum(POSTBACK_TRIGGERS),+});++// Postback event schemas+const postbackLinkSchema = LinkSchema.pick({+ id: true,+ shortLink: true,+ domain: true,+ key: true,+});++const postbackCustomerSchema = CustomerEnrichedSchema.pick({+ id: true,+ country: true,+ createdAt: true,+ firstSaleAt: true,+ subscriptionCanceledAt: true,+});++export const leadEventPostbackSchema = z.object({+ eventName: z.string(),+ click: clickEventSchema,+ link: postbackLinkSchema,+ customer: postbackCustomerSchema,+});++export const saleEventPostbackSchema = z.object({+ eventName: z.string(),+ click: clickEventSchema,+ link: postbackLinkSchema,+ customer: postbackCustomerSchema,+ sale: z.object({+ amount: z.number(),+ currency: z.string(),+ }),+});++export const commissionEventPostbackSchema = CommissionSchema.pick({+ id: true,+ type: true,+ amount: true,+ earnings: true,+ currency: true,+ status: true,+ description: true,+ quantity: true,+ createdAt: true,+}).extend({+ link: postbackLinkSchema.nullable(),+ customer: postbackCustomerSchema.nullable(),+});++export const postbackCallbackParamsSchema = z.object({+ postbackId: z.string(),+ eventId: z.string(),+ event: z.enum(POSTBACK_TRIGGERS),+});++export const postbackCallbackBodySchema = z.object({+ status: z.number(),+ url: z.string(),+ sourceMessageId: z.string(),+ body: z.string().optional().default(""),+ sourceBody: z.string(),+ retried: z.number().optional().default(0),+});++export const postbackEventInputSchemaTB = z.object({+ postback_id: z.string(),+ event_id: z.string(),+ message_id: z.string(),+ event: z.enum(POSTBACK_TRIGGERS),+ url: z.url(),+ response_status: z.number(),+ response_body: z.string(),+ request_body: z.string(),+ timestamp: z.string(),+ retry_attempt: z.number(),+});++export const postbackEventOutputSchemaTB = postbackEventInputSchemaTB.omit({+ postback_id: true,+ message_id: true,+});diff --git a/apps/web/lib/swr/use-partner-profile.ts b/apps/web/lib/swr/use-partner-profile.tsindex 29d103d1ca..c3e9aa53be 100644--- a/apps/web/lib/swr/use-partner-profile.ts+++ b/apps/web/lib/swr/use-partner-profile.ts@@ -5,7 +5,11 @@ import {} from "@dub/utils";import { useSession } from "next-auth/react";import useSWR from "swr";-import { PartnerProps } from "../types";+import { PartnerBetaFeatures, PartnerProps } from "../types";++interface PartnerProfile extends PartnerProps {+ featureFlags?: Record<PartnerBetaFeatures, boolean>;+}export default function usePartnerProfile() {const { data: session, status } = useSession();@@ -16,7 +20,7 @@ export default function usePartnerProfile() {error,isLoading,mutate,- } = useSWR<PartnerProps>(+ } = useSWR<PartnerProfile>(defaultPartnerId && "/api/partner-profile",fetcher,{diff --git a/apps/web/lib/tolt/update-stripe-customers.ts b/apps/web/lib/tolt/update-stripe-customers.tsindex 915c5027bf..c7ee53c89f 100644--- a/apps/web/lib/tolt/update-stripe-customers.ts+++ b/apps/web/lib/tolt/update-stripe-customers.ts@@ -144,8 +144,7 @@ async function searchStripeAndUpdateCustomer({} else {// look for the one with subscriptionsconst customerWithSubcription = stripeCustomers.data.find(- ({ subscriptions }) =>- subscriptions && subscriptions.data.length > 0,+ ({ subscriptions }) => subscriptions && subscriptions.data.length > 0,);if (customerWithSubcription) {diff --git a/apps/web/lib/types.ts b/apps/web/lib/types.tsindex 1e8ae6d22c..31f1f08afc 100644--- a/apps/web/lib/types.ts+++ b/apps/web/lib/types.ts@@ -35,6 +35,8 @@ import {FOLDER_PERMISSIONS,FOLDER_WORKSPACE_ACCESS,} from "./folder/constants";+import { POSTBACK_TRIGGERS } from "./postback/constants";+import { postbackEventInputSchemaTB, postbackSchema } from "./postback/schemas";import { WEBHOOK_TRIGGER_DESCRIPTIONS } from "./webhook/constants";import {activityLogActionSchema,@@ -236,6 +238,8 @@ export type PlanProps = (typeof plans)[number];export type BetaFeatures = "noDubLink" | "analyticsSettingsSiteVisitTracking";+export type PartnerBetaFeatures = "postbacks";+export interface WorkspaceProps extends Project {logo: string | null;plan: PlanProps;@@ -825,3 +829,9 @@ export type FieldDiff = z.infer<typeof fieldDiffSchema>;export type ChangeSet = Record<string, FieldDiff>;export type ActivityLog = z.infer<typeof activityLogSchema>;++export type PostbackProps = z.infer<typeof postbackSchema>;++export type PostbackEventProps = z.infer<typeof postbackEventInputSchemaTB>;++export type PostbackTrigger = (typeof POSTBACK_TRIGGERS)[number];diff --git a/apps/web/ui/layout/sidebar/partners-sidebar-nav.tsx b/apps/web/ui/layout/sidebar/partners-sidebar-nav.tsxindex b788e4bbb6..e7380c9c42 100644--- a/apps/web/ui/layout/sidebar/partners-sidebar-nav.tsx+++ b/apps/web/ui/layout/sidebar/partners-sidebar-nav.tsx@@ -1,5 +1,6 @@"use client";+import usePartnerProfile from "@/lib/swr/use-partner-profile";import usePartnerProgramBounties from "@/lib/swr/use-partner-program-bounties";import useProgramEnrollment from "@/lib/swr/use-program-enrollment";import useProgramEnrollmentsCount from "@/lib/swr/use-program-enrollments-count";@@ -21,6 +22,7 @@ import {Trophy,UserCheck,Users2,+ Webhook,} from "@dub/ui/icons";import { useParams, usePathname } from "next/navigation";import { ReactNode, useMemo } from "react";@@ -42,6 +44,7 @@ type SidebarNavData = {unreadMessagesCount?: number;programBountiesCount?: number;showDetailedAnalytics?: boolean;+ postbacksEnabled?: boolean;};const NAV_GROUPS: SidebarNavGroups<SidebarNavData> = ({@@ -122,7 +125,7 @@ const NAV_AREAS: SidebarNavAreas<SidebarNavData> = {],}),- profile: () => ({+ profile: ({ postbacksEnabled }) => ({title: "Partner profile",direction: "left",content: [@@ -141,6 +144,20 @@ const NAV_AREAS: SidebarNavAreas<SidebarNavData> = {},],},+ ...(postbacksEnabled+ ? [+ {+ name: "Developer",+ items: [+ {+ name: "Postbacks",+ icon: Webhook,+ href: "/profile/postbacks" as `/${string}`,+ },+ ],+ },+ ]+ : []),{name: "Account",items: [@@ -332,6 +349,8 @@ export function PartnersSidebarNav({},});+ const { partner } = usePartnerProfile();+return (<SidebarNavgroups={NAV_GROUPS}@@ -346,6 +365,7 @@ export function PartnersSidebarNav({unreadMessagesCount,programBountiesCount: bountiesCount.active,showDetailedAnalytics,+ postbacksEnabled: partner?.featureFlags?.postbacks,}}toolContent={toolContent}newsContent={newsContent}diff --git a/apps/web/ui/modals/confirm-modal.tsx b/apps/web/ui/modals/confirm-modal.tsxindex 78fd252fe4..7d21fa973a 100644--- a/apps/web/ui/modals/confirm-modal.tsx+++ b/apps/web/ui/modals/confirm-modal.tsx@@ -10,6 +10,7 @@ type PromptModelProps = {onConfirm: () => Promise<void> | void;confirmText?: string;+ confirmVariant?: "primary" | "danger";confirmShortcut?: string;confirmShortcutOptions?: {@@ -30,6 +31,7 @@ function ConfirmModal({cancelText = "Cancel",onConfirm,confirmText = "Confirm",+ confirmVariant = "primary",confirmShortcut,confirmShortcutOptions = { modal: true },}: {@@ -77,7 +79,7 @@ function ConfirmModal({}}/><Button- variant="primary"+ variant={confirmVariant}className="h-8 w-fit px-3"text={confirmText}loading={isLoading}diff --git a/apps/web/ui/postbacks/add-edit-postback-modal.tsx b/apps/web/ui/postbacks/add-edit-postback-modal.tsxnew file mode 100644index 0000000000..b0b61ad0f3--- /dev/null+++ b/apps/web/ui/postbacks/add-edit-postback-modal.tsx@@ -0,0 +1,334 @@+"use client";++import { partnerProfileFetch } from "@/lib/api/partner-profile/client";+import {+ POSTBACK_TRIGGER_DESCRIPTIONS,+ POSTBACK_TRIGGERS,+} from "@/lib/postback/constants";+import {+ createPostbackInputSchema,+ postbackSchema,+} from "@/lib/postback/schemas";+import { mutatePrefix } from "@/lib/swr/mutate";+import { PostbackTrigger } from "@/lib/types";+import { Badge, Button, Combobox, Modal, useMediaQuery } from "@dub/ui";+import { cn } from "@dub/utils";+import { ChevronsUpDown } from "lucide-react";+import { useEffect, useMemo, useState } from "react";+import { useForm } from "react-hook-form";+import { toast } from "sonner";+import * as z from "zod/v4";++type PostbackForEdit = z.infer<typeof postbackSchema>;++type FormData = z.infer<typeof createPostbackInputSchema>;++interface AddEditPostbackModalProps {+ showModal: boolean;+ setShowModal: (show: boolean) => void;+ postback: PostbackForEdit | null;+ onSuccess: () => void;+ onCreatedWithSecret?: (secret: string) => void;+}++function AddEditPostbackModal({+ showModal,+ setShowModal,+ postback,+ onSuccess,+ onCreatedWithSecret,+}: AddEditPostbackModalProps) {+ const { isMobile } = useMediaQuery();+ const [isOpen, setIsOpen] = useState(false);++ const {+ register,+ handleSubmit,+ reset,+ setValue,+ watch,+ formState: { isDirty, isSubmitting },+ } = useForm<FormData>({+ defaultValues: {+ name: "",+ url: "",+ triggers: [],+ },+ });++ const triggerOptions = POSTBACK_TRIGGERS.map((t) => ({+ value: t,+ label: POSTBACK_TRIGGER_DESCRIPTIONS[t],+ }));++ const isEdit = !!postback;+ const triggers = watch("triggers") ?? [];++ const selectedTriggers = useMemo(+ () =>+ triggers+ .map((t) => triggerOptions.find((o) => o.value === t))+ .filter(Boolean) as { value: string; label: string }[],+ [triggers, triggerOptions],+ );++ useEffect(() => {+ if (showModal) {+ reset({+ name: postback?.name ?? "",+ url: postback?.url ?? "",+ triggers: (postback?.triggers ?? []) as PostbackTrigger[],+ });+ }+ }, [showModal, postback, reset]);++ async function onSubmit(data: FormData) {+ // Update postback+ if (postback) {+ await partnerProfileFetch(+ "@patch/api/partner-profile/postbacks/:postbackId",+ {+ params: {+ postbackId: postback.id,+ },+ body: {+ name: data.name,+ url: data.url,+ triggers: data.triggers,+ },+ onSuccess: async () => {+ toast.success("Postback updated");+ setShowModal(false);+ await mutatePrefix("/api/partner-profile/postbacks");+ onSuccess();+ },+ onError: ({ error }) => {+ toast.error(error.error.message);+ },+ },+ );++ return;+ }++ // Create postback+ await partnerProfileFetch("/api/partner-profile/postbacks", {+ body: {+ name: data.name,+ url: data.url,+ triggers: data.triggers,+ },+ onSuccess: async ({ data: createdPostback }) => {+ toast.success("Postback created");++ if (createdPostback?.secret) {+ onCreatedWithSecret?.(createdPostback.secret);+ }++ setShowModal(false);+ onSuccess();++ await mutatePrefix("/api/partner-profile/postbacks");+ },+ onError: ({ error }) => {+ toast.error(error.error.message);+ },+ });+ }++ return (+ <>+ <Modal showModal={showModal} setShowModal={setShowModal}>+ <div className="border-b border-neutral-200 px-4 py-4 sm:px-6">+ <h3 className="text-lg font-medium leading-none">+ {isEdit ? "Edit" : "Add"} Postback+ </h3>+ </div>++ <div className="bg-neutral-50">+ <form+ onSubmit={(e) => {+ e.stopPropagation();+ return handleSubmit(onSubmit)(e);+ }}+ >+ <div className="flex flex-col gap-4 px-4 py-6 text-left sm:px-6">+ <div>+ <label+ htmlFor="postback-name"+ className="text-content-emphasis block text-sm font-medium"+ >+ Name+ </label>+ <input+ id="postback-name"+ type="text"+ autoComplete="off"+ className="border-border-subtle mt-2 block w-full rounded-lg text-neutral-900 placeholder-neutral-400 focus:border-neutral-500 focus:outline-none focus:ring-neutral-500 sm:text-sm"+ placeholder="My postback"+ autoFocus={!isMobile}+ disabled={isSubmitting}+ {...register("name")}+ />+ </div>++ <div>+ <label+ htmlFor="postback-url"+ className="text-content-emphasis block text-sm font-medium"+ >+ Destination URL+ </label>+ <input+ id="postback-url"+ type="url"+ autoComplete="off"+ className="border-border-subtle mt-2 block w-full rounded-lg text-neutral-900 placeholder-neutral-400 focus:border-neutral-500 focus:outline-none focus:ring-neutral-500 sm:text-sm"+ placeholder="https://your-server.com/webhook"+ disabled={isSubmitting}+ {...register("url")}+ />+ <p className="mt-1 text-xs text-neutral-500">+ Must be a valid HTTPS URL. We will send POST requests to this+ URL.+ </p>+ </div>++ <div>+ <label className="text-content-emphasis mb-1 block text-sm font-medium">+ Events+ </label>+ <Combobox+ multiple+ selected={selectedTriggers}+ setSelected={(opts) => {+ setValue(+ "triggers",+ opts.map((o) => o.value),+ { shouldDirty: true },+ );+ }}+ options={triggerOptions}+ searchPlaceholder="Search events..."+ buttonProps={{+ className: cn(+ "h-auto min-h-10 w-full justify-start px-2.5 py-1.5 font-normal border-neutral-200 bg-white",+ selectedTriggers.length === 0 && "text-neutral-400",+ ),+ disabled: isSubmitting,+ }}+ matchTriggerWidth+ caret={+ <ChevronsUpDown className="ml-2 size-4 shrink-0 text-neutral-400" />+ }+ open={isOpen}+ onOpenChange={setIsOpen}+ >+ {selectedTriggers.length > 0 ? (+ <div className="flex flex-wrap gap-2">+ {selectedTriggers.map((opt) => (+ <Badge+ key={opt.value}+ variant="gray"+ className="animate-fade-in"+ >+ {opt.label}+ </Badge>+ ))}+ </div>+ ) : (+ <span className="block py-0.5">Select events...</span>+ )}+ </Combobox>+ </div>+ </div>++ <div className="flex items-center justify-end gap-2 border-t border-neutral-200 px-4 py-4 sm:px-6">+ <Button+ type="button"+ variant="secondary"+ text="Cancel"+ className="h-9 w-fit"+ onClick={() => setShowModal(false)}+ disabled={isSubmitting}+ />+ <Button+ type="submit"+ text={isEdit ? "Save changes" : "Create postback"}+ className="h-9 w-fit"+ loading={isSubmitting}+ disabled={!isDirty}+ />+ </div>+ </form>+ </div>+ </Modal>+ </>+ );+}++interface AddEditPostbackModalWrapperProps {+ postback: PostbackForEdit | null | undefined;+ onSuccess?: () => void;+ onCreatedWithSecret?: (secret: string) => void;+ closePostbackModal: () => void;+}++function AddEditPostbackModalWrapper({+ postback,+ onSuccess,+ onCreatedWithSecret,+ closePostbackModal,+}: AddEditPostbackModalWrapperProps) {+ if (postback === undefined) return null;++ return (+ <AddEditPostbackModal+ showModal+ postback={postback}+ onSuccess={() => onSuccess?.()}+ onCreatedWithSecret={onCreatedWithSecret}+ setShowModal={(show) => {+ if (!show) {+ closePostbackModal();+ }+ }}+ />+ );+}++export function useAddEditPostbackModal(+ onSuccess?: () => void,+ onCreatedWithSecret?: (secret: string) => void,+) {+ const [postback, setPostback] = useState<PostbackForEdit | null | undefined>(+ undefined,+ );++ function openAddPostbackModal() {+ setPostback(null);+ }++ function openEditPostbackModal(postbackToEdit: PostbackForEdit) {+ setPostback(postbackToEdit);+ }++ function closePostbackModal() {+ setPostback(undefined);+ }++ return {+ openAddPostbackModal,+ openEditPostbackModal,+ closePostbackModal,+ AddEditPostbackModal: (+ <AddEditPostbackModalWrapper+ postback={postback}+ onSuccess={onSuccess}+ onCreatedWithSecret={onCreatedWithSecret}+ closePostbackModal={closePostbackModal}+ />+ ),+ isAddEditPostbackModalOpen: postback !== undefined,+ };+}diff --git a/apps/web/ui/postbacks/partner-postback-actions.tsx b/apps/web/ui/postbacks/partner-postback-actions.tsxnew file mode 100644index 0000000000..7f236824c0--- /dev/null+++ b/apps/web/ui/postbacks/partner-postback-actions.tsx@@ -0,0 +1,261 @@+"use client";++import { partnerProfileFetch } from "@/lib/api/partner-profile/client";+import { mutatePrefix } from "@/lib/swr/mutate";+import { PostbackProps } from "@/lib/types";+import { useConfirmModal } from "@/ui/modals/confirm-modal";+import { usePostbackSecretModal } from "@/ui/postbacks/postback-secret-modal";+import { SendTestPostbackModal } from "@/ui/postbacks/send-test-postback-modal";+import { ThreeDots } from "@/ui/shared/icons";+import { Button, Popover } from "@dub/ui";+import {+ CircleCheck,+ CircleX,+ Pencil,+ RefreshCw,+ Send,+ Trash,+} from "lucide-react";+import { useRouter } from "next/navigation";+import { useState } from "react";+import { toast } from "sonner";++interface PostbackActionsProps {+ postback: PostbackProps;+ openPopover: boolean;+ setOpenPopover: (open: boolean) => void;+ onEditPostback: (postback: PostbackProps) => void;+ onMutate?: () => void;+}++export function PostbackActions({+ postback,+ openPopover,+ setOpenPopover,+ onEditPostback,+ onMutate,+}: PostbackActionsProps) {+ const router = useRouter();+ const [showSendTest, setShowSendTest] = useState(false);++ const { openPostbackSecretModal, PostbackSecretModal } =+ usePostbackSecretModal();++ const isDisabled = !!postback.disabledAt;++ const {+ confirmModal: disableConfirmModal,+ setShowConfirmModal: setShowDisableConfirmModal,+ } = useConfirmModal({+ title: "Disable postback",+ description:+ "Events will no longer be sent to this URL. You can re-enable it at any time.",+ confirmText: "Disable",+ onConfirm: async () => {+ await partnerProfileFetch(+ "@patch/api/partner-profile/postbacks/:postbackId",+ {+ params: {+ postbackId: postback.id,+ },+ body: {+ disabled: true,+ },+ onSuccess: () => {+ toast.success("Postback disabled");+ onMutate?.();+ },+ onError: () => {+ throw new Error("Failed to disable");+ },+ },+ );+ },+ });++ const {+ confirmModal: enableConfirmModal,+ setShowConfirmModal: setShowEnableConfirmModal,+ } = useConfirmModal({+ title: "Enable postback",+ description: "Events will be sent to this URL again.",+ confirmText: "Enable",+ onConfirm: async () => {+ await partnerProfileFetch(+ "@patch/api/partner-profile/postbacks/:postbackId",+ {+ params: {+ postbackId: postback.id,+ },+ body: {+ disabled: false,+ },+ onSuccess: () => {+ toast.success("Postback enabled");+ onMutate?.();+ },+ onError: () => {+ throw new Error("Failed to enable");+ },+ },+ );+ },+ });++ const {+ confirmModal: deleteConfirmModal,+ setShowConfirmModal: setShowDeleteConfirmModal,+ } = useConfirmModal({+ title: "Delete postback",+ description:+ "This action cannot be undone. This postback will be permanently deleted.",+ confirmText: "Delete",+ confirmVariant: "danger",+ onConfirm: async () => {+ await partnerProfileFetch(+ "@delete/api/partner-profile/postbacks/:postbackId",+ {+ params: {+ postbackId: postback.id,+ },+ onSuccess: () => {+ toast.success("Postback deleted");+ mutatePrefix("/api/partner-profile/postbacks");+ router.push("/profile/postbacks");+ },+ onError: () => {+ throw new Error("Failed to delete");+ },+ },+ );+ },+ });++ const {+ confirmModal: rollSecretConfirmModal,+ setShowConfirmModal: setShowRollSecretConfirmModal,+ } = useConfirmModal({+ title: "Roll signing secret",+ description:+ "The current signing secret will be invalidated. Update your application with the new secret.",+ confirmText: "Roll secret",+ onConfirm: async () => {+ const { data } = await partnerProfileFetch(+ "@post/api/partner-profile/postbacks/:postbackId/rotate-secret",+ {+ params: {+ postbackId: postback.id,+ },+ onSuccess: () => {+ toast.success("Signing secret rolled");+ onMutate?.();+ },+ onError: () => {+ throw new Error("Failed to roll secret");+ },+ },+ );+ if (data?.secret) {+ openPostbackSecretModal(data.secret);+ }+ },+ });++ const closeAnd = (fn: () => void) => {+ setOpenPopover(false);+ fn();+ };++ const handleEnableDisable = () => {+ if (isDisabled) {+ setShowEnableConfirmModal(true);+ } else {+ setShowDisableConfirmModal(true);+ }+ };++ return (+ <>+ {disableConfirmModal}+ {enableConfirmModal}+ {deleteConfirmModal}+ {rollSecretConfirmModal}+ <PostbackSecretModal />+ <SendTestPostbackModal+ postbackId={postback.id}+ triggers={postback.triggers}+ showModal={showSendTest}+ setShowModal={setShowSendTest}+ onSuccess={onMutate}+ />+ <Popover+ content={+ <div className="w-screen sm:w-48">+ <div className="grid gap-px p-2">+ <Button+ text="Send test event"+ variant="outline"+ icon={<Send className="size-4" />}+ className="h-9 justify-start px-2"+ onClick={() => closeAnd(() => setShowSendTest(true))}+ />+ <Button+ text="Roll signing secret"+ variant="outline"+ icon={<RefreshCw className="size-4" />}+ className="h-9 justify-start px-2"+ onClick={() =>+ closeAnd(() => setShowRollSecretConfirmModal(true))+ }+ />+ </div>++ <div className="h-px w-full bg-neutral-200" />++ <div className="grid gap-px p-2">+ <Button+ text="Edit postback"+ variant="outline"+ icon={<Pencil className="size-4" />}+ className="h-9 justify-start px-2"+ onClick={() => closeAnd(() => onEditPostback(postback))}+ />++ <Button+ text={isDisabled ? "Enable postback" : "Disable postback"}+ variant="outline"+ icon={+ isDisabled ? (+ <CircleCheck className="size-4" />+ ) : (+ <CircleX className="size-4" />+ )+ }+ className="h-9 justify-start px-2"+ onClick={() => closeAnd(handleEnableDisable)}+ />++ <Button+ text="Delete postback"+ variant="danger-outline"+ icon={<Trash className="size-4" />}+ className="h-9 justify-start px-2"+ onClick={() => closeAnd(() => setShowDeleteConfirmModal(true))}+ />+ </div>+ </div>+ }+ align="end"+ openPopover={openPopover}+ setOpenPopover={setOpenPopover}+ >+ <Button+ variant="outline"+ className="flex w-8 rounded-md border border-neutral-200 px-2 transition-[border-color] duration-200"+ icon={<ThreeDots className="h-5 w-5 shrink-0 text-neutral-500" />}+ onClick={() => setOpenPopover(!openPopover)}+ />+ </Popover>+ </>+ );+}diff --git a/apps/web/ui/postbacks/postback-card.tsx b/apps/web/ui/postbacks/postback-card.tsxnew file mode 100644index 0000000000..73e5569335--- /dev/null+++ b/apps/web/ui/postbacks/postback-card.tsx@@ -0,0 +1,34 @@+import { PostbackProps } from "@/lib/types";+import { Slack, TokenAvatar } from "@dub/ui";+import Link from "next/link";+import { PostbackStatus } from "./postback-status";++export function PostbackCard(postback: PostbackProps) {+ return (+ <Link+ href={`/profile/postbacks/${postback.id}`}+ className="hover:drop-shadow-card-hover relative rounded-xl border border-neutral-200 bg-white px-5 py-4 transition-[filter]"+ >+ <div className="flex items-center gap-x-3">+ <div className="flex-shrink-0 rounded-md border border-neutral-200 bg-gradient-to-t from-neutral-100 p-2.5">+ {postback.receiver === "slack" ? (+ <Slack className="size-6" />+ ) : (+ <TokenAvatar id={postback.name} className="size-6" />+ )}+ </div>+ <div className="overflow-hidden">+ <div className="flex items-center gap-1">+ <span className="text-sm font-medium text-neutral-700">+ {postback.name}+ </span>+ <PostbackStatus disabledAt={postback.disabledAt} />+ </div>+ <div className="truncate text-sm text-neutral-500">+ {postback.url}+ </div>+ </div>+ </div>+ </Link>+ );+}diff --git a/apps/web/ui/postbacks/postback-detail-skeleton.tsx b/apps/web/ui/postbacks/postback-detail-skeleton.tsxnew file mode 100644index 0000000000..d6b5bd128f--- /dev/null+++ b/apps/web/ui/postbacks/postback-detail-skeleton.tsx@@ -0,0 +1,24 @@+import { PostbackEventListSkeleton } from "@/ui/postbacks/postback-event-list-skeleton";++export function PostbackDetailSkeleton() {+ return (+ <>+ <div className="flex justify-between gap-8 sm:items-center">+ <div className="flex min-w-0 flex-col gap-3 sm:flex-row sm:items-center">+ <div className="w-fit flex-none rounded-md border border-neutral-200 bg-gradient-to-t from-neutral-100 p-2">+ <div className="size-8 animate-pulse rounded-full bg-neutral-100" />+ </div>+ <div className="flex flex-col gap-2">+ <div className="h-5 w-28 animate-pulse rounded-full bg-neutral-100" />+ <div className="h-3 w-48 animate-pulse rounded-full bg-neutral-100" />+ </div>+ </div>+ <div className="size-8 shrink-0 animate-pulse rounded-md border border-neutral-200 bg-neutral-100" />+ </div>+ <div className="space-y-4">+ <h2 className="text-sm font-medium">Events</h2>+ <PostbackEventListSkeleton />+ </div>+ </>+ );+}diff --git a/apps/web/ui/postbacks/postback-event-details-sheet.tsx b/apps/web/ui/postbacks/postback-event-details-sheet.tsxnew file mode 100644index 0000000000..8e5014ec70--- /dev/null+++ b/apps/web/ui/postbacks/postback-event-details-sheet.tsx@@ -0,0 +1,149 @@+"use client";++import { PostbackEventProps } from "@/lib/types";+import { Button, ButtonTooltip, Sheet, useCopyToClipboard } from "@dub/ui";+import { Copy } from "@dub/ui/icons";+import { Dispatch, SetStateAction, useEffect, useState } from "react";+import type { HighlighterCore } from "shiki";+import { toast } from "sonner";+import { X } from "../shared/icons";++interface PostbackEventDetailsSheetProps {+ isOpen: boolean;+ setIsOpen: Dispatch<SetStateAction<boolean>>;+ event: PostbackEventProps | null;+}++function PostbackEventDetailsSheetContent({+ event,+}: Omit<PostbackEventDetailsSheetProps, "isOpen" | "setIsOpen">) {+ const [highlighter, setHighlighter] = useState<HighlighterCore | null>(null);+ const [responseBody, setResponseBody] = useState("");+ const [requestBody, setRequestBody] = useState("");++ useEffect(() => {+ import("shiki").then(({ createHighlighter }) => {+ createHighlighter({+ themes: ["min-light"],+ langs: ["json"],+ }).then(setHighlighter);+ });+ }, []);++ useEffect(() => {+ if (!highlighter || !event) return;++ const toHighlightedJson = (raw: string) => {+ let value: unknown;+ try {+ value = JSON.parse(raw);+ } catch {+ value = raw;+ }++ const jsonStr = JSON.stringify(value, null, 2) ?? String(value);+ return highlighter.codeToHtml(jsonStr, {+ theme: "min-light",+ lang: "json",+ });+ };++ setResponseBody(toHighlightedJson(event.response_body));+ setRequestBody(toHighlightedJson(event.request_body));+ }, [highlighter, event]);++ const [, copyToClipboard] = useCopyToClipboard();++ if (!event) return null;++ return (+ <div className="flex size-full flex-col">+ <div className="p-6">+ <div className="flex items-start justify-between">+ <Sheet.Title className="text-lg font-semibold">+ {event.event}+ </Sheet.Title>+ <Sheet.Close asChild>+ <Button+ variant="outline"+ icon={<X className="size-5" />}+ className="h-auto w-fit p-1"+ />+ </Sheet.Close>+ </div>+ <div className="group flex items-center gap-2">+ <p className="font-mono text-sm text-neutral-500">{event.event_id}</p>+ <ButtonTooltip+ tooltipProps={{+ content: "Copy event ID",+ }}+ onClick={() =>+ toast.promise(copyToClipboard(event.event_id), {+ success: "Copied to clipboard",+ })+ }+ >+ <Copy className="size-4 opacity-0 transition-opacity group-hover:opacity-100" />+ </ButtonTooltip>+ </div>+ </div>+ <div className="scrollbar-hide flex min-h-0 flex-1 flex-col overflow-y-auto">+ <div className="grid gap-4 border-t border-neutral-200 bg-white p-6">+ <h4 className="font-semibold">Response</h4>+ <div className="flex items-center gap-8">+ <p className="text-sm text-neutral-500">HTTP status code</p>+ <p className="text-sm text-neutral-700">{event.response_status}</p>+ </div>+ <div+ className="shiki-wrapper overflow-y-scroll text-sm"+ dangerouslySetInnerHTML={{ __html: responseBody }}+ />+ </div>+ <div className="grid gap-4 border-t border-neutral-200 bg-white p-6">+ <h4 className="font-semibold">Request</h4>+ <div+ className="shiki-wrapper overflow-y-scroll text-sm"+ dangerouslySetInnerHTML={{ __html: requestBody }}+ />+ </div>+ </div>+ </div>+ );+}++export function PostbackEventDetailsSheet({+ isOpen,+ setIsOpen,+ event,+}: PostbackEventDetailsSheetProps) {+ return (+ <Sheet+ open={isOpen}+ onOpenChange={setIsOpen}+ contentProps={{ className: "md:w-[650px]" }}+ >+ <PostbackEventDetailsSheetContent event={event} />+ </Sheet>+ );+}++export function usePostbackEventDetailsSheet() {+ const [isOpen, setIsOpen] = useState(false);+ const [event, setEvent] = useState<PostbackEventProps | null>(null);++ const openWithEvent = (e: PostbackEventProps) => {+ setEvent(e);+ setIsOpen(true);+ };++ return {+ postbackEventDetailsSheet: event ? (+ <PostbackEventDetailsSheet+ event={event}+ isOpen={isOpen}+ setIsOpen={setIsOpen}+ />+ ) : null,+ openWithEvent,+ };+}diff --git a/apps/web/ui/postbacks/postback-event-list-skeleton.tsx b/apps/web/ui/postbacks/postback-event-list-skeleton.tsxnew file mode 100644index 0000000000..666b2d1621--- /dev/null+++ b/apps/web/ui/postbacks/postback-event-list-skeleton.tsx@@ -0,0 +1,23 @@+export const PostbackEventListSkeleton = () => {+ return (+ <div className="overflow-hidden rounded-md border border-neutral-200">+ <div className="flex flex-col divide-y divide-neutral-200">+ {[...Array(5)].map((_, index) => (+ <div+ className="flex items-center justify-between gap-5 px-3.5 py-3"+ key={index}+ >+ <div className="flex items-center gap-5">+ <div className="flex items-center gap-2.5">+ <div className="h-4 w-4 animate-pulse rounded-full bg-neutral-200" />+ <div className="h-4 w-12 animate-pulse rounded-full bg-neutral-200" />+ </div>+ <div className="h-4 w-24 animate-pulse rounded-full bg-neutral-200" />+ </div>+ <div className="h-3 w-20 animate-pulse rounded-full bg-neutral-200" />+ </div>+ ))}+ </div>+ </div>+ );+};diff --git a/apps/web/ui/postbacks/postback-event-list.tsx b/apps/web/ui/postbacks/postback-event-list.tsxnew file mode 100644index 0000000000..5c264ed13d--- /dev/null+++ b/apps/web/ui/postbacks/postback-event-list.tsx@@ -0,0 +1,83 @@+"use client";++import { PostbackEventProps } from "@/lib/types";+import { TimestampTooltip, Tooltip } from "@dub/ui";+import { CircleCheck, CircleHalfDottedClock } from "@dub/ui/icons";+import { formatDateTimeSmart } from "@dub/utils";+import { PropsWithChildren } from "react";++export type PostbackEventListProps = PropsWithChildren<{+ events: PostbackEventProps[];+ onEventClick: (event: PostbackEventProps) => void;+}>;++const PostbackEventRow = ({+ event,+ onClick,+}: {+ event: PostbackEventProps;+ onClick: () => void;+}) => {+ const isSuccess = event.response_status >= 200 && event.response_status < 300;++ return (+ <button+ type="button"+ onClick={onClick}+ className="flex items-center justify-between gap-5 px-3.5 py-3 hover:bg-neutral-50 focus:outline-none"+ >+ <div className="flex items-center gap-5">+ <div className="flex items-center gap-2.5">+ <Tooltip+ content={+ isSuccess+ ? "This postback was successfully delivered."+ : "This postback failed to deliver – it will be retried."+ }+ >+ <div>+ {isSuccess ? (+ <CircleCheck className="size-4 text-green-500" />+ ) : (+ <CircleHalfDottedClock className="size-4 text-amber-500" />+ )}+ </div>+ </Tooltip>+ <div className="text-sm text-neutral-500">+ {event.response_status}+ </div>+ </div>+ <div className="text-sm text-neutral-500">{event.event}</div>+ </div>++ <TimestampTooltip+ timestamp={event.timestamp}+ side="right"+ rows={["local", "utc", "unix"]}+ >+ <div className="text-xs text-neutral-400">+ {formatDateTimeSmart(event.timestamp)}+ </div>+ </TimestampTooltip>+ </button>+ );+};++export const PostbackEventList = ({+ events,+ onEventClick,+}: PostbackEventListProps) => {+ return (+ <div className="overflow-hidden rounded-md border border-neutral-200">+ <div className="flex flex-col divide-y divide-neutral-200">+ {events.map((event) => (+ <PostbackEventRow+ key={event.event_id}+ event={event}+ onClick={() => onEventClick(event)}+ />+ ))}+ </div>+ </div>+ );+};diff --git a/apps/web/ui/postbacks/postback-placeholder.tsx b/apps/web/ui/postbacks/postback-placeholder.tsxnew file mode 100644index 0000000000..9d7bc138b8--- /dev/null+++ b/apps/web/ui/postbacks/postback-placeholder.tsx@@ -0,0 +1,13 @@+export function PostbackPlaceholder() {+ return (+ <div className="relative grid gap-4 rounded-xl border border-neutral-200 bg-white px-5 py-4">+ <div className="flex items-center gap-2">+ <div className="flex size-12 items-center justify-center rounded-lg bg-neutral-100" />+ <div className="flex flex-col gap-2">+ <div className="h-4 w-20 rounded-full bg-neutral-100" />+ <div className="h-3 w-28 rounded-full bg-neutral-100" />+ </div>+ </div>+ </div>+ );+}diff --git a/apps/web/ui/postbacks/postback-secret-modal.tsx b/apps/web/ui/postbacks/postback-secret-modal.tsxnew file mode 100644index 0000000000..fc8cf35ac9--- /dev/null+++ b/apps/web/ui/postbacks/postback-secret-modal.tsx@@ -0,0 +1,109 @@+"use client";++import { Button, Copy, Modal, Tick, useCopyToClipboard } from "@dub/ui";+import { Dispatch, SetStateAction, useState } from "react";+import { toast } from "sonner";++interface PostbackSecretModalProps {+ showModal: boolean;+ setShowModal: Dispatch<SetStateAction<boolean>>;+ secret: string;+}++function PostbackSecretModal({+ showModal,+ setShowModal,+ secret,+}: PostbackSecretModalProps) {+ const [copied, copyToClipboard] = useCopyToClipboard();++ return (+ <Modal+ showModal={showModal}+ setShowModal={setShowModal}+ className="max-w-md"+ >+ <div className="space-y-2 border-b border-neutral-200 px-4 py-4 sm:px-6">+ <h3 className="text-lg font-medium">Signing secret</h3>+ <p className="text-sm text-neutral-500">+ Copy it and store it somewhere safe. You will need it to verify+ postback signatures.+ </p>+ </div>++ <div className="flex flex-col space-y-4 bg-neutral-50 px-4 py-8 sm:px-6">+ <div className="flex flex-col gap-1">+ <h2 className="text-sm font-medium text-neutral-800">+ Signing secret+ </h2>+ <div className="flex items-center justify-between gap-2 rounded-md border border-neutral-200 bg-white p-2">+ <p className="truncate font-mono text-sm text-neutral-500">+ {secret}+ </p>+ <button+ onClick={(e) => {+ e.stopPropagation();+ toast.promise(copyToClipboard(secret), {+ success: "Secret copied to clipboard!",+ });+ }}+ type="button"+ className="text-neutral-90 flex h-7 shrink-0 items-center gap-2 rounded-md border border-neutral-200 bg-white px-2 py-1 text-xs font-medium hover:bg-neutral-50"+ >+ {copied ? (+ <Tick className="h-3.5 w-3.5" />+ ) : (+ <Copy className="h-3.5 w-3.5" />+ )}+ {copied ? "Copied" : "Copy"}+ </button>+ </div>+ </div>++ <Button+ text="Done"+ variant="secondary"+ onClick={() => setShowModal(false)}+ className="w-full"+ />+ </div>+ </Modal>+ );+}++export function usePostbackSecretModal() {+ const [state, setState] = useState<{ show: boolean; secret: string }>({+ show: false,+ secret: "",+ });++ function openPostbackSecretModal(secret: string) {+ setState({ show: true, secret });+ }++ function closePostbackSecretModal() {+ setState({ show: false, secret: "" });+ }++ function PostbackSecretModalWrapper() {+ if (!state.show) return null;++ return (+ <PostbackSecretModal+ showModal={state.show}+ setShowModal={(show) => {+ const next = typeof show === "function" ? show(state.show) : show;+ if (!next) closePostbackSecretModal();+ }}+ secret={state.secret}+ />+ );+ }++ return {+ openPostbackSecretModal,+ closePostbackSecretModal,+ PostbackSecretModal: PostbackSecretModalWrapper,+ isPostbackSecretModalOpen: state.show,+ };+}diff --git a/apps/web/ui/postbacks/postback-status.tsx b/apps/web/ui/postbacks/postback-status.tsxnew file mode 100644index 0000000000..2433521211--- /dev/null+++ b/apps/web/ui/postbacks/postback-status.tsx@@ -0,0 +1,16 @@+import { Postback } from "@dub/prisma/client";+import { Badge } from "@dub/ui";+import { cn } from "@dub/utils";++export function PostbackStatus({ disabledAt }: Pick<Postback, "disabledAt">) {+ const isDisabled = !!disabledAt;++ return (+ <Badge+ variant={isDisabled ? "neutral" : "green"}+ className={cn(isDisabled && "border-red-100 bg-red-100 text-red-500")}+ >+ {isDisabled ? "Disabled" : "Enabled"}+ </Badge>+ );+}diff --git a/apps/web/ui/postbacks/send-test-postback-modal.tsx b/apps/web/ui/postbacks/send-test-postback-modal.tsxnew file mode 100644index 0000000000..b10bfbdd16--- /dev/null+++ b/apps/web/ui/postbacks/send-test-postback-modal.tsx@@ -0,0 +1,147 @@+"use client";++import { partnerProfileFetch } from "@/lib/api/partner-profile/client";+import { POSTBACK_TRIGGER_DESCRIPTIONS } from "@/lib/postback/constants";+import { sendTestPostbackInputSchema } from "@/lib/postback/schemas";+import { mutatePrefix } from "@/lib/swr/mutate";+import { PostbackTrigger } from "@/lib/types";+import { Button, Combobox, ComboboxOption, Modal } from "@dub/ui";+import { Dispatch, SetStateAction, useEffect, useMemo } from "react";+import { useForm } from "react-hook-form";+import { toast } from "sonner";+import * as z from "zod/v4";++type FormData = z.infer<typeof sendTestPostbackInputSchema>;++interface SendTestPostbackModalProps {+ postbackId: string;+ triggers: string[];+ showModal: boolean;+ setShowModal: Dispatch<SetStateAction<boolean>>;+ onSuccess?: () => void;+}++export function SendTestPostbackModal({+ postbackId,+ triggers,+ showModal,+ setShowModal,+ onSuccess,+}: SendTestPostbackModalProps) {+ const options = useMemo(+ () =>+ triggers.map((t) => ({+ value: t,+ label: POSTBACK_TRIGGER_DESCRIPTIONS[t as PostbackTrigger] ?? t,+ })),+ [triggers],+ );++ const {+ handleSubmit,+ reset,+ setValue,+ watch,+ formState: { isSubmitting },+ } = useForm<FormData>({+ defaultValues: {+ event: "" as FormData["event"],+ },+ });++ const selectedEvent = watch("event");++ const selectedOption: ComboboxOption | null = selectedEvent+ ? options.find((o) => o.value === selectedEvent) ?? null+ : null;++ useEffect(() => {+ if (showModal) {+ reset({+ event: "" as FormData["event"],+ });+ }+ }, [showModal, reset]);++ const onSubmit = async (data: FormData) => {+ await partnerProfileFetch(+ "@post/api/partner-profile/postbacks/:postbackId/send-test",+ {+ params: {+ postbackId,+ },+ body: {+ event: data.event,+ },+ onSuccess: async () => {+ setShowModal(false);+ await mutatePrefix("/api/partner-profile/postbacks");+ toast.success("Test event sent successfully");+ onSuccess?.();+ },+ onError: ({ error }) => {+ toast.error(error.error.message);+ },+ },+ );+ };++ return (+ <Modal showModal={showModal} setShowModal={setShowModal}>+ <div className="space-y-2 border-b border-neutral-200 px-4 py-4 sm:px-6">+ <h3 className="text-lg font-medium leading-none">+ Send test postback event+ </h3>+ <p className="text-sm text-neutral-500">+ Choose an event to send a test payload to your endpoint.+ </p>+ </div>++ <div className="bg-neutral-50">+ <form+ onSubmit={(e) => {+ e.stopPropagation();+ return handleSubmit(onSubmit)(e);+ }}+ >+ <div className="flex flex-col gap-4 px-4 py-6 text-left sm:px-6">+ <div className="mt-2">+ <Combobox+ options={options}+ selected={selectedOption}+ setSelected={(opt) =>+ setValue("event", (opt?.value as FormData["event"]) ?? "", {+ shouldDirty: true,+ })+ }+ placeholder="Select an event"+ matchTriggerWidth+ caret+ />+ </div>+ </div>++ <div className="flex items-center justify-end border-t border-neutral-200 px-4 py-4 sm:px-6">+ <div className="flex gap-2">+ <Button+ type="button"+ variant="secondary"+ text="Cancel"+ className="h-9 w-fit"+ onClick={() => setShowModal(false)}+ disabled={isSubmitting}+ />+ <Button+ type="submit"+ text="Send test event"+ className="h-9 w-fit"+ loading={isSubmitting}+ disabled={!selectedEvent || isSubmitting}+ />+ </div>+ </div>+ </form>+ </div>+ </Modal>+ );+}diff --git a/apps/web/ui/webhooks/webhook-event-details-sheet.tsx b/apps/web/ui/webhooks/webhook-event-details-sheet.tsxnew file mode 100644index 0000000000..2c629ec149--- /dev/null+++ b/apps/web/ui/webhooks/webhook-event-details-sheet.tsx@@ -0,0 +1,151 @@+"use client";++import { WebhookEventProps } from "@/lib/types";+import { Button, ButtonTooltip, Sheet, useCopyToClipboard } from "@dub/ui";+import { Copy } from "@dub/ui/icons";+import { Dispatch, SetStateAction, useEffect, useState } from "react";+import type { HighlighterCore } from "shiki";+import { toast } from "sonner";+import { X } from "../shared/icons";++interface WebhookEventDetailsSheetProps {+ isOpen: boolean;+ setIsOpen: Dispatch<SetStateAction<boolean>>;+ event: WebhookEventProps | null;+}++function WebhookEventDetailsSheetContent({+ event,+}: Omit<WebhookEventDetailsSheetProps, "isOpen" | "setIsOpen">) {+ const [highlighter, setHighlighter] = useState<HighlighterCore | null>(null);+ const [responseBody, setResponseBody] = useState("");+ const [requestBody, setRequestBody] = useState("");++ useEffect(() => {+ import("shiki").then(({ createHighlighter }) => {+ createHighlighter({+ themes: ["min-light"],+ langs: ["json"],+ }).then(setHighlighter);+ });+ }, []);++ useEffect(() => {+ if (!highlighter || !event) return;++ const toHighlightedJson = (raw: string) => {+ let value: unknown;+ try {+ value = JSON.parse(raw);+ } catch {+ value = raw;+ }++ const jsonStr = JSON.stringify(value, null, 2) ?? String(value);+ return highlighter.codeToHtml(jsonStr, {+ theme: "min-light",+ lang: "json",+ });+ };++ setResponseBody(toHighlightedJson(event.response_body));+ setRequestBody(toHighlightedJson(event.request_body));+ }, [highlighter, event]);++ const [, copyToClipboard] = useCopyToClipboard();++ if (!event) return null;++ return (+ <div className="flex size-full flex-col">+ <div className="p-6">+ <div className="flex items-start justify-between">+ <Sheet.Title className="text-lg font-semibold">+ {event.event}+ </Sheet.Title>+ <Sheet.Close asChild>+ <Button+ variant="outline"+ icon={<X className="size-5" />}+ className="h-auto w-fit p-1"+ />+ </Sheet.Close>+ </div>+ <div className="group flex items-center gap-2">+ <p className="font-mono text-sm text-neutral-500">+ {event.event_id}+ </p>+ <ButtonTooltip+ tooltipProps={{+ content: "Copy event ID",+ }}+ onClick={() =>+ toast.promise(copyToClipboard(event.event_id), {+ success: "Copied to clipboard",+ })+ }+ >+ <Copy className="size-4 opacity-0 transition-opacity group-hover:opacity-100" />+ </ButtonTooltip>+ </div>+ </div>+ <div className="scrollbar-hide flex min-h-0 flex-1 flex-col overflow-y-auto">+ <div className="grid gap-4 border-t border-neutral-200 bg-white p-6">+ <h4 className="font-semibold">Response</h4>+ <div className="flex items-center gap-8">+ <p className="text-sm text-neutral-500">HTTP status code</p>+ <p className="text-sm text-neutral-700">{event.http_status}</p>+ </div>+ <div+ className="shiki-wrapper overflow-y-scroll text-sm"+ dangerouslySetInnerHTML={{ __html: responseBody }}+ />+ </div>+ <div className="grid gap-4 border-t border-neutral-200 bg-white p-6">+ <h4 className="font-semibold">Request</h4>+ <div+ className="shiki-wrapper overflow-y-scroll text-sm"+ dangerouslySetInnerHTML={{ __html: requestBody }}+ />+ </div>+ </div>+ </div>+ );+}++export function WebhookEventDetailsSheet({+ isOpen,+ setIsOpen,+ event,+}: WebhookEventDetailsSheetProps) {+ return (+ <Sheet+ open={isOpen}+ onOpenChange={setIsOpen}+ contentProps={{ className: "md:w-[650px]" }}+ >+ <WebhookEventDetailsSheetContent event={event} />+ </Sheet>+ );+}++export function useWebhookEventDetailsSheet() {+ const [isOpen, setIsOpen] = useState(false);+ const [event, setEvent] = useState<WebhookEventProps | null>(null);++ const openWithEvent = (e: WebhookEventProps) => {+ setEvent(e);+ setIsOpen(true);+ };++ return {+ webhookEventDetailsSheet: event ? (+ <WebhookEventDetailsSheet+ event={event}+ isOpen={isOpen}+ setIsOpen={setIsOpen}+ />+ ) : null,+ openWithEvent,+ };+}diff --git a/apps/web/ui/webhooks/webhook-event-list.tsx b/apps/web/ui/webhooks/webhook-event-list.tsxnew file mode 100644index 0000000000..5dd7de02e3--- /dev/null+++ b/apps/web/ui/webhooks/webhook-event-list.tsx@@ -0,0 +1,81 @@+"use client";++import { WebhookEventProps } from "@/lib/types";+import { TimestampTooltip, Tooltip } from "@dub/ui";+import { CircleCheck, CircleHalfDottedClock } from "@dub/ui/icons";+import { formatDateTimeSmart } from "@dub/utils";+import { PropsWithChildren } from "react";++export type WebhookEventListProps = PropsWithChildren<{+ events: WebhookEventProps[];+ onEventClick: (event: WebhookEventProps) => void;+}>;++const WebhookEventRow = ({+ event,+ onClick,+}: {+ event: WebhookEventProps;+ onClick: () => void;+}) => {+ const isSuccess = event.http_status >= 200 && event.http_status < 300;++ return (+ <button+ type="button"+ onClick={onClick}+ className="flex items-center justify-between gap-5 px-3.5 py-3 hover:bg-neutral-50 focus:outline-none"+ >+ <div className="flex items-center gap-5">+ <div className="flex items-center gap-2.5">+ <Tooltip+ content={+ isSuccess+ ? "This webhook was successfully delivered."+ : "This webhook failed to deliver – it will be retried."+ }+ >+ <div>+ {isSuccess ? (+ <CircleCheck className="size-4 text-green-500" />+ ) : (+ <CircleHalfDottedClock className="size-4 text-amber-500" />+ )}+ </div>+ </Tooltip>+ <div className="text-sm text-neutral-500">{event.http_status}</div>+ </div>+ <div className="text-sm text-neutral-500">{event.event}</div>+ </div>++ <TimestampTooltip+ timestamp={event.timestamp}+ side="right"+ rows={["local", "utc", "unix"]}+ >+ <div className="text-xs text-neutral-400">+ {formatDateTimeSmart(event.timestamp)}+ </div>+ </TimestampTooltip>+ </button>+ );+};++export const WebhookEventList = ({+ events,+ onEventClick,+}: WebhookEventListProps) => {+ return (+ <div className="overflow-hidden rounded-md border border-neutral-200">+ <div className="flex flex-col divide-y divide-neutral-200">+ {events.map((event) => (+ <WebhookEventRow+ key={event.event_id}+ event={event}+ onClick={() => onEventClick(event)}+ />+ ))}+ </div>+ </div>+ );+};diff --git a/apps/web/ui/webhooks/webhook-events.tsx b/apps/web/ui/webhooks/webhook-events.tsxdeleted file mode 100644index e4d9c0ff3c..0000000000--- a/apps/web/ui/webhooks/webhook-events.tsx+++ /dev/null@@ -1,182 +0,0 @@-"use client";--import { WebhookEventProps } from "@/lib/types";-import {- Button,- ButtonTooltip,- Sheet,- Tooltip,- useCopyToClipboard,- useMediaQuery,-} from "@dub/ui";-import { CircleCheck, CircleHalfDottedClock, Copy } from "@dub/ui/icons";-import { PropsWithChildren, useEffect, useState } from "react";-import { Highlighter } from "shiki";-import { toast } from "sonner";-import { X } from "../shared/icons";--export type EventListProps = PropsWithChildren<{- events: WebhookEventProps[];-}>;--const WebhookEvent = ({ event }: { event: WebhookEventProps }) => {- const [highlighter, setHighlighter] = useState<Highlighter | null>(null);- const [responseBody, setResponseBody] = useState<string>("");- const [requestBody, setRequestBody] = useState<string>("");-- useEffect(() => {- import("shiki").then(({ getHighlighter }) => {- getHighlighter({- themes: ["min-light"],- langs: ["json"],- }).then(setHighlighter);- });- }, []);-- useEffect(() => {- if (highlighter) {- let responseBodyDecoded = event.response_body;-- try {- responseBodyDecoded = JSON.parse(event.response_body);- } catch {- // If it's not JSON, just use the original response body- }-- const responseBodyHtml = highlighter.codeToHtml(- JSON.stringify(responseBodyDecoded, null, 2),- {- theme: "min-light",- lang: "json",- },- );- setResponseBody(responseBodyHtml);- const requestBodyHtml = highlighter.codeToHtml(- JSON.stringify(event.request_body, null, 2),- {- theme: "min-light",- lang: "json",- },- );- setRequestBody(requestBodyHtml);- }- }, [highlighter, event]);-- const [, copyToClipboard] = useCopyToClipboard();-- const isSuccess = event.http_status >= 200 && event.http_status < 300;- const { isMobile } = useMediaQuery();-- const [isOpen, setIsOpen] = useState(false);-- return (- <>- <button- type="button"- onClick={() => setIsOpen(true)}- className="flex items-center justify-between gap-5 px-3.5 py-3 hover:bg-neutral-50 focus:outline-none"- >- <div className="flex items-center gap-5">- <div className="flex items-center gap-2.5">- <Tooltip- content={- isSuccess- ? "This webhook was successfully delivered."- : "This webhook failed to deliver – it will be retried."- }- >- <div>- {isSuccess ? (- <CircleCheck className="size-4 text-green-500" />- ) : (- <CircleHalfDottedClock className="size-4 text-amber-500" />- )}- </div>- </Tooltip>- <div className="text-sm text-neutral-500">{event.http_status}</div>- </div>- <div className="text-sm text-neutral-500">{event.event}</div>- </div>-- <div className="text-xs text-neutral-400">- {(() => {- const date = new Date(event.timestamp);- const localDate = new Date(- date.getTime() - date.getTimezoneOffset() * 60000,- );- return isMobile- ? localDate.toLocaleTimeString()- : localDate.toLocaleString();- })()}- </div>- </button>- <Sheet- open={isOpen}- onOpenChange={setIsOpen}- contentProps={{ className: "md:w-[650px]" }}- >- <div className="p-6">- <div className="flex items-start justify-between">- <Sheet.Title className="text-lg font-semibold">- {event.event}- </Sheet.Title>- <Sheet.Close asChild>- <Button- variant="outline"- icon={<X className="size-5" />}- className="h-auto w-fit p-1"- />- </Sheet.Close>- </div>- <div className="group flex items-center gap-2">- <p className="font-mono text-sm text-neutral-500">- {event.event_id}- </p>- <ButtonTooltip- tooltipProps={{- content: "Copy event ID",- }}- onClick={() =>- toast.promise(copyToClipboard(event.event_id), {- success: "Copied to clipboard",- })- }- >- <Copy className="size-4 opacity-0 transition-opacity group-hover:opacity-100" />- </ButtonTooltip>- </div>- </div>- <div className="grid gap-4 border-t border-neutral-200 bg-white p-6">- <h4 className="font-semibold">Response</h4>- <div className="flex items-center gap-8">- <p className="text-sm text-neutral-500">HTTP status code</p>- <p className="text-sm text-neutral-700">{event.http_status}</p>- </div>- <div- className="shiki-wrapper overflow-y-scroll text-sm"- dangerouslySetInnerHTML={{ __html: responseBody }}- />- </div>- <div className="grid gap-4 border-t border-neutral-200 bg-white p-6">- <h4 className="font-semibold">Request</h4>- <div- className="shiki-wrapper overflow-y-scroll text-sm"- dangerouslySetInnerHTML={{ __html: requestBody }}- />- </div>- </Sheet>- </>- );-};--export const WebhookEventList = ({ events }: EventListProps) => {- return (- <div className="overflow-hidden rounded-md border border-neutral-200">- <div className="flex flex-col divide-y divide-neutral-200">- {events.map((event, index) => (- <WebhookEvent key={index} event={event} />- ))}- </div>- </div>- );-};diff --git a/packages/prisma/schema/partner.prisma b/packages/prisma/schema/partner.prismaindex 38dc51e099..cab2f20268 100644--- a/packages/prisma/schema/partner.prisma+++ b/packages/prisma/schema/partner.prisma@@ -50,6 +50,7 @@ model Partner {payouts Payout[]commissions Commission[]bountySubmissions BountySubmission[]+ postbacks Postback[]messages Message[]sentMessages Message[] @relation("SenderPartner")comments PartnerComment[]@@ -146,4 +147,4 @@ model PartnerSalesChannel {partner Partner @relation(fields: [partnerId], references: [id], onDelete: Cascade)@@unique([partnerId, salesChannel])-}+}\ No newline at end of filediff --git a/packages/prisma/schema/postback.prisma b/packages/prisma/schema/postback.prismanew file mode 100644index 0000000000..525aaec64a--- /dev/null+++ b/packages/prisma/schema/postback.prisma@@ -0,0 +1,21 @@+enum PostbackReceiver {+ custom+ slack+}++model Postback {+ id String @id @default(cuid())+ partnerId String+ name String+ url String @db.LongText+ secret String+ triggers Json+ receiver PostbackReceiver+ disabledAt DateTime?+ createdAt DateTime @default(now())+ updatedAt DateTime @updatedAt++ partner Partner @relation(fields: [partnerId], references: [id], onDelete: Cascade)++ @@index(partnerId)+}diff --git a/packages/tinybird/datasources/dub_postback_events.datasource b/packages/tinybird/datasources/dub_postback_events.datasourcenew file mode 100644index 0000000000..14b9e7d52a--- /dev/null+++ b/packages/tinybird/datasources/dub_postback_events.datasource@@ -0,0 +1,18 @@+TOKEN "dub_tinybird_token" APPEND+++SCHEMA >+ `timestamp` DateTime64(3) `json:$.timestamp` DEFAULT now(),+ `event_id` String `json:$.event_id`,+ `postback_id` String `json:$.postback_id`,+ `url` String `json:$.url`,+ `event` LowCardinality(String) `json:$.event`,+ `response_status` UInt16 `json:$.response_status`,+ `request_body` String `json:$.request_body`,+ `response_body` String `json:$.response_body`,+ `message_id` String `json:$.message_id`,+ `retry_attempt` UInt8 `json:$.retry_attempt`++ENGINE "MergeTree"+ENGINE_PARTITION_KEY "toYYYYMM(timestamp)"+ENGINE_SORTING_KEY "postback_id, event_id, timestamp"diff --git a/packages/tinybird/pipes/get_postback_events.pipe b/packages/tinybird/pipes/get_postback_events.pipenew file mode 100644index 0000000000..0e0449862b--- /dev/null+++ b/packages/tinybird/pipes/get_postback_events.pipe@@ -0,0 +1,24 @@+DESCRIPTION >+ Get partner postback events+++NODE endpoint+SQL >++ %+ SELECT *+ FROM dub_postback_events+ WHERE+ postback_id+ = {{+ String(+ postbackId,+ 'pb_fjs8YfXkgsFL7eF7LOBvbluDb',+ description="The ID of the postback",+ required=True,+ )+ }}+ ORDER BY timestamp DESC+ limit 100++