The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
Intercom integration (#3982)
Kiran Kf008b7605032
diff --git a/apps/web/.env.example b/apps/web/.env.exampleindex 353d65404a..a1c0de4a3d 100644--- a/apps/web/.env.example+++ b/apps/web/.env.example@@ -178,10 +178,14 @@ FIRECRAWL_API_KEY=# for generating planetscale backups (https://planetscale.com/docs/api/service-tokens)PLANETSCALE_SERVICE_TOKEN=-# Hubspot+# Hubspot integrationHUBSPOT_CLIENT_ID=HUBSPOT_CLIENT_SECRET=+# Intercom integration+INTERCOM_CLIENT_ID=+INTERCOM_CLIENT_SECRET=+# E2E Playwright TestsPLAYWRIGHT_BASE_URL=http://partners.localhost:8888E2E_PARTNER_EMAIL=diff --git a/apps/web/app/(ee)/api/intercom/callback/route.ts b/apps/web/app/(ee)/api/intercom/callback/route.tsnew file mode 100644index 0000000000..078e11cf93--- /dev/null+++ b/apps/web/app/(ee)/api/intercom/callback/route.ts@@ -0,0 +1,126 @@+import { DubApiError, handleAndReturnErrorResponse } from "@/lib/api/errors";+import { getSession } from "@/lib/auth";+import { encrypt } from "@/lib/encryption";+import { installIntegration } from "@/lib/integrations/install";+import { Intercom } from "@/lib/integrations/intercom/client";+import { intercomOAuthProvider } from "@/lib/integrations/intercom/oauth";+import { intercomCredentialsSchema } from "@/lib/integrations/intercom/schema";+import { getPlanCapabilities } from "@/lib/plan-capabilities";+import { WorkspaceProps } from "@/lib/types";+import { prisma } from "@dub/prisma";+import { INTERCOM_INTEGRATION_ID } from "@dub/utils";+import { redirect } from "next/navigation";++export const dynamic = "force-dynamic";++// GET /api/intercom/callback - OAuth callback from Intercom+export const GET = async (req: Request) => {+ const { searchParams } = new URL(req.url);++ if (+ process.env.NODE_ENV === "development" &&+ !req.headers.get("host")?.includes("localhost")+ ) {+ return redirect(+ `http://localhost:8888/api/intercom/callback?${searchParams.toString()}`,+ );+ }++ let workspace:+ | (Pick<WorkspaceProps, "id" | "slug" | "users"> & { plan: string })+ | null = null;++ try {+ const session = await getSession();++ if (!session?.user.id) {+ throw new DubApiError({+ code: "unauthorized",+ message: "Unauthorized. Please login to continue.",+ });+ }++ const { token, contextId: workspaceId } =+ await intercomOAuthProvider.exchangeCodeForToken<string>(req);++ workspace = await prisma.project.findUniqueOrThrow({+ where: {+ id: workspaceId,+ },+ select: {+ id: true,+ slug: true,+ plan: true,+ users: {+ where: {+ userId: session.user.id,+ },+ select: {+ role: true,+ defaultFolderId: true,+ },+ },+ },+ });++ if (workspace.users.length === 0) {+ throw new DubApiError({+ code: "bad_request",+ message: "You are not a member of this workspace.",+ });+ }++ if (workspace.users[0].role !== "owner") {+ throw new DubApiError({+ code: "bad_request",+ message: "Only workspace owners can install integrations.",+ });+ }++ if (!getPlanCapabilities(workspace.plan).canInstallAdvancedIntegrations) {+ throw new DubApiError({+ code: "forbidden",+ message:+ "Intercom integration is only available on Advanced and Enterprise plans.",+ });+ }++ const integration = await prisma.integration.findUniqueOrThrow({+ where: {+ id: INTERCOM_INTEGRATION_ID,+ },+ select: {+ id: true,+ },+ });++ const intercom = new Intercom({+ token: token.access_token,+ });++ const admin = await intercom.getAdmin();++ if (!admin.app?.id_code) {+ throw new DubApiError({+ code: "internal_server_error",+ message: "Failed to retrieve Intercom workspace ID.",+ });+ }++ const credentials = intercomCredentialsSchema.parse({+ accessToken: encrypt(token.access_token),+ appId: admin.app?.id_code,+ });++ await installIntegration({+ integrationId: integration.id,+ userId: session.user.id,+ workspaceId,+ credentials,+ });+ } catch (error) {+ return handleAndReturnErrorResponse(error);+ }++ redirect(`/${workspace.slug}/settings/integrations/intercom`);+};diff --git a/apps/web/app/(ee)/api/intercom/webhook/health-check/route.ts b/apps/web/app/(ee)/api/intercom/webhook/health-check/route.tsnew file mode 100644index 0000000000..91aad15175--- /dev/null+++ b/apps/web/app/(ee)/api/intercom/webhook/health-check/route.ts@@ -0,0 +1,66 @@+import { handleAndReturnErrorResponse } from "@/lib/api/errors";+import { withAxiom } from "@/lib/axiom/server";+import {+ intercomCredentialsSchema,+ IntercomHealthCheckResponse,+ intercomHealthCheckWebhookSchema,+} from "@/lib/integrations/intercom/schema";+import { prisma } from "@dub/prisma";+import { INTERCOM_INTEGRATION_ID } from "@dub/utils";+import { NextResponse } from "next/server";+import { verifyWebhookSignature } from "../verify-webhook";++// POST /api/intercom/webhook/health-check – health check for the Intercom webhook+export const POST = withAxiom(async (req) => {+ try {+ const rawBody = await verifyWebhookSignature(req);+ const body = JSON.parse(rawBody);++ const { workspace_id: intercomWorkspaceId } =+ intercomHealthCheckWebhookSchema.parse(body);++ const installation = await prisma.installedIntegration.findFirst({+ where: {+ integrationId: INTERCOM_INTEGRATION_ID,+ credentials: {+ path: "$.appId",+ equals: intercomWorkspaceId,+ },+ },+ select: {+ id: true,+ credentials: true,+ },+ });++ if (!installation) {+ return NextResponse.json<IntercomHealthCheckResponse>({+ state: "UNHEALTHY",+ message: "You need to re-install with Dub to continue using the app.",+ cta_type: "URL_CTA",+ cta_label: "Finish setup",+ cta_url: "https://app.dub.co/settings/integrations/intercom",+ });+ }++ const { success } = intercomCredentialsSchema.safeParse(+ installation.credentials,+ );++ if (!success) {+ return NextResponse.json<IntercomHealthCheckResponse>({+ state: "UNHEALTHY",+ message: "You need to re-install with Dub to continue using the app.",+ cta_type: "URL_CTA",+ cta_label: "Finish setup",+ cta_url: "https://app.dub.co/settings/integrations/intercom",+ });+ }++ return NextResponse.json<IntercomHealthCheckResponse>({+ state: "OK",+ });+ } catch (error) {+ return handleAndReturnErrorResponse(error);+ }+});diff --git a/apps/web/app/(ee)/api/intercom/webhook/process/conversation-admin-replied.ts b/apps/web/app/(ee)/api/intercom/webhook/process/conversation-admin-replied.tsnew file mode 100644index 0000000000..cb5dea33e8--- /dev/null+++ b/apps/web/app/(ee)/api/intercom/webhook/process/conversation-admin-replied.ts@@ -0,0 +1,350 @@+import { createId } from "@/lib/api/create-id";+import { qstash } from "@/lib/cron";+import { decrypt } from "@/lib/encryption";+import { Intercom } from "@/lib/integrations/intercom/client";+import {+ IntercomAttachment,+ IntercomContact,+ intercomConversationRepliedSchema,+ IntercomCredentials,+ intercomCredentialsSchema,+} from "@/lib/integrations/intercom/schema";+import { PROGRAM_ALLOWED_ATTACHMENT_TYPES } from "@/lib/messages/constants";+import { sanitizeFileName } from "@/lib/messages/utils";+import { storage } from "@/lib/storage";+import { prisma } from "@dub/prisma";+import {+ InstalledIntegration,+ Message,+ MessageAttachment,+ Program,+} from "@dub/prisma/client";+import {+ APP_DOMAIN_WITH_NGROK,+ fetchWithTimeout,+ nanoid,+ pluralize,+} from "@dub/utils";+import * as z from "zod/v4";++export async function handleConversationAdminReplied({+ data,+ program,+ installation,+}: {+ data: z.infer<typeof intercomConversationRepliedSchema>;+ program: Pick<Program, "id" | "workspaceId">;+ installation: Pick<InstalledIntegration, "credentials" | "userId">;+}): Promise<string> {+ const credentials = intercomCredentialsSchema.parse(installation.credentials);++ const partners = await identifyPartnersFromContacts({+ contacts: data.item.contacts.contacts,+ program,+ credentials,+ });++ if (partners.length === 0) {+ return `No partners found for ${pluralize("contact", data.item.contacts.contacts.length)} ${data.item.contacts.contacts.map((contact) => contact.id).join(", ")}. Skipping message forwarding.`;+ }++ const { conversation_parts: conversations } = data.item.conversation_parts;+ const createdMessages: Pick<Message, "id" | "programId" | "partnerId">[] = [];++ for (const {+ body,+ attachments,+ author,+ app_package_code: appPackageCode,+ } of conversations) {+ // Skip parts created via the Intercom API (e.g. messages we forward from+ // partners back into Intercom) to avoid echoing them back to partners.+ if (appPackageCode) {+ continue;+ }++ let originalMessage =+ body?.replaceAll(/\[(Image|Attachment|GIF)\]/g, "") || "";++ // Nothing to forward: no text and no attachments+ if (attachments.length === 0 && originalMessage.trim() === "") {+ console.warn("No attachments and no text. Skipping.");+ continue;+ }++ const workspaceUser = await resolveWorkspaceUser({+ workspaceId: program.workspaceId,+ authorEmail: author.email,+ installationUserId: installation.userId,+ });++ if (!workspaceUser) {+ console.warn("No workspace user found. Skipping.");+ continue;+ }++ // Download Intercom attachments and store them in the private R2 bucket+ const { storedAttachments, externalAttachments } =+ await uploadIntercomAttachments({+ attachments,+ programId: program.id,+ });++ // Graceful degradation: only append the URLs we couldn't store+ if (externalAttachments.length > 0) {+ originalMessage += `\n\n${externalAttachments.map((attachment) => `[${attachment.name}](${attachment.url})`).join(", ")}`;+ }++ // Keep the part if it has text or at least one stored attachment+ if (originalMessage.trim() === "" && storedAttachments.length === 0) {+ continue;+ }++ for (const { partnerId } of partners) {+ const messageId = createId({ prefix: "msg_" });++ await prisma.message.create({+ data: {+ id: messageId,+ programId: program.id,+ partnerId,+ senderUserId: workspaceUser.id,+ text: originalMessage,+ ...(storedAttachments.length > 0 && {+ attachments: {+ create: storedAttachments.map((attachment) => ({+ id: createId({ prefix: "msa_" }),+ storageKey: attachment.storageKey,+ name: attachment.name,+ size: attachment.size,+ type: attachment.type,+ })),+ },+ }),+ },+ });++ createdMessages.push({+ id: messageId,+ programId: program.id,+ partnerId,+ });+ }+ }++ // Find the latest message for each partner+ const latestMessageByPartner = new Map<+ string,+ (typeof createdMessages)[number]+ >();++ for (const message of createdMessages) {+ latestMessageByPartner.set(message.partnerId, message);+ }++ await Promise.allSettled(+ [...latestMessageByPartner.values()].map((message) =>+ qstash.publishJSON({+ url: `${APP_DOMAIN_WITH_NGROK}/api/cron/messages/notify-partner`,+ delay: 60 * 3,+ deduplicationId: `${message.programId}-${message.partnerId}`,+ body: {+ programId: message.programId,+ partnerId: message.partnerId,+ lastMessageId: message.id,+ },+ }),+ ),+ );++ return `Message forwarded to ${pluralize("partner", partners.length)}.`;+}++async function resolveWorkspaceUser({+ workspaceId,+ authorEmail,+ installationUserId,+}: {+ workspaceId: string;+ authorEmail: string;+ installationUserId: string;+}) {+ const workspaceUsers = await prisma.projectUsers.findMany({+ where: {+ projectId: workspaceId,+ },+ include: {+ user: {+ select: {+ id: true,+ email: true,+ },+ },+ },+ });++ if (workspaceUsers.length === 0) {+ return null;+ }++ let workspaceUser = workspaceUsers.find(+ ({ user }) => user.email === authorEmail,+ );++ if (!workspaceUser) {+ // Fallback to the person who installed the integration+ workspaceUser = workspaceUsers.find(+ ({ user }) => user.id === installationUserId,+ );++ // Fallback to the first owner+ if (!workspaceUser) {+ workspaceUser = workspaceUsers.find(({ role }) => role === "owner");+ }+ }++ if (!workspaceUser) {+ return null;+ }++ return workspaceUser.user;+}++// Identify partner from Intercom contact ID+async function identifyPartnersFromContacts({+ contacts,+ program,+ credentials,+}: {+ contacts: IntercomContact[];+ program: Pick<Program, "id">;+ credentials: IntercomCredentials;+}): Promise<{ partnerId: string }[]> {+ const intercom = new Intercom({+ token: decrypt(credentials.accessToken),+ });++ const emailAddresses: string[] = [];++ for (const contact of contacts) {+ const contactFound = await intercom.getContactById(contact.id);++ if (!contactFound || !contactFound.email) {+ continue;+ }++ emailAddresses.push(contactFound.email.toLowerCase());+ }++ if (emailAddresses.length === 0) {+ return [];+ }++ const partners = await prisma.partner.findMany({+ where: {+ email: {+ in: emailAddresses,+ },+ },+ select: {+ id: true,+ },+ });++ if (partners.length === 0) {+ return [];+ }++ const programEnrollments = await prisma.programEnrollment.findMany({+ where: {+ programId: program.id,+ partnerId: {+ in: partners.map((partner) => partner.id),+ },+ },+ select: {+ partnerId: true,+ },+ });++ return programEnrollments.map(({ partnerId }) => ({ partnerId }));+}++// Download Intercom attachments and upload them to the private R2 bucket so they+// can be stored as MessageAttachment rows+async function uploadIntercomAttachments({+ attachments,+ programId,+}: {+ attachments: IntercomAttachment[];+ programId: string;+}) {+ const storedAttachments: Pick<+ MessageAttachment,+ "name" | "type" | "size" | "storageKey"+ >[] = [];++ const externalAttachments: { name: string; url: string }[] = [];++ for (const attachment of attachments) {+ try {+ const response = await fetchWithTimeout(+ attachment.url,+ {+ redirect: "error",+ },+ 30000,+ );++ if (+ !PROGRAM_ALLOWED_ATTACHMENT_TYPES.includes(+ attachment.content_type as (typeof PROGRAM_ALLOWED_ATTACHMENT_TYPES)[number],+ )+ ) {+ throw new Error(+ `Unsupported attachment type: ${attachment.content_type}`,+ );+ }++ if (!response.ok) {+ throw new Error(`Failed to fetch attachment: ${response.status}`);+ }++ const blob = await response.blob();++ const name = (attachment.name.trim() || "attachment").slice(0, 191);+ const storageKey = `messages/${programId}/${nanoid(10)}/${sanitizeFileName(name)}`;++ await storage.upload({+ key: storageKey,+ body: blob,+ bucket: "private",+ opts: {+ contentType: attachment.content_type,+ },+ });++ storedAttachments.push({+ name: attachment.name?.trim() || "attachment",+ type: attachment.content_type,+ size: attachment.filesize,+ storageKey,+ });+ } catch (error) {+ console.error(+ `[Intercom] Failed to store attachment ${attachment.url}`,+ error,+ );++ externalAttachments.push({+ name: attachment.name?.trim() || "attachment",+ url: attachment.url,+ });+ }+ }++ return {+ storedAttachments,+ externalAttachments,+ };+}diff --git a/apps/web/app/(ee)/api/intercom/webhook/process/route.ts b/apps/web/app/(ee)/api/intercom/webhook/process/route.tsnew file mode 100644index 0000000000..5b27b9cb92--- /dev/null+++ b/apps/web/app/(ee)/api/intercom/webhook/process/route.ts@@ -0,0 +1,124 @@+import { captureWebhookLog } from "@/lib/api-logs/capture-webhook-log";+import { handleAndReturnErrorResponse } from "@/lib/api/errors";+import { withAxiom } from "@/lib/axiom/server";+import { verifyQstashSignature } from "@/lib/cron/verify-qstash";+import { intercomWebhookSchema } from "@/lib/integrations/intercom/schema";+import { prisma } from "@dub/prisma";+import { INTERCOM_INTEGRATION_ID } from "@dub/utils";+import { logAndRespond } from "../../../cron/utils";+import { handleConversationAdminReplied } from "./conversation-admin-replied";++// POST /api/intercom/webhook/process+export const POST = withAxiom(async (req) => {+ const startTime = Date.now();++ let body: any;+ let workspaceId: string | undefined;++ try {+ const rawBody = await req.text();++ await verifyQstashSignature({+ req,+ rawBody,+ });++ body = JSON.parse(rawBody);++ const {+ topic,+ data,+ app_id: intercomWorkspaceId,+ } = intercomWebhookSchema.parse(body);++ // Find the installation+ const installation = await prisma.installedIntegration.findFirst({+ where: {+ integrationId: INTERCOM_INTEGRATION_ID,+ credentials: {+ path: "$.appId",+ equals: intercomWorkspaceId,+ },+ },+ include: {+ project: {+ select: {+ id: true,+ programs: {+ select: {+ id: true,+ deactivatedAt: true,+ workspaceId: true,+ },+ },+ },+ },+ },+ });++ if (!installation) {+ return logAndRespond(+ `[Intercom] Installation not found for Intercom workspace ${intercomWorkspaceId}.`,+ );+ }++ workspaceId = installation.projectId;++ const {+ project: { programs },+ } = installation;++ const program = programs?.[0];++ if (!program) {+ return logAndRespond(+ `[Intercom] No programs found for Intercom workspace ${intercomWorkspaceId}.`,+ );+ }++ if (program.deactivatedAt) {+ return logAndRespond(`[Intercom] Program ${program.id} is deactivated.`);+ }++ let response: Awaited<ReturnType<typeof handleConversationAdminReplied>> =+ "";++ if (topic === "conversation.admin.replied") {+ response = await handleConversationAdminReplied({+ data,+ program,+ installation,+ });+ }++ await captureWebhookLog({+ workspaceId,+ method: "POST",+ path: "/intercom/webhook",+ statusCode: 200,+ duration: Date.now() - startTime,+ requestBody: body,+ responseBody: response,+ userAgent: req.headers.get("user-agent"),+ });++ return logAndRespond(response);+ } catch (error) {+ const response = handleAndReturnErrorResponse(error);++ if (workspaceId) {+ await captureWebhookLog({+ workspaceId,+ method: "POST",+ path: "/intercom/webhook",+ statusCode: response.status,+ duration: Date.now() - startTime,+ requestBody: body,+ responseBody: response,+ userAgent: req.headers.get("user-agent"),+ });+ }++ return response;+ }+});diff --git a/apps/web/app/(ee)/api/intercom/webhook/route.ts b/apps/web/app/(ee)/api/intercom/webhook/route.tsnew file mode 100644index 0000000000..ecb42f4667--- /dev/null+++ b/apps/web/app/(ee)/api/intercom/webhook/route.ts@@ -0,0 +1,45 @@+import { handleAndReturnErrorResponse } from "@/lib/api/errors";+import { withAxiom } from "@/lib/axiom/server";+import { enqueueBatchJobs } from "@/lib/cron/enqueue-batch-jobs";+import { intercomWebhookSchema } from "@/lib/integrations/intercom/schema";+import { APP_DOMAIN_WITH_NGROK } from "@dub/utils";+import { logAndRespond } from "../../cron/utils";+import { verifyWebhookSignature } from "./verify-webhook";++const relevantTopics = new Set(["conversation.admin.replied", "ping"]);++// POST /api/intercom/webhook – listen to webhook events from Intercom+export const POST = withAxiom(async (req) => {+ try {+ const rawBody = await verifyWebhookSignature(req);+ const body = JSON.parse(rawBody);++ const { topic } = intercomWebhookSchema.parse(body);++ if (!relevantTopics.has(topic)) {+ return logAndRespond(`[Intercom] Unsupported topic: ${topic}.`);+ }++ if (topic === "ping") {+ return logAndRespond("Received ping event. No action required.");+ }++ const qstashResponse = await enqueueBatchJobs([+ {+ queueName: "process-intercom-webhook",+ url: `${APP_DOMAIN_WITH_NGROK}/api/intercom/webhook/process`,+ method: "POST",+ body,+ },+ ]);++ console.log(+ `[intercom/webhook] Enqueued webhook event to be processed.`,+ qstashResponse,+ );++ return logAndRespond("Webhook received.");+ } catch (error) {+ return handleAndReturnErrorResponse(error);+ }+});diff --git a/apps/web/app/(ee)/api/intercom/webhook/uninstall/route.ts b/apps/web/app/(ee)/api/intercom/webhook/uninstall/route.tsnew file mode 100644index 0000000000..a5f743bd46--- /dev/null+++ b/apps/web/app/(ee)/api/intercom/webhook/uninstall/route.ts@@ -0,0 +1,49 @@+import { handleAndReturnErrorResponse } from "@/lib/api/errors";+import { withAxiom } from "@/lib/axiom/server";+import { intercomUninstallWebhookSchema } from "@/lib/integrations/intercom/schema";+import { prisma } from "@dub/prisma";+import { INTERCOM_INTEGRATION_ID } from "@dub/utils";+import { logAndRespond } from "../../../cron/utils";+import { verifyWebhookSignature } from "../verify-webhook";++// POST /api/intercom/webhook/uninstall – notified when someone uninstalls the app or revokes access through any means+export const POST = withAxiom(async (req) => {+ try {+ const rawBody = await verifyWebhookSignature(req);+ const body = JSON.parse(rawBody);++ const { app_id: intercomWorkspaceId } =+ intercomUninstallWebhookSchema.parse(body);++ const installation = await prisma.installedIntegration.findFirst({+ where: {+ integrationId: INTERCOM_INTEGRATION_ID,+ credentials: {+ path: "$.appId",+ equals: intercomWorkspaceId,+ },+ },+ select: {+ id: true,+ },+ });++ if (!installation) {+ return logAndRespond(+ `[Intercom] Installation not found for Intercom workspace ${intercomWorkspaceId}.`,+ );+ }++ await prisma.installedIntegration.delete({+ where: {+ id: installation.id,+ },+ });++ return logAndRespond(+ "[Intercom] Removed Intercom installation from the workspace.",+ );+ } catch (error) {+ return handleAndReturnErrorResponse(error);+ }+});diff --git a/apps/web/app/(ee)/api/intercom/webhook/verify-webhook.ts b/apps/web/app/(ee)/api/intercom/webhook/verify-webhook.tsnew file mode 100644index 0000000000..ff31d5dcc5--- /dev/null+++ b/apps/web/app/(ee)/api/intercom/webhook/verify-webhook.ts@@ -0,0 +1,54 @@+import { DubApiError } from "@/lib/api/errors";+import crypto from "crypto";++const INTERCOM_CLIENT_SECRET = process.env.INTERCOM_CLIENT_SECRET || "";++export async function verifyWebhookSignature(req: Request): Promise<string> {+ const rawBody = await req.text();+ const signature = req.headers.get("X-Hub-Signature");++ if (!signature) {+ throw new DubApiError({+ code: "bad_request",+ message: "Missing X-Hub-Signature header.",+ });+ }++ if (!INTERCOM_CLIENT_SECRET) {+ throw new DubApiError({+ code: "internal_server_error",+ message: "Missing INTERCOM_CLIENT_SECRET environment variable.",+ });+ }++ const expectedSignature =+ "sha1=" ++ crypto+ .createHmac("sha1", INTERCOM_CLIENT_SECRET)+ .update(rawBody)+ .digest("hex");++ const providedSignature = Buffer.from(signature, "utf8");+ const expectedSignatureBuffer = Buffer.from(expectedSignature, "utf8");++ if (providedSignature.length !== expectedSignatureBuffer.length) {+ throw new DubApiError({+ code: "unauthorized",+ message: "Invalid webhook signature.",+ });+ }++ const isSignatureValid = crypto.timingSafeEqual(+ Uint8Array.from(providedSignature),+ Uint8Array.from(expectedSignatureBuffer),+ );++ if (!isSignatureValid) {+ throw new DubApiError({+ code: "unauthorized",+ message: "Invalid webhook signature.",+ });+ }++ return rawBody;+}diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/integrations/[integrationSlug]/page-client.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/integrations/[integrationSlug]/page-client.tsxindex adc446637d..1814eb61b1 100644--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/integrations/[integrationSlug]/page-client.tsx+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/integrations/[integrationSlug]/page-client.tsx@@ -54,7 +54,10 @@ import {STRIPE_INTEGRATION_ID,ZAPIER_INTEGRATION_ID,} from "@dub/utils";-import { HUBSPOT_INTEGRATION_ID } from "@dub/utils/src/constants/integrations";+import {+ HUBSPOT_INTEGRATION_ID,+ INTERCOM_INTEGRATION_ID,+} from "@dub/utils/src/constants/integrations";import { useAction } from "next-safe-action/hooks";import Link from "next/link";import { useMemo, useState } from "react";@@ -340,9 +343,12 @@ export default function IntegrationPageClient({className="h-9 px-3"icon={<ConnectedDots className="size-4" />}disabledTooltip={- [HUBSPOT_INTEGRATION_ID, APPSFLYER_INTEGRATION_ID].includes(- integration.id,- ) && !canInstallAdvancedIntegrations ? (+ [+ HUBSPOT_INTEGRATION_ID,+ APPSFLYER_INTEGRATION_ID,+ INTERCOM_INTEGRATION_ID,+ ].includes(integration.id) &&+ !canInstallAdvancedIntegrations ? (<TooltipContenttitle="This integration is only available on Advanced and Enterprise plans."cta="Upgrade to Advanced"diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/integrations/integrations-cards.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/integrations/integrations-cards.tsxindex b7577043f6..27cf631f23 100644--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/integrations/integrations-cards.tsx+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/integrations/integrations-cards.tsx@@ -18,6 +18,7 @@ const CATEGORY_ORDER = ["Productivity","CMS","Miscellaneous",+ "Communication",] as const;const PRESENCE_ANIMATION = {diff --git a/apps/web/lib/actions/get-integration-install-url.ts b/apps/web/lib/actions/get-integration-install-url.tsindex df4460f51b..84864132fa 100644--- a/apps/web/lib/actions/get-integration-install-url.ts+++ b/apps/web/lib/actions/get-integration-install-url.ts@@ -2,6 +2,7 @@import * as z from "zod/v4";import { hubSpotOAuthProvider } from "../integrations/hubspot/oauth";+import { intercomOAuthProvider } from "../integrations/intercom/oauth";import { slackOAuthProvider } from "../integrations/slack/oauth";import { authActionClient } from "./safe-action";import { throwIfNoPermission } from "./throw-if-no-permission";@@ -29,6 +30,8 @@ export const getIntegrationInstallUrl = authActionClienturl = await slackOAuthProvider.generateAuthUrl(workspace.id);} else if (integrationSlug === "hubspot") {url = await hubSpotOAuthProvider.generateAuthUrl(workspace.id);+ } else if (integrationSlug === "intercom") {+ url = await intercomOAuthProvider.generateAuthUrl(workspace.id);} else {throw new Error("Invalid integration slug");}diff --git a/apps/web/lib/api-logs/constants.ts b/apps/web/lib/api-logs/constants.tsindex d672c79b8f..ebd15003ce 100644--- a/apps/web/lib/api-logs/constants.ts+++ b/apps/web/lib/api-logs/constants.ts@@ -2,6 +2,7 @@ import type { PlanProps } from "@/lib/types";import {APPSFLYER_INTEGRATION_ID,HUBSPOT_INTEGRATION_ID,+ INTERCOM_INTEGRATION_ID,SHOPIFY_INTEGRATION_ID,STRIPE_INTEGRATION_ID,} from "@dub/utils";@@ -133,6 +134,12 @@ export const WEBHOOK_REQUEST_ACTORS_BY_PATH = {image:"https://dubassets.com/integrations/int_ffw3qgrFAahY6qs1hXaH3wHS_JPoCPOh",},+ "/intercom/webhook": {+ id: INTERCOM_INTEGRATION_ID,+ name: "Intercom",+ image:+ "https://dubassets.com/integrations/int_ffw3qgrFAahY6qs1hXaH3wHS_JPoCPOh",+ },} as const;export const PUBLISHABLE_KEY_ACTOR = {diff --git a/apps/web/lib/cron/enqueue-batch-jobs.ts b/apps/web/lib/cron/enqueue-batch-jobs.tsindex 789b7e378e..9737c749db 100644--- a/apps/web/lib/cron/enqueue-batch-jobs.ts+++ b/apps/web/lib/cron/enqueue-batch-jobs.ts@@ -9,38 +9,35 @@ type EnqueueBatchJobsProps = PublishBatchRequest<unknown> & {| "create-discount-code"| "sync-bounty-social-metrics"| "process-hubspot-webhook"+ | "process-intercom-webhook"| "delete-discount-code"| "create-referral-commissions";};// Generic helper to enqueue a batch of QStash jobs.export async function enqueueBatchJobs(jobs: EnqueueBatchJobsProps[]) {- try {- const result = await qstash.batchJSON(jobs);+ const maxRetries = 3;- console.log(- `[enqueueBatchJobs] ${result.length} batch jobs enqueued successfully.`,- {- result,- jobs,- },- );+ for (let attempt = 0; attempt <= maxRetries; attempt++) {+ try {+ return await qstash.batchJSON(jobs);+ } catch (error) {+ if (attempt < maxRetries) {+ await new Promise((resolve) =>+ setTimeout(resolve, 1000 * Math.pow(2, attempt)),+ );+ continue;+ }- return result;- } catch (error) {- console.error("[enqueueBatchJobs] Failed to enqueue batch jobs", {- error: JSON.stringify(error, null, 2),- jobs,- });+ await log({+ message: `[enqueueBatchJobs] Failed to enqueue batch jobs: ${JSON.stringify(error, null, 2)}`,+ type: "errors",+ mention: true,+ });- await log({- message: `[enqueueBatchJobs] Failed to enqueue batch jobs: ${JSON.stringify(error, null, 2)}`,- type: "errors",- mention: true,- });-- throw new Error(- `Failed to enqueue batch jobs: ${JSON.stringify(error, null, 2)}`,- );+ throw new Error(+ `Failed to enqueue batch jobs: ${JSON.stringify(error, null, 2)}`,+ );+ }}}diff --git a/apps/web/lib/integrations/intercom/client.ts b/apps/web/lib/integrations/intercom/client.tsnew file mode 100644index 0000000000..dd165ebe0c--- /dev/null+++ b/apps/web/lib/integrations/intercom/client.ts@@ -0,0 +1,198 @@+import { Message, Partner } from "@dub/prisma/client";+import { IntercomClient } from "intercom-client";++interface IntercomContact {+ id: string;+}++interface IntercomAdmin {+ id: string;+}++interface IntercomConversation {+ id: string;+}++export interface IntercomAttachmentFile {+ content_type: string;+ data: string;+ name: string;+}++export class Intercom {+ private client: IntercomClient;++ constructor({ token }: { token: string }) {+ this.client = new IntercomClient({ token });+ }++ // Get currently authorised admin+ async getAdmin() {+ const admin = await this.client.admins.identify();++ if (!admin) {+ throw new Error("[Intercom] Failed to identify admin.");+ }++ return admin;+ }++ async findAdminByEmail(email: string): Promise<IntercomAdmin | null> {+ const { admins } = await this.client.admins.list();++ const admin = admins?.find(+ (admin) => admin?.email?.toLowerCase() === email.toLowerCase(),+ );++ if (!admin?.id) {+ return null;+ }++ return {+ id: admin.id,+ };+ }++ async searchContactByEmail(email: string) {+ const { data: contacts } = await this.client.contacts.search({+ query: {+ field: "email",+ operator: "=",+ value: email,+ },+ });++ if (contacts.length === 0) {+ return null;+ }++ return contacts[0];+ }++ async getContactById(id: string) {+ return await this.client.contacts.find({+ contact_id: id,+ });+ }++ async createContact(+ partner: Pick<Partner, "id" | "email" | "name" | "image">,+ ) {+ return await this.client.contacts.create({+ name: partner.name,+ email: partner.email!,+ role: "user",+ avatar: partner.image ?? undefined,+ });+ }++ async getOrCreateContact(+ partner: Pick<Partner, "id" | "email" | "name" | "image">,+ ) {+ const contact = await this.searchContactByEmail(partner.email!);++ if (!contact) {+ return await this.createContact(partner);+ }++ return contact;+ }++ async createConversationAsContact({+ contact,+ message,+ attachmentUrls,+ }: {+ contact: IntercomContact;+ message: Pick<Message, "text">;+ attachmentUrls?: string[];+ }) {+ return await this.client.conversations.create({+ from: {+ type: "user",+ id: contact.id,+ },+ body: message.text,+ // The SDK's CreateConversationRequest type omits attachment_urls, but Intercom's+ // API (OpenAPI 2.14) supports it and the SDK sends the request body as-is.+ ...(attachmentUrls?.length && { attachment_urls: attachmentUrls }),+ } as Parameters<IntercomClient["conversations"]["create"]>[0]);+ }++ async replyAsContact({+ message,+ contact,+ conversation,+ attachmentUrls,+ attachmentFiles,+ }: {+ message: Pick<Message, "text">;+ contact: IntercomContact;+ conversation: IntercomConversation;+ attachmentUrls?: string[];+ attachmentFiles?: IntercomAttachmentFile[];+ }) {+ return await this.client.conversations.reply({+ conversation_id: conversation.id,+ body: {+ message_type: "comment",+ type: "user",+ intercom_user_id: contact.id,+ body: message.text,+ attachment_urls: attachmentUrls?.length ? attachmentUrls : undefined,+ attachment_files: attachmentFiles?.length ? attachmentFiles : undefined,+ },+ });+ }++ async createConversationAsAdmin({+ admin,+ contact,+ message,+ }: {+ admin: IntercomAdmin;+ contact: IntercomContact;+ message: Pick<Message, "text">;+ }) {+ return await this.client.messages.create({+ message_type: "inapp",+ body: message.text,+ template: "plain",+ from: {+ type: "admin",+ id: Number(admin.id),+ },+ to: {+ type: "user",+ id: contact.id,+ },+ create_conversation_without_contact_reply: true,+ });+ }++ async replyAsAdmin({+ admin,+ message,+ conversation,+ attachmentUrls,+ attachmentFiles,+ }: {+ admin: IntercomAdmin;+ message: Pick<Message, "text">;+ conversation: IntercomConversation;+ attachmentUrls?: string[];+ attachmentFiles?: IntercomAttachmentFile[];+ }) {+ return await this.client.conversations.reply({+ conversation_id: conversation.id,+ body: {+ message_type: "comment",+ type: "admin",+ admin_id: admin.id,+ body: message.text || undefined,+ attachment_urls: attachmentUrls?.length ? attachmentUrls : undefined,+ attachment_files: attachmentFiles?.length ? attachmentFiles : undefined,+ },+ });+ }+}diff --git a/apps/web/lib/integrations/intercom/forward-message.ts b/apps/web/lib/integrations/intercom/forward-message.tsnew file mode 100644index 0000000000..9e572b7c47--- /dev/null+++ b/apps/web/lib/integrations/intercom/forward-message.ts@@ -0,0 +1,234 @@+import { decrypt } from "@/lib/encryption";+import { storage } from "@/lib/storage";+import { redis } from "@/lib/upstash";+import {+ InstalledIntegration,+ Message,+ MessageAttachment,+ Partner,+ Program,+ User,+} from "@dub/prisma/client";+import { Intercom, IntercomAttachmentFile } from "./client";+import { intercomCredentialsSchema } from "./schema";++export async function forwardPartnerMessageToIntercom({+ program,+ partner,+ message,+ intercomInstallation,+}: {+ program: Pick<Program, "id" | "workspaceId">;+ partner: Pick<Partner, "id" | "email" | "name" | "image">;+ message: Pick<Message, "id" | "text"> & {+ attachments: MessageAttachment[];+ };+ intercomInstallation: Pick<InstalledIntegration, "id" | "credentials"> | null;+}) {+ if (!partner.email) {+ return;+ }++ if (!intercomInstallation) {+ console.log(+ `[Intercom] Installation not found for program ${program.id}. Skipping forward message.`,+ );+ return;+ }++ const credentials = intercomCredentialsSchema.parse(+ intercomInstallation.credentials,+ );++ const intercom = new Intercom({+ token: decrypt(credentials.accessToken),+ });++ const contact = await intercom.getOrCreateContact(partner);+ const redisKey = `intercom:thread:${credentials.appId}:${program.id}:${partner.id}`;+ let conversationId = await redis.get<string>(redisKey);++ const { attachmentUrls, attachmentFiles } = await buildIntercomAttachments(+ message.attachments,+ );++ // If no conversation exists, create a new one+ // and store the conversation ID in Redis for future use+ if (!conversationId) {+ const conversation = await intercom.createConversationAsContact({+ contact,+ message,+ attachmentUrls,+ });++ conversationId = conversation.conversation_id;++ await redis.set(redisKey, conversationId);++ // Conversation creation can't carry non-image files; send any as a follow-up reply+ if (attachmentFiles.length > 0) {+ await intercom.replyAsContact({+ contact,+ message,+ conversation: {+ id: conversationId,+ },+ attachmentFiles,+ });+ }++ return;+ }++ // If a conversation exists, reply to it+ await intercom.replyAsContact({+ contact,+ message,+ conversation: {+ id: conversationId,+ },+ attachmentUrls,+ attachmentFiles,+ });+}++export async function forwardProgramMessageToIntercom({+ program,+ partner,+ message,+ intercomInstallation,+}: {+ program: Pick<Program, "id" | "workspaceId">;+ partner: Pick<Partner, "id" | "email" | "name" | "image">;+ message: Pick<Message, "id" | "text"> & {+ senderUser: Pick<User, "email"> | null;+ attachments: MessageAttachment[];+ };+ intercomInstallation: Pick<InstalledIntegration, "id" | "credentials">;+}) {+ if (!partner.email || !message.senderUser?.email) {+ return;+ }++ const credentials = intercomCredentialsSchema.parse(+ intercomInstallation.credentials,+ );++ const intercom = new Intercom({+ token: decrypt(credentials.accessToken),+ });++ const admin = await intercom.findAdminByEmail(message.senderUser.email);++ if (!admin) {+ console.log(+ `[Intercom] Admin not found for email ${message.senderUser.email}. Skipping forward message.`,+ );+ return;+ }++ const contact = await intercom.getOrCreateContact(partner);+ const redisKey = `intercom:thread:${credentials.appId}:${program.id}:${partner.id}`;+ let conversationId = await redis.get<string>(redisKey);++ const { attachmentUrls, attachmentFiles } = await buildIntercomAttachments(+ message.attachments,+ );++ const hasAttachments =+ attachmentUrls.length > 0 || attachmentFiles.length > 0;++ if (!conversationId) {+ const conversation = await intercom.createConversationAsAdmin({+ admin,+ contact,+ message,+ });++ conversationId = conversation.conversation_id;++ await redis.set(redisKey, conversationId);++ // Conversation creation can't carry non-image files; send them as an attachments-only admin reply+ if (hasAttachments) {+ await intercom.replyAsAdmin({+ admin,+ message: {+ text: "",+ },+ conversation: {+ id: conversationId,+ },+ attachmentUrls,+ attachmentFiles,+ });+ }++ return;+ }++ await intercom.replyAsAdmin({+ admin,+ message,+ conversation: {+ id: conversationId,+ },+ attachmentUrls,+ attachmentFiles,+ });+}++// Prepare Dub message attachments (stored in private R2) for forwarding to Intercom.+// Intercom only honors ONE of attachment_urls / attachment_files per reply — when both+// are present it keeps the URLs and silently drops the files. So we never mix them:+// - all images → signed URLs (Intercom fetches them; lightweight, and the only form+// the create-conversation endpoint accepts)+// - otherwise → send everything (images included) inline as base64, so a mixed+// image + PDF message delivers both.+async function buildIntercomAttachments(+ attachments: MessageAttachment[],+): Promise<{+ attachmentUrls: string[];+ attachmentFiles: { content_type: string; data: string; name: string }[];+}> {+ const attachmentUrls: string[] = [];+ const attachmentFiles: IntercomAttachmentFile[] = [];++ const allImages = attachments.every((attachment) =>+ attachment.type.startsWith("image/"),+ );++ for (const attachment of attachments) {+ try {+ const signedUrl = await storage.getSignedDownloadUrl({+ key: attachment.storageKey,+ bucket: "private",+ expiresIn: 30 * 60,+ });++ if (allImages) {+ attachmentUrls.push(signedUrl);+ continue;+ }++ const response = await fetch(signedUrl);+ const buffer = Buffer.from(await response.arrayBuffer());++ attachmentFiles.push({+ content_type: attachment.type,+ data: buffer.toString("base64"),+ name: attachment.name,+ });+ } catch (error) {+ console.error(+ `[Intercom] Failed to prepare attachment ${attachment.storageKey} for forwarding`,+ error,+ );+ }+ }++ return {+ attachmentUrls,+ attachmentFiles,+ };+}diff --git a/apps/web/lib/integrations/intercom/oauth.ts b/apps/web/lib/integrations/intercom/oauth.tsnew file mode 100644index 0000000000..a092843c96--- /dev/null+++ b/apps/web/lib/integrations/intercom/oauth.ts@@ -0,0 +1,24 @@+import { APP_DOMAIN } from "@dub/utils";+import { OAuthProvider, OAuthProviderConfig } from "../oauth-provider";+import { intercomAuthTokenSchema } from "./schema";++class IntercomOAuthProvider extends OAuthProvider<+ typeof intercomAuthTokenSchema+> {+ constructor(provider: OAuthProviderConfig<typeof intercomAuthTokenSchema>) {+ super(provider);+ }+}++export const intercomOAuthProvider = new IntercomOAuthProvider({+ name: "Intercom",+ clientId: process.env.INTERCOM_CLIENT_ID!,+ clientSecret: process.env.INTERCOM_CLIENT_SECRET!,+ authUrl: "https://app.intercom.com/oauth",+ tokenUrl: "https://api.intercom.io/auth/eagle/token",+ redirectUri: `${APP_DOMAIN}/api/intercom/callback`,+ redisStatePrefix: "intercom:oauth:state",+ tokenSchema: intercomAuthTokenSchema,+ bodyFormat: "json",+ authorizationMethod: "body",+});diff --git a/apps/web/lib/integrations/intercom/schema.ts b/apps/web/lib/integrations/intercom/schema.tsnew file mode 100644index 0000000000..54881f4217--- /dev/null+++ b/apps/web/lib/integrations/intercom/schema.ts@@ -0,0 +1,103 @@+import * as z from "zod/v4";++export const intercomAuthTokenSchema = z.object({+ access_token: z.string(),+ token_type: z.string(),+});++// Integration credentials Dub stores+export const intercomCredentialsSchema = z.object({+ accessToken: z.string(),+ appId: z.string().describe("Intercom workspace ID."),+});++export const intercomContactSchema = z.object({+ id: z.string(),+ external_id: z.string().nullable(),+});++export const intercomUninstallWebhookSchema = z.object({+ app_id: z.string(),+});++export const intercomHealthCheckWebhookSchema = z.object({+ workspace_id: z.string(),+});++const intercomHealthCheckResponseSchema = z.discriminatedUnion("state", [+ z.object({+ state: z.literal("OK"),+ }),++ z.object({+ state: z.literal("UNHEALTHY"),+ message: z.string(),+ cta_type: z.literal("URL_CTA"),+ cta_label: z.string(),+ cta_url: z.url(),+ }),+]);++export const intercomAttachmentSchema = z.object({+ type: z.string(),+ name: z.string(),+ url: z.url(),+ content_type: z.string(),+ filesize: z.number(),+});++export const intercomConversationRepliedSchema = z.object({+ item: z.object({+ id: z.string(),+ type: z.string(),+ contacts: z.object({+ contacts: z.array(intercomContactSchema),+ }),+ conversation_parts: z.object({+ conversation_parts: z.array(+ z.object({+ type: z.string(),+ id: z.string(),+ body: z.string().nullable(),+ author: z.object({+ type: z.string(),+ id: z.string(),+ name: z.string(),+ email: z.string(),+ }),+ attachments: z.array(intercomAttachmentSchema),+ app_package_code: z+ .string()+ .nullable()+ .describe(+ "The app package code if this part was created via API. null if the part was not created via API.",+ ),+ }),+ ),+ }),+ }),+});++export const intercomWebhookSchema = z.discriminatedUnion("topic", [+ z.object({+ topic: z.literal("conversation.admin.replied"),+ app_id: z.string(),+ data: intercomConversationRepliedSchema,+ }),++ z.object({+ topic: z.literal("ping"),+ app_id: z.string(),+ data: z.unknown(),+ }),+]);++export type IntercomCredentials = z.infer<typeof intercomCredentialsSchema>;++export type IntercomContact = z.infer<typeof intercomContactSchema>;++export type IntercomAttachment = z.infer<typeof intercomAttachmentSchema>;++export type IntercomHealthCheckResponse = z.infer<+ typeof intercomHealthCheckResponseSchema+>;diff --git a/apps/web/lib/messages/message-partner.ts b/apps/web/lib/messages/message-partner.tsindex 3ebcf78160..28e08cbb04 100644--- a/apps/web/lib/messages/message-partner.ts+++ b/apps/web/lib/messages/message-partner.ts@@ -6,10 +6,10 @@ import { getNetworkInvitesUsage } from "@/lib/api/partners/get-network-invites-uimport { partnerReachableByProgramWhereInput } from "@/lib/api/partners/partner-reachable-by-program-where-input";import { getDefaultProgramIdOrThrow } from "@/lib/api/programs/get-default-program-id-or-throw";import { qstash } from "@/lib/cron";+import { forwardProgramMessageToIntercom } from "@/lib/integrations/intercom/forward-message";import { getPlanCapabilities } from "@/lib/plan-capabilities";import { prisma } from "@dub/prisma";-import { APP_DOMAIN_WITH_NGROK } from "@dub/utils";-import { waitUntil } from "@vercel/functions";+import { APP_DOMAIN_WITH_NGROK, INTERCOM_INTEGRATION_ID } from "@dub/utils";import * as z from "zod/v4";import { authActionClient } from "../actions/safe-action";import { throwIfNoPermission } from "../actions/throw-if-no-permission";@@ -48,31 +48,32 @@ export const messagePartnerAction = authActionClient}// Make sure partner is either approved or trusted in the partner network, enrolled in the program, or already has a message with the program- const { _count, programs } = await prisma.partner.findFirstOrThrow({- where: {- id: partnerId,- ...partnerReachableByProgramWhereInput(programId),- },- include: {- _count: {- select: {- messages: {- where: {- programId,+ const { _count, programs, ...partner } =+ await prisma.partner.findFirstOrThrow({+ where: {+ id: partnerId,+ ...partnerReachableByProgramWhereInput(programId),+ },+ include: {+ _count: {+ select: {+ messages: {+ where: {+ programId,+ },},},},- },- programs: {- where: {- programId,- },- select: {- status: true,+ programs: {+ where: {+ programId,+ },+ select: {+ status: true,+ },},},- },- });+ });// if the partner is not enrolled / is in invited status, cap at one messageconst enrollment = programs[0];@@ -152,17 +153,38 @@ export const messagePartnerAction = authActionClient},});- waitUntil(- qstash.publishJSON({- url: `${APP_DOMAIN_WITH_NGROK}/api/cron/messages/notify-partner`,- body: {- programId,- partnerId,- lastMessageId: message.id,+ (async () => {+ const intercomInstallation = await prisma.installedIntegration.findFirst({+ where: {+ projectId: workspace.id,+ integrationId: INTERCOM_INTEGRATION_ID,},- delay: 60 * 3, // 3 minute delay for a chance to read + batching multiple messages- }),- );+ select: {+ id: true,+ credentials: true,+ },+ });++ await Promise.allSettled([+ qstash.publishJSON({+ url: `${APP_DOMAIN_WITH_NGROK}/api/cron/messages/notify-partner`,+ body: {+ programId,+ partnerId,+ lastMessageId: message.id,+ },+ delay: 60 * 3, // 3 minute delay for a chance to read + batching multiple messages+ }),++ intercomInstallation &&+ forwardProgramMessageToIntercom({+ program: { id: programId, workspaceId: workspace.id },+ partner,+ message,+ intercomInstallation,+ }),+ ]);+ })();return {message: MessageSchema.parse(message),diff --git a/apps/web/lib/messages/message-program.ts b/apps/web/lib/messages/message-program.tsindex 051e6bcffc..a289a56f3a 100644--- a/apps/web/lib/messages/message-program.ts+++ b/apps/web/lib/messages/message-program.ts@@ -2,8 +2,9 @@import { createId } from "@/lib/api/create-id";import { qstash } from "@/lib/cron";+import { forwardPartnerMessageToIntercom } from "@/lib/integrations/intercom/forward-message";import { prisma } from "@dub/prisma";-import { APP_DOMAIN_WITH_NGROK } from "@dub/utils";+import { APP_DOMAIN_WITH_NGROK, INTERCOM_INTEGRATION_ID } from "@dub/utils";import { waitUntil } from "@vercel/functions";import { authPartnerActionClient } from "../actions/safe-action";import { MessageSchema, messageProgramSchema } from "./schemas";@@ -23,6 +24,7 @@ export const messageProgramAction = authPartnerActionClientconst program = await prisma.program.findFirstOrThrow({select: {id: true,+ workspaceId: true,},where: {slug: programSlug,@@ -97,15 +99,42 @@ export const messageProgramAction = authPartnerActionClient});waitUntil(- qstash.publishJSON({- url: `${APP_DOMAIN_WITH_NGROK}/api/cron/messages/notify-program`,- body: {- programId: program.id,- partnerId: partner.id,- lastMessageId: message.id,- },- delay: 60 * 3, // 3 minute delay for a chance to read + batching multiple messages- }),+ (async () => {+ const intercomInstallation =+ await prisma.installedIntegration.findFirst({+ where: {+ projectId: program.workspaceId,+ integrationId: INTERCOM_INTEGRATION_ID,+ },+ select: {+ id: true,+ credentials: true,+ },+ });++ await Promise.allSettled([+ // Skip notifying the program of new partner messages when Intercom is connected+ !intercomInstallation &&+ qstash.publishJSON({+ url: `${APP_DOMAIN_WITH_NGROK}/api/cron/messages/notify-program`,+ body: {+ programId: program.id,+ partnerId: partner.id,+ lastMessageId: message.id,+ },+ delay: 60 * 3, // 3 minute delay for a chance to read + batching multiple messages+ }),++ // Forward the message to the Intercom+ intercomInstallation &&+ forwardPartnerMessageToIntercom({+ program,+ partner,+ message,+ intercomInstallation,+ }),+ ]);+ })(),);return {diff --git a/apps/web/package.json b/apps/web/package.jsonindex fca7af61a7..50d3be4202 100644--- a/apps/web/package.json+++ b/apps/web/package.json@@ -94,6 +94,7 @@"he": "^1.2.0","html-escaper": "^3.0.3","input-otp": "^1.2.4",+ "intercom-client": "^7.0.3","jose": "^6.1.0","js-cookie": "^3.0.5","json-2-csv": "^5.5.0",diff --git a/apps/web/scripts/create-integration.ts b/apps/web/scripts/create-integration.tsindex 68e252749a..dee1df8818 100644--- a/apps/web/scripts/create-integration.ts+++ b/apps/web/scripts/create-integration.ts@@ -7,15 +7,14 @@ async function main() {const integration = await prisma.integration.create({data: {id: createId({ prefix: "int_" }),- name: "AppsFlyer",- slug: "appsflyer",- description:- "Listen to AppsFlyer postbacks and track them as lead/sale conversion events on Dub.",+ name: "Intercom",+ slug: "intercom",+ description: "Intercom integration",developer: "Dub",website: "https://dub.co",verified: true,projectId: DUB_WORKSPACE_ID,- category: "analytics",+ category: "Communication",},});diff --git a/apps/web/scripts/dev/seed-integration.ts b/apps/web/scripts/dev/seed-integration.tsindex 16150a7f10..57ea7649d7 100644--- a/apps/web/scripts/dev/seed-integration.ts+++ b/apps/web/scripts/dev/seed-integration.ts@@ -1,22 +1,25 @@+import { encrypt } from "@/lib/encryption";import { prisma } from "@dub/prisma";-import { ACME_WORKSPACE_ID, STRIPE_INTEGRATION_ID } from "@dub/utils";+import { ACME_WORKSPACE_ID } from "@dub/utils";+import { INTERCOM_INTEGRATION_ID } from "@dub/utils/src";import "dotenv-flow/config";async function main() {await prisma.installedIntegration.upsert({where: {userId_integrationId_projectId: {- userId: "user_cludszk1h0000wmd2e0ea2b0p",- integrationId: STRIPE_INTEGRATION_ID,+ userId: "cl7p1s07k000687rbuhpwqkqa",+ integrationId: INTERCOM_INTEGRATION_ID,projectId: ACME_WORKSPACE_ID,},},create: {- userId: "user_cludszk1h0000wmd2e0ea2b0p",- integrationId: STRIPE_INTEGRATION_ID,+ userId: "cl7p1s07k000687rbuhpwqkqa",+ integrationId: INTERCOM_INTEGRATION_ID,projectId: ACME_WORKSPACE_ID,- settings: {- stripeMode: "sandbox",+ credentials: {+ appId: "xxx",+ accessToken: encrypt("xxx"),},},update: {diff --git a/packages/utils/src/constants/integrations.ts b/packages/utils/src/constants/integrations.tsindex f8e0abe515..e9f7537cfd 100644--- a/packages/utils/src/constants/integrations.ts+++ b/packages/utils/src/constants/integrations.ts@@ -5,3 +5,4 @@ export const ZAPIER_INTEGRATION_ID = "clzlmz336000fjeqynwhfv8vo";export const SHOPIFY_INTEGRATION_ID = "int_iWOtrZgmcyU6XDwKr4AYYqLN";export const HUBSPOT_INTEGRATION_ID = "int_ffw3qgrFAahY6qs1hXaH3wHS";export const APPSFLYER_INTEGRATION_ID = "int_1KN8JP7ET3VQQRF7ZQEVNFPJ5";+export const INTERCOM_INTEGRATION_ID = "int_1KV6R1E61E0044C0VFQKV2Q6K";diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 0ba6f4012c..f5ef488c08 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -260,6 +260,9 @@ importers:input-otp:specifier: ^1.2.4+ intercom-client:+ specifier: ^7.0.3+ version: 7.0.3jose:specifier: ^6.1.0version: 6.1.0@@ -8980,6 +8983,10 @@ packages:resolution: {integrity: sha512-0crLweprevJ02tTuA6ThpoAERAGyVILC4sS74uib58Xf/zSr1/ZWtmm7D5CI+bSQEaA04f0K7idaHpQbSWgiVQ==}engines: {node: '>=8.0.0'}+ resolution: {integrity: sha512-2rsNxBNqDqA0rZ0E/VsWa+/Ao+/nOxKNj9P7gUiQoOGY88eULTJUNtT9oNnT4Dq2+6dr0vvvo+I8ZNzN30Xj7A==}+ engines: {node: '>=18.0.0'}+resolution: {integrity: sha512-Y+R5hJrzs52QCG2laLn4udYVnxsfny9CpOhNhUvk/SSSVyF6T27FzRbF0sroPidSu3X8oEAkOn2K804mjpt6UQ==}engines: {node: '>= 0.4'}@@ -23478,6 +23485,8 @@ snapshots:strip-ansi: 6.0.1through: 2.3.8+ [email protected]: {}+dependencies:get-intrinsic: 1.3.0