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.

track the final lead + refresh the token if expired

Kiran K546729685287
diff --git a/apps/web/app/(ee)/api/hubspot/callback/route.ts b/apps/web/app/(ee)/api/hubspot/callback/route.ts
index 393d26ce66..d91734081e 100644
--- a/apps/web/app/(ee)/api/hubspot/callback/route.ts
+++ b/apps/web/app/(ee)/api/hubspot/callback/route.ts
@@ -12,6 +12,7 @@ import z from "@/lib/zod";
import { prisma } from "@dub/prisma";
import { Project } from "@dub/prisma/client";
import { getSearchParams } from "@dub/utils";
+import { refreshAccessToken } from "app/api/oauth/token/refresh-access-token";
import { redirect } from "next/navigation";
export const dynamic = "force-dynamic";
@@ -88,7 +89,17 @@ export const GET = async (req: Request) => {
body,
});
- const credentials = await response.json();
+ const result = await response.json();
+
+ if (!response.ok) {
+ console.error(result);
+
+ throw new DubApiError({
+ code: "bad_request",
+ message:
+ "[HubSpot] Failed to exchange authorization code for access token",
+ });
+ }
// Find the integration
const integration = await prisma.integration.findUniqueOrThrow({
@@ -102,7 +113,10 @@ export const GET = async (req: Request) => {
integrationId: integration.id,
userId: session.user.id,
workspaceId,
- credentials,
+ credentials: {
+ ...result,
+ created_at: Date.now(),
+ },
});
} catch (e: any) {
return handleAndReturnErrorResponse(e);
diff --git a/apps/web/app/(ee)/api/hubspot/webhook/route.ts b/apps/web/app/(ee)/api/hubspot/webhook/route.ts
index 41e1260435..f329ba76ed 100644
--- a/apps/web/app/(ee)/api/hubspot/webhook/route.ts
+++ b/apps/web/app/(ee)/api/hubspot/webhook/route.ts
@@ -1,5 +1,7 @@
import { DubApiError, handleAndReturnErrorResponse } from "@/lib/api/errors";
import { HUBSPOT_CLIENT_SECRET } from "@/lib/integrations/hubspot/constants";
+import { refreshAccessToken } from "@/lib/integrations/hubspot/refresh-token";
+import { hubSpotWebhookSchema } from "@/lib/integrations/hubspot/schema";
import { trackHubSpotLeadEvent } from "@/lib/integrations/hubspot/track-lead";
import { HubSpotAuthToken } from "@/lib/integrations/hubspot/types";
import { prisma } from "@dub/prisma";
@@ -45,7 +47,12 @@ export const POST = withAxiom(async (req: AxiomRequest) => {
const payload = JSON.parse(rawPayload);
+ // HS send multiple events in the same request
+ // so we need to process each event individually
for (const event of payload) {
+ const { objectTypeId, portalId, subscriptionType } =
+ hubSpotWebhookSchema.parse(event);
+
// Find the installation
const installation = await prisma.installedIntegration.findFirst({
where: {
@@ -54,7 +61,7 @@ export const POST = withAxiom(async (req: AxiomRequest) => {
},
credentials: {
path: "$.hub_id",
- equals: event.portalId,
+ equals: portalId,
},
},
include: {
@@ -64,22 +71,50 @@ export const POST = withAxiom(async (req: AxiomRequest) => {
if (!installation) {
console.error(
- `HubSpot Installation is not found for portalId ${event.portalId}.`,
+ `[HubSpot] Installation is not found for portalId ${portalId}.`,
);
continue;
}
const workspace = installation.project;
- switch (event.objectTypeId) {
- case "0-1":
+ // Refresh the access token if needed
+ const authToken = await refreshAccessToken({
+ installationId: installation.id,
+ authToken: installation.credentials as HubSpotAuthToken,
+ });
+
+ if (!authToken) {
+ console.error(
+ `[HubSpot] Authentication token is not found or valid for portalId ${portalId}.`,
+ );
+ continue;
+ }
+
+ // Track a deferred lead event
+ if (objectTypeId === "0-1") {
+ await trackHubSpotLeadEvent({
+ payload: event,
+ workspace,
+ authToken,
+ });
+ }
+
+ if (objectTypeId === "0-3") {
+ // Track the final lead event
+ if (subscriptionType === "object.creation") {
await trackHubSpotLeadEvent({
- mode: "deferred",
payload: event,
workspace,
- authToken: installation.credentials as HubSpotAuthToken,
+ authToken,
});
- break;
+ }
+
+ // Track the sale event
+ if (subscriptionType === "object.propertyChange") {
+ // TODO:
+ // Track sale
+ }
}
}
diff --git a/apps/web/lib/integrations/hubspot/constants.ts b/apps/web/lib/integrations/hubspot/constants.ts
index 9648f98c45..8c37175c07 100644
--- a/apps/web/lib/integrations/hubspot/constants.ts
+++ b/apps/web/lib/integrations/hubspot/constants.ts
@@ -8,6 +8,8 @@ export const HUBSPOT_REDIRECT_URI =
process.env.HUBSPOT_REDIRECT_URI ||
`${APP_DOMAIN_WITH_NGROK}/api/hubspot/callback`;
+export const HUBSPOT_API_HOST = "https://api.hubapi.com";
+
export const HUBSPOT_APP_SCOPES = [
"oauth",
"crm.objects.contacts.read",
@@ -18,11 +20,7 @@ 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";
+export const HUBSPOT_OBJECT_TYPE_IDS = [
+ "0-1", // contact
+ "0-3", // deal
+] as const;
diff --git a/apps/web/lib/integrations/hubspot/get-contact.ts b/apps/web/lib/integrations/hubspot/get-contact.ts
index 86dc305462..1a1c3036e7 100644
--- a/apps/web/lib/integrations/hubspot/get-contact.ts
+++ b/apps/web/lib/integrations/hubspot/get-contact.ts
@@ -1,11 +1,11 @@
import { HUBSPOT_API_HOST } from "./constants";
import { hubSpotContactSchema } from "./schema";
-export async function getContact({
+export async function getHubSpotContact({
contactId,
accessToken,
}: {
- contactId: number;
+ contactId: number | string;
accessToken: string;
}) {
try {
@@ -28,7 +28,7 @@ export async function getContact({
return hubSpotContactSchema.parse(result);
} catch (error) {
console.error(
- `Failed to retrieve contact ${contactId} from HubSpot: ${error}`,
+ `[HubSpot] Failed to retrieve contact ${contactId}: ${error}`,
);
return null;
}
diff --git a/apps/web/lib/integrations/hubspot/get-deal.ts b/apps/web/lib/integrations/hubspot/get-deal.ts
new file mode 100644
index 0000000000..32f759526b
--- /dev/null
+++ b/apps/web/lib/integrations/hubspot/get-deal.ts
@@ -0,0 +1,33 @@
+import { HUBSPOT_API_HOST } from "./constants";
+import { hubSpotDealSchema } from "./schema";
+
+export async function getHubSpotDeal({
+ dealId,
+ accessToken,
+}: {
+ dealId: number;
+ accessToken: string;
+}) {
+ try {
+ const response = await fetch(
+ `${HUBSPOT_API_HOST}/crm/v3/objects/0-3/${dealId}?associations=contacts`,
+ {
+ method: "GET",
+ headers: {
+ Authorization: `Bearer ${accessToken}`,
+ },
+ },
+ );
+
+ const result = await response.json();
+
+ if (!response.ok) {
+ throw new Error(result.message);
+ }
+
+ return hubSpotDealSchema.parse(result);
+ } catch (error) {
+ console.error(`[HubSpot] Failed to retrieve deal ${dealId}: ${error}`);
+ return null;
+ }
+}
diff --git a/apps/web/lib/integrations/hubspot/refresh-token.ts b/apps/web/lib/integrations/hubspot/refresh-token.ts
index 8596d5d9ed..040e3b345a 100644
--- a/apps/web/lib/integrations/hubspot/refresh-token.ts
+++ b/apps/web/lib/integrations/hubspot/refresh-token.ts
@@ -1,15 +1,22 @@
+import { prisma } from "@dub/prisma";
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> {
+export async function refreshAccessToken({
+ installationId,
+ authToken,
+}: {
+ installationId: string;
+ authToken: HubSpotAuthToken;
+}) {
+ if (isTokenValid(authToken)) {
+ return authToken;
+ }
+
try {
const response = await fetch(`${HUBSPOT_API_HOST}/oauth/v1/token`, {
method: "POST",
@@ -18,56 +25,47 @@ export async function refreshAccessToken(
},
body: new URLSearchParams({
grant_type: "refresh_token",
- refresh_token: refreshToken,
+ refresh_token: authToken.refresh_token,
client_id: HUBSPOT_CLIENT_ID,
client_secret: HUBSPOT_CLIENT_SECRET,
- redirect_uri: HUBSPOT_REDIRECT_URI,
}),
});
- const result = hubSpotRefreshTokenSchema.parse(await response.json());
+ const result = await response.json();
if (!response.ok) {
- console.error("Failed to refresh HubSpot access token:", result);
- return null;
+ console.error(result);
+ throw new Error(result.message);
}
- 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
+ // Store the new auth token
+ const newAuthToken: HubSpotAuthToken = {
+ ...result,
+ created_at: Date.now(),
};
- return hubSpotAuthTokenSchema.parse(authToken);
+ await prisma.installedIntegration.update({
+ where: {
+ id: installationId,
+ },
+ data: {
+ credentials: newAuthToken,
+ },
+ });
+
+ return newAuthToken;
} catch (error) {
- console.error("Error refreshing HubSpot access token:", error);
+ console.error(
+ "[HubSpot] Error refreshing the access token:",
+ error.message,
+ );
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;
- }
+function isTokenValid(authToken: HubSpotAuthToken) {
+ const buffer = 60 * 1000; // refresh 1 min early
+ const expiresAt = authToken.created_at + authToken.expires_in * 1000;
- // Preserve the original scopes and hub_id
- return {
- ...refreshedToken,
- scopes: currentToken.scopes,
- hub_id: currentToken.hub_id,
- };
+ return Date.now() < expiresAt - buffer;
}
diff --git a/apps/web/lib/integrations/hubspot/schema.ts b/apps/web/lib/integrations/hubspot/schema.ts
index 235f457e95..97371ba040 100644
--- a/apps/web/lib/integrations/hubspot/schema.ts
+++ b/apps/web/lib/integrations/hubspot/schema.ts
@@ -1,23 +1,29 @@
import z from "@/lib/zod";
import { HUBSPOT_OBJECT_TYPE_IDS } from "./constants";
+// Authentication
export const hubSpotAuthTokenSchema = z.object({
access_token: z.string(),
refresh_token: z.string(),
scopes: z.array(z.string()),
- expires_in: z.number(),
hub_id: z.number(),
+ expires_in: z.number().describe("Expires in seconds."),
+ created_at: z.number(),
});
-export const hubSpotWebhookSchema = z.object({
- portalId: z.number(),
- objectTypeId: z.enum(HUBSPOT_OBJECT_TYPE_IDS as [string, ...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(),
});
+// CRM
export const hubSpotContactSchema = z.object({
id: z.string(),
properties: z.object({
- email: z.string().nullable(),
+ email: z.string(),
firstname: z.string().nullable(),
lastname: z.string().nullable(),
phone: z.string().nullable(),
@@ -26,10 +32,34 @@ export const hubSpotContactSchema = z.object({
}),
});
-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(),
+export const hubSpotDealSchema = z.object({
+ id: z.string(),
+ properties: z.object({
+ dealname: z.string(),
+ amount: z.string(),
+ dealstage: z.enum(["appointmentscheduled"]),
+ }),
+ associations: z.object({
+ contacts: z.object({
+ results: z.array(
+ z.object({
+ id: z.string(),
+ type: z.string(),
+ }),
+ ),
+ }),
+ }),
+});
+
+// Webhooks
+export const hubSpotWebhookSchema = z.object({
+ portalId: z.number(),
+ objectTypeId: z.enum(HUBSPOT_OBJECT_TYPE_IDS),
+ subscriptionType: z.enum(["object.creation", "object.propertyChange"]),
+});
+
+export const hubSpotLeadEventSchema = z.object({
+ objectId: z.number(),
+ subscriptionType: z.enum(["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 721e8eafb2..c01e2d23d7 100644
--- a/apps/web/lib/integrations/hubspot/track-lead.ts
+++ b/apps/web/lib/integrations/hubspot/track-lead.ts
@@ -1,62 +1,89 @@
import { trackLead } from "@/lib/api/conversions/track-lead";
import { WorkspaceProps } from "@/lib/types";
-import { z } from "zod";
-import { HUBSPOT_OBJECT_TYPE_IDS } from "./constants";
-import { getContact } from "./get-contact";
+import { getHubSpotContact } from "./get-contact";
+import { getHubSpotDeal } from "./get-deal";
+import { hubSpotLeadEventSchema } from "./schema";
import { HubSpotAuthToken } from "./types";
-const hubSpotLeadEventSchema = z.object({
- objectId: z.number(),
- subscriptionType: z.enum(["object.creation"]),
- objectTypeId: z.enum(HUBSPOT_OBJECT_TYPE_IDS as [string, ...string[]]),
-});
-
export const trackHubSpotLeadEvent = async ({
payload,
workspace,
authToken,
- mode,
}: {
payload: Record<string, any>;
workspace: Pick<WorkspaceProps, "id" | "stripeConnectId" | "webhookEnabled">;
authToken: HubSpotAuthToken;
- mode: "async" | "deferred";
}) => {
const { objectId, objectTypeId, subscriptionType } =
hubSpotLeadEventSchema.parse(payload);
- if (subscriptionType !== "object.creation" || objectTypeId !== "0-1") {
- console.log(
- `Unsupported subscriptionType or objectTypeId: ${subscriptionType} ${objectTypeId}`,
- );
- return;
- }
+ // A new contact is created
+ if (objectTypeId === "0-1" && subscriptionType === "object.creation") {
+ const contact = await getHubSpotContact({
+ contactId: objectId,
+ accessToken: authToken.access_token,
+ });
+
+ if (!contact) {
+ return;
+ }
- // Get the contact from HubSpot
- const contact = await getContact({
- contactId: objectId,
- accessToken: authToken.access_token,
- });
+ const { properties } = contact;
- if (!contact) {
- console.error(`Contact not found for objectId: ${objectId}`);
- return;
+ const customerName =
+ [properties.firstname, properties.lastname].filter(Boolean).join(" ") ||
+ null;
+
+ return await trackLead({
+ clickId: properties.dub_id || "",
+ eventName: "Sign up",
+ customerEmail: properties.email,
+ customerExternalId: properties.email,
+ customerName,
+ mode: "deferred",
+ workspace,
+ rawBody: payload,
+ });
}
- const { properties } = contact;
-
- const customerName =
- [properties.firstname, properties.lastname].filter(Boolean).join(" ") ||
- null;
-
- return await trackLead({
- clickId: properties.dub_id || "",
- eventName: "Sign up",
- customerEmail: properties.email,
- customerExternalId: contact.id,
- customerName,
- mode,
- workspace,
- rawBody: payload,
- });
+ // A deal is created for the contact (Eg: lead is tracked)
+ if (objectTypeId === "0-3" && subscriptionType === "object.creation") {
+ const deal = await getHubSpotDeal({
+ dealId: objectId,
+ accessToken: authToken.access_token,
+ });
+
+ if (!deal) {
+ return;
+ }
+
+ const { properties, associations } = deal;
+
+ // Find the contact associated with the deal
+ const contact = associations.contacts.results[0];
+
+ if (!contact) {
+ return;
+ }
+
+ // HubSpot doesn't return the contact properties in the deal associations,
+ // so we need to get it separately
+ const contactInfo = await getHubSpotContact({
+ contactId: contact.id,
+ accessToken: authToken.access_token,
+ });
+
+ if (!contactInfo) {
+ return;
+ }
+
+ return await trackLead({
+ clickId: "",
+ eventName: properties.dealstage,
+ customerExternalId: contactInfo.properties.email,
+ mode: "async",
+ workspace,
+ rawBody: payload,
+ });
+ }
};