Skip to content

armgit / dub

Public Imported from GitHub
0

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

fix track lead

Kiran Kec15bda24912
diff --git a/apps/web/app/(ee)/api/hubspot/webhook/route.ts b/apps/web/app/(ee)/api/hubspot/webhook/route.ts
index b8667aac86..41e1260435 100644
--- a/apps/web/app/(ee)/api/hubspot/webhook/route.ts
+++ b/apps/web/app/(ee)/api/hubspot/webhook/route.ts
@@ -1,5 +1,8 @@
import { DubApiError, handleAndReturnErrorResponse } from "@/lib/api/errors";
import { HUBSPOT_CLIENT_SECRET } from "@/lib/integrations/hubspot/constants";
+import { trackHubSpotLeadEvent } from "@/lib/integrations/hubspot/track-lead";
+import { HubSpotAuthToken } from "@/lib/integrations/hubspot/types";
+import { prisma } from "@dub/prisma";
import crypto from "crypto";
import { AxiomRequest, withAxiom } from "next-axiom";
import { NextResponse } from "next/server";
@@ -7,7 +10,7 @@ import { NextResponse } from "next/server";
// POST /api/hubspot/webhook – listen to webhook events from Hubspot
export const POST = withAxiom(async (req: AxiomRequest) => {
try {
- const rawBody = await req.text();
+ const rawPayload = await req.text();
const signature = req.headers.get("X-HubSpot-Signature");
// Verify webhook signature
@@ -26,7 +29,7 @@ export const POST = withAxiom(async (req: AxiomRequest) => {
}
// Create expected hash: client_secret + request_body
- const sourceString = HUBSPOT_CLIENT_SECRET + rawBody;
+ const sourceString = HUBSPOT_CLIENT_SECRET + rawPayload;
const expectedHash = crypto
.createHash("sha256")
.update(sourceString)
@@ -40,8 +43,45 @@ export const POST = withAxiom(async (req: AxiomRequest) => {
});
}
- const body = JSON.parse(rawBody);
- console.log("Verified webhook payload:", body);
+ const payload = JSON.parse(rawPayload);
+
+ for (const event of payload) {
+ // Find the installation
+ const installation = await prisma.installedIntegration.findFirst({
+ where: {
+ integration: {
+ slug: "hubspot",
+ },
+ credentials: {
+ path: "$.hub_id",
+ equals: event.portalId,
+ },
+ },
+ include: {
+ project: true,
+ },
+ });
+
+ if (!installation) {
+ console.error(
+ `HubSpot Installation is not found for portalId ${event.portalId}.`,
+ );
+ continue;
+ }
+
+ const workspace = installation.project;
+
+ switch (event.objectTypeId) {
+ case "0-1":
+ await trackHubSpotLeadEvent({
+ mode: "deferred",
+ payload: event,
+ workspace,
+ authToken: installation.credentials as HubSpotAuthToken,
+ });
+ break;
+ }
+ }
return NextResponse.json({ message: "Webhook received." });
} catch (error) {
diff --git a/apps/web/lib/integrations/hubspot/constants.ts b/apps/web/lib/integrations/hubspot/constants.ts
index 19f0b8279e..9648f98c45 100644
--- a/apps/web/lib/integrations/hubspot/constants.ts
+++ b/apps/web/lib/integrations/hubspot/constants.ts
@@ -17,3 +17,12 @@ export const HUBSPOT_APP_SCOPES = [
];
export const HUBSPOT_STATE_CACHE_PREFIX = "hubspot:install:state";
+
+export const HUBSPOT_OBJECT_TYPE_ID_MAP = {
+ "0-1": "contact",
+ "0-3": "deal",
+};
+
+export const HUBSPOT_OBJECT_TYPE_IDS = Object.keys(HUBSPOT_OBJECT_TYPE_ID_MAP);
+
+export const HUBSPOT_API_HOST = "https://api.hubapi.com";
diff --git a/apps/web/lib/integrations/hubspot/get-contact.ts b/apps/web/lib/integrations/hubspot/get-contact.ts
new file mode 100644
index 0000000000..86dc305462
--- /dev/null
+++ b/apps/web/lib/integrations/hubspot/get-contact.ts
@@ -0,0 +1,35 @@
+import { HUBSPOT_API_HOST } from "./constants";
+import { hubSpotContactSchema } from "./schema";
+
+export async function getContact({
+ contactId,
+ accessToken,
+}: {
+ contactId: number;
+ accessToken: string;
+}) {
+ try {
+ const response = await fetch(
+ `${HUBSPOT_API_HOST}/crm/v3/objects/contacts/${contactId}?properties=email,firstname,lastname,phone,dub_id`,
+ {
+ method: "GET",
+ headers: {
+ Authorization: `Bearer ${accessToken}`,
+ },
+ },
+ );
+
+ const result = await response.json();
+
+ if (!response.ok) {
+ throw new Error(result.message);
+ }
+
+ return hubSpotContactSchema.parse(result);
+ } catch (error) {
+ console.error(
+ `Failed to retrieve contact ${contactId} from HubSpot: ${error}`,
+ );
+ return null;
+ }
+}
diff --git a/apps/web/lib/integrations/hubspot/refresh-token.ts b/apps/web/lib/integrations/hubspot/refresh-token.ts
new file mode 100644
index 0000000000..8596d5d9ed
--- /dev/null
+++ b/apps/web/lib/integrations/hubspot/refresh-token.ts
@@ -0,0 +1,73 @@
+import {
+ HUBSPOT_API_HOST,
+ HUBSPOT_CLIENT_ID,
+ HUBSPOT_CLIENT_SECRET,
+ HUBSPOT_REDIRECT_URI,
+} from "./constants";
+import { hubSpotAuthTokenSchema, hubSpotRefreshTokenSchema } from "./schema";
+import { HubSpotAuthToken } from "./types";
+
+export async function refreshAccessToken(
+ refreshToken: string,
+): Promise<HubSpotAuthToken | null> {
+ try {
+ const response = await fetch(`${HUBSPOT_API_HOST}/oauth/v1/token`, {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/x-www-form-urlencoded",
+ },
+ body: new URLSearchParams({
+ grant_type: "refresh_token",
+ refresh_token: refreshToken,
+ client_id: HUBSPOT_CLIENT_ID,
+ client_secret: HUBSPOT_CLIENT_SECRET,
+ redirect_uri: HUBSPOT_REDIRECT_URI,
+ }),
+ });
+
+ const result = hubSpotRefreshTokenSchema.parse(await response.json());
+
+ if (!response.ok) {
+ console.error("Failed to refresh HubSpot access token:", result);
+ return null;
+ }
+
+ console.log(result);
+
+ // Transform the response to match our schema
+ const authToken: HubSpotAuthToken = {
+ access_token: result.access_token,
+ refresh_token: result.refresh_token,
+ scopes: [], // Scopes are not returned in refresh response, will need to be preserved
+ expires_in: result.expires_in,
+ hub_id: 0, // Hub ID is not returned in refresh response, will need to be preserved
+ };
+
+ return hubSpotAuthTokenSchema.parse(authToken);
+ } catch (error) {
+ console.error("Error refreshing HubSpot access token:", error);
+ return null;
+ }
+}
+
+/**
+ * Refreshes an access token while preserving existing scopes and hub_id
+ * @param currentToken - The current HubSpot auth token
+ * @returns Updated token with new access_token and refresh_token, or null if refresh failed
+ */
+export async function refreshAccessTokenWithContext(
+ currentToken: HubSpotAuthToken,
+): Promise<HubSpotAuthToken | null> {
+ const refreshedToken = await refreshAccessToken(currentToken.refresh_token);
+
+ if (!refreshedToken) {
+ return null;
+ }
+
+ // Preserve the original scopes and hub_id
+ return {
+ ...refreshedToken,
+ scopes: currentToken.scopes,
+ hub_id: currentToken.hub_id,
+ };
+}
diff --git a/apps/web/lib/integrations/hubspot/schema.ts b/apps/web/lib/integrations/hubspot/schema.ts
index 627f111f40..235f457e95 100644
--- a/apps/web/lib/integrations/hubspot/schema.ts
+++ b/apps/web/lib/integrations/hubspot/schema.ts
@@ -1,4 +1,5 @@
import z from "@/lib/zod";
+import { HUBSPOT_OBJECT_TYPE_IDS } from "./constants";
export const hubSpotAuthTokenSchema = z.object({
access_token: z.string(),
@@ -7,3 +8,28 @@ export const hubSpotAuthTokenSchema = z.object({
expires_in: z.number(),
hub_id: z.number(),
});
+
+export const hubSpotWebhookSchema = z.object({
+ portalId: z.number(),
+ objectTypeId: z.enum(HUBSPOT_OBJECT_TYPE_IDS as [string, ...string[]]),
+});
+
+export const hubSpotContactSchema = z.object({
+ id: z.string(),
+ properties: z.object({
+ email: z.string().nullable(),
+ firstname: z.string().nullable(),
+ lastname: z.string().nullable(),
+ phone: z.string().nullable(),
+ dub_id: z.string().nullable(),
+ createdate: z.string(),
+ }),
+});
+
+export const hubSpotRefreshTokenSchema = z.object({
+ access_token: z.string(),
+ refresh_token: z.string(),
+ token_type: z.string(),
+ expires_in: z.number(),
+ id_token: z.string().nullable(),
+});
diff --git a/apps/web/lib/integrations/hubspot/track-lead.ts b/apps/web/lib/integrations/hubspot/track-lead.ts
index 6bca22b30f..721e8eafb2 100644
--- a/apps/web/lib/integrations/hubspot/track-lead.ts
+++ b/apps/web/lib/integrations/hubspot/track-lead.ts
@@ -1,63 +1,62 @@
import { trackLead } from "@/lib/api/conversions/track-lead";
import { WorkspaceProps } from "@/lib/types";
-import { trackLeadRequestSchema } from "@/lib/zod/schemas/leads";
import { z } from "zod";
+import { HUBSPOT_OBJECT_TYPE_IDS } from "./constants";
+import { getContact } from "./get-contact";
+import { HubSpotAuthToken } from "./types";
-const singularLeadEventSchema = z.object({
- dub_id: z.string().min(1),
- event_name: z.string().min(1),
- event_attributes: z
- .string()
- .transform((val) => {
- try {
- return JSON.parse(val);
- } catch {
- throw new Error("Invalid JSON in event_attributes");
- }
- })
- .pipe(
- z.object({
- customer_external_id: trackLeadRequestSchema.shape.customerExternalId,
- customer_name: trackLeadRequestSchema.shape.customerName,
- customer_email: trackLeadRequestSchema.shape.customerEmail,
- customer_avatar: trackLeadRequestSchema.shape.customerAvatar,
- event_quantity: trackLeadRequestSchema.shape.eventQuantity,
- mode: trackLeadRequestSchema.shape.mode,
- }),
- ),
+const hubSpotLeadEventSchema = z.object({
+ objectId: z.number(),
+ subscriptionType: z.enum(["object.creation"]),
+ objectTypeId: z.enum(HUBSPOT_OBJECT_TYPE_IDS as [string, ...string[]]),
});
-export const trackSingularLeadEvent = async ({
- queryParams,
+export const trackHubSpotLeadEvent = async ({
+ payload,
workspace,
+ authToken,
+ mode,
}: {
- queryParams: Record<string, string>;
+ payload: Record<string, any>;
workspace: Pick<WorkspaceProps, "id" | "stripeConnectId" | "webhookEnabled">;
+ authToken: HubSpotAuthToken;
+ mode: "async" | "deferred";
}) => {
- const {
- dub_id: clickId,
- event_name: eventName,
- event_attributes: {
- customer_external_id: customerExternalId,
- customer_name: customerName,
- customer_email: customerEmail,
- customer_avatar: customerAvatar,
- event_quantity: eventQuantity,
- mode,
- },
- } = singularLeadEventSchema.parse(queryParams);
+ const { objectId, objectTypeId, subscriptionType } =
+ hubSpotLeadEventSchema.parse(payload);
+
+ if (subscriptionType !== "object.creation" || objectTypeId !== "0-1") {
+ console.log(
+ `Unsupported subscriptionType or objectTypeId: ${subscriptionType} ${objectTypeId}`,
+ );
+ return;
+ }
+
+ // Get the contact from HubSpot
+ const contact = await getContact({
+ contactId: objectId,
+ accessToken: authToken.access_token,
+ });
+
+ if (!contact) {
+ console.error(`Contact not found for objectId: ${objectId}`);
+ return;
+ }
+
+ const { properties } = contact;
+
+ const customerName =
+ [properties.firstname, properties.lastname].filter(Boolean).join(" ") ||
+ null;
return await trackLead({
- clickId,
- eventName,
- customerEmail,
- customerAvatar,
- customerExternalId,
+ clickId: properties.dub_id || "",
+ eventName: "Sign up",
+ customerEmail: properties.email,
+ customerExternalId: contact.id,
customerName,
- eventQuantity,
mode,
- metadata: null,
workspace,
- rawBody: queryParams,
+ rawBody: payload,
});
};
diff --git a/apps/web/lib/integrations/hubspot/types.ts b/apps/web/lib/integrations/hubspot/types.ts
new file mode 100644
index 0000000000..d92bd63c13
--- /dev/null
+++ b/apps/web/lib/integrations/hubspot/types.ts
@@ -0,0 +1,6 @@
+import { z } from "zod";
+import { hubSpotAuthTokenSchema, hubSpotRefreshTokenSchema } from "./schema";
+
+export type HubSpotAuthToken = z.infer<typeof hubSpotAuthTokenSchema>;
+
+export type HubSpotRefreshToken = z.infer<typeof hubSpotRefreshTokenSchema>;
diff --git a/packages/prisma/schema/integration.prisma b/packages/prisma/schema/integration.prisma
index 3b80ec2cd9..170ab82f64 100644
--- a/packages/prisma/schema/integration.prisma
+++ b/packages/prisma/schema/integration.prisma
@@ -23,8 +23,8 @@ model Integration {
oAuthApp OAuthApp?
installations InstalledIntegration[]
- @@index([projectId])
- @@index([userId])
+ @@index(projectId)
+ @@index(userId)
}
model InstalledIntegration {
@@ -44,6 +44,6 @@ model InstalledIntegration {
webhooks Webhook[]
@@unique([userId, integrationId, projectId])
- @@index([projectId])
- @@index([integrationId])
+ @@index(projectId)
+ @@index(integrationId)
}