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.

Refactor HubSpot webhook processing to handle events in reverse order, enhance logging, and improve lead tracking logic with lifecycle stage checks and settings integration

Kiran Kb057400997ce
diff --git a/apps/web/app/(ee)/api/hubspot/webhook/route.ts b/apps/web/app/(ee)/api/hubspot/webhook/route.ts
index b9343a0172..fce206c8d7 100644
--- a/apps/web/app/(ee)/api/hubspot/webhook/route.ts
+++ b/apps/web/app/(ee)/api/hubspot/webhook/route.ts
@@ -53,7 +53,7 @@ export const POST = withAxiom(async (req: AxiomRequest) => {
// HS send multiple events in the same request
// so we need to process each event individually
- await Promise.allSettled(payload.map(processWebhookEvent));
+ await Promise.allSettled(payload.reverse().map(processWebhookEvent));
return NextResponse.json({ message: "Webhook received." });
} catch (error) {
@@ -102,38 +102,59 @@ async function processWebhookEvent(event: any) {
return;
}
- const integrationSettings = hubSpotSettingsSchema.parse(
- installation.settings ?? {},
- );
+ const settings = hubSpotSettingsSchema.parse(installation.settings ?? {});
- console.log("[HubSpot] Integration settings", integrationSettings);
+ console.log("[HubSpot] Event", event);
+ console.log("[HubSpot] Integration settings", settings);
- // Track a deferred lead event
+ // Contact events
if (objectTypeId === "0-1") {
- await trackHubSpotLeadEvent({
- payload: event,
- workspace,
- authToken,
- });
+ // Track a deferred lead event
+ if (subscriptionType === "object.creation") {
+ await trackHubSpotLeadEvent({
+ payload: event,
+ workspace,
+ authToken,
+ settings,
+ });
+ }
+
+ // Track the final lead event
+ else if (
+ subscriptionType === "object.propertyChange" &&
+ settings.leadTriggerEvent === "lifecycleStageReached"
+ ) {
+ await trackHubSpotLeadEvent({
+ payload: event,
+ workspace,
+ authToken,
+ settings,
+ });
+ }
}
+ // Deal event
if (objectTypeId === "0-3") {
// Track the final lead event
- if (subscriptionType === "object.creation") {
+ if (
+ subscriptionType === "object.creation" &&
+ settings.leadTriggerEvent === "dealCreated"
+ ) {
await trackHubSpotLeadEvent({
payload: event,
workspace,
authToken,
+ settings,
});
}
// Track the sale event when deal is closed won
- if (subscriptionType === "object.propertyChange") {
+ else if (subscriptionType === "object.propertyChange") {
await trackHubSpotSaleEvent({
payload: event,
workspace,
authToken,
- closedWonDealStageId: integrationSettings?.closedWonDealStageId,
+ settings,
});
}
}
diff --git a/apps/web/lib/integrations/hubspot/api.ts b/apps/web/lib/integrations/hubspot/api.ts
index b1329318dc..e68c235415 100644
--- a/apps/web/lib/integrations/hubspot/api.ts
+++ b/apps/web/lib/integrations/hubspot/api.ts
@@ -55,7 +55,7 @@ export class HubSpotApi {
async getContact(contactId: number | string) {
try {
const contact = await this.fetch(
- `/objects/contacts/${contactId}?properties=email,firstname,lastname,dub_id,dub_link,dub_partner_email`,
+ `/objects/contacts/${contactId}?properties=email,firstname,lastname,dub_id,dub_link,dub_partner_email,lifecyclestage`,
);
return hubSpotContactSchema.parse(contact);
diff --git a/apps/web/lib/integrations/hubspot/schema.ts b/apps/web/lib/integrations/hubspot/schema.ts
index d95fefe1c6..844188e346 100644
--- a/apps/web/lib/integrations/hubspot/schema.ts
+++ b/apps/web/lib/integrations/hubspot/schema.ts
@@ -47,6 +47,7 @@ export const hubSpotContactSchema = z.object({
dub_id: z.string().nullish(),
dub_link: z.string().nullish(),
dub_partner_email: z.string().nullish(),
+ lifecyclestage: z.string().nullish(),
}),
});
@@ -78,7 +79,7 @@ export const hubSpotWebhookSchema = z.object({
export const hubSpotLeadEventSchema = z.object({
objectId: z.number(),
- subscriptionType: z.literal("object.creation"),
+ subscriptionType: z.enum(["object.propertyChange", "object.creation"]),
objectTypeId: z.enum(HUBSPOT_OBJECT_TYPE_IDS),
});
diff --git a/apps/web/lib/integrations/hubspot/track-lead.ts b/apps/web/lib/integrations/hubspot/track-lead.ts
index 973fa33261..ffad2611dd 100644
--- a/apps/web/lib/integrations/hubspot/track-lead.ts
+++ b/apps/web/lib/integrations/hubspot/track-lead.ts
@@ -2,27 +2,31 @@ import { trackLead } from "@/lib/api/conversions/track-lead";
import { TrackLeadResponse, WorkspaceProps } from "@/lib/types";
import { prisma } from "@dub/prisma";
import { waitUntil } from "@vercel/functions";
+import { z } from "zod";
import { HubSpotAuthToken, HubSpotContact } from "../types";
import { HubSpotApi } from "./api";
-import { hubSpotLeadEventSchema } from "./schema";
+import { hubSpotLeadEventSchema, hubSpotSettingsSchema } from "./schema";
export const trackHubSpotLeadEvent = async ({
payload,
workspace,
authToken,
+ settings,
}: {
payload: Record<string, any>;
workspace: Pick<WorkspaceProps, "id" | "stripeConnectId" | "webhookEnabled">;
authToken: HubSpotAuthToken;
+ settings: z.infer<typeof hubSpotSettingsSchema>;
}) => {
- const { objectId, objectTypeId } = hubSpotLeadEventSchema.parse(payload);
-
const hubSpotApi = new HubSpotApi({
token: authToken.access_token,
});
+ const { objectId, objectTypeId, subscriptionType } =
+ hubSpotLeadEventSchema.parse(payload);
+
// A new contact is created (deferred lead tracking)
- if (objectTypeId === "0-1") {
+ if (objectTypeId === "0-1" && subscriptionType === "object.creation") {
const contactInfo = await hubSpotApi.getContact(objectId);
if (!contactInfo) {
@@ -64,8 +68,13 @@ export const trackHubSpotLeadEvent = async ({
return trackLeadResult;
}
- // A deal is created for the contact (Eg: lead is tracked)
- if (objectTypeId === "0-3") {
+ // Track the final lead event
+ // Case 1: A deal is created for the contact
+ if (
+ objectTypeId === "0-3" &&
+ subscriptionType === "object.creation" &&
+ settings.leadTriggerEvent === "dealCreated"
+ ) {
const deal = await hubSpotApi.getDeal(objectId);
if (!deal) {
@@ -112,6 +121,59 @@ export const trackHubSpotLeadEvent = async ({
return trackLeadResult;
}
+
+ // Track the final lead event
+ // Case 2: When the contact's lifecycle stage is changed to a qualified lead
+ if (
+ objectTypeId === "0-1" &&
+ subscriptionType === "object.propertyChange" &&
+ settings.leadTriggerEvent === "lifecycleStageReached"
+ ) {
+ const contactInfo = await hubSpotApi.getContact(objectId);
+
+ if (!contactInfo) {
+ return;
+ }
+
+ if (
+ contactInfo.properties.lifecyclestage !== settings.leadLifecycleStageId
+ ) {
+ console.error(
+ `[HubSpot] Unknown contact lifecyclestage ${contactInfo.properties.lifecyclestage}. Expected ${settings.leadLifecycleStageId}.`,
+ );
+ return;
+ }
+
+ const { properties } = contactInfo;
+
+ if (!properties.dub_id) {
+ console.error(`[HubSpot] No dub_id found for contact ${objectId}.`);
+ return;
+ }
+
+ const trackLeadResult = await trackLead({
+ clickId: "",
+ eventName: `Contact ${properties.lifecyclestage}`,
+ customerExternalId: contactInfo.properties.email,
+ customerName: `${contactInfo.properties.firstname} ${contactInfo.properties.lastname}`,
+ customerEmail: contactInfo.properties.email,
+ mode: "async",
+ workspace,
+ rawBody: payload,
+ });
+
+ if (trackLeadResult) {
+ waitUntil(
+ _updateHubSpotContact({
+ contact: contactInfo,
+ trackLeadResult,
+ hubSpotApi,
+ }),
+ );
+ }
+
+ return trackLeadResult;
+ }
};
// Update the HubSpot contact with `dub_link` and `dub_partner_email`
diff --git a/apps/web/lib/integrations/hubspot/track-sale.ts b/apps/web/lib/integrations/hubspot/track-sale.ts
index 55a03d1eb6..4fb71e8a71 100644
--- a/apps/web/lib/integrations/hubspot/track-sale.ts
+++ b/apps/web/lib/integrations/hubspot/track-sale.ts
@@ -1,24 +1,21 @@
import { trackSale } from "@/lib/api/conversions/track-sale";
import { WorkspaceProps } from "@/lib/types";
+import { z } from "zod";
import { HubSpotAuthToken } from "../types";
import { HubSpotApi } from "./api";
-import { HUBSPOT_DEFAULT_CLOSED_WON_DEAL_STAGE_ID } from "./constants";
-import { hubSpotSaleEventSchema } from "./schema";
+import { hubSpotSaleEventSchema, hubSpotSettingsSchema } from "./schema";
export const trackHubSpotSaleEvent = async ({
payload,
workspace,
authToken,
- closedWonDealStageId,
+ settings,
}: {
payload: Record<string, any>;
workspace: Pick<WorkspaceProps, "id" | "stripeConnectId" | "webhookEnabled">;
authToken: HubSpotAuthToken;
- closedWonDealStageId?: string | null;
+ settings: z.infer<typeof hubSpotSettingsSchema>;
}) => {
- closedWonDealStageId =
- closedWonDealStageId ?? HUBSPOT_DEFAULT_CLOSED_WON_DEAL_STAGE_ID;
-
const { objectId, subscriptionType, propertyName, propertyValue } =
hubSpotSaleEventSchema.parse(payload);
@@ -34,9 +31,9 @@ export const trackHubSpotSaleEvent = async ({
return;
}
- if (propertyValue !== closedWonDealStageId) {
+ if (propertyValue !== settings.closedWonDealStageId) {
console.error(
- `[HubSpot] Unknown propertyValue ${propertyValue}. Expected ${closedWonDealStageId}.`,
+ `[HubSpot] Unknown propertyValue ${propertyValue}. Expected ${settings.closedWonDealStageId}.`,
);
return;
}
diff --git a/packages/hubspot-app/src/app/webhooks/webhooks-hsmeta.json b/packages/hubspot-app/src/app/webhooks/webhooks-hsmeta.json
index 5c304e274b..7650c5c753 100644
--- a/packages/hubspot-app/src/app/webhooks/webhooks-hsmeta.json
+++ b/packages/hubspot-app/src/app/webhooks/webhooks-hsmeta.json
@@ -23,6 +23,12 @@
"propertyName": "dealstage",
"objectType": "deal",
"active": true
+ },
+ {
+ "subscriptionType": "object.propertyChange",
+ "propertyName": "lifecyclestage",
+ "objectType": "contact",
+ "active": true
}
]
}