The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
HubSpot - create the contact properties during integration installation
Kiran Kf0b6854a7da8
diff --git a/apps/web/app/(ee)/api/hubspot/callback/route.ts b/apps/web/app/(ee)/api/hubspot/callback/route.tsindex 520a3cec46..0994081ee7 100644--- a/apps/web/app/(ee)/api/hubspot/callback/route.ts+++ b/apps/web/app/(ee)/api/hubspot/callback/route.ts@@ -1,9 +1,11 @@import { DubApiError, handleAndReturnErrorResponse } from "@/lib/api/errors";import { getSession } from "@/lib/auth";+import { HubSpotApi } from "@/lib/integrations/hubspot/api";import {HUBSPOT_API_HOST,HUBSPOT_CLIENT_ID,HUBSPOT_CLIENT_SECRET,+ HUBSPOT_DUB_CONTACT_PROPERTIES,HUBSPOT_REDIRECT_URI,HUBSPOT_STATE_CACHE_PREFIX,} from "@/lib/integrations/hubspot/constants";@@ -14,6 +16,7 @@ import { redis } from "@/lib/upstash";import z from "@/lib/zod";import { prisma } from "@dub/prisma";import { getSearchParams } from "@dub/utils";+import { waitUntil } from "@vercel/functions";import { redirect } from "next/navigation";export const dynamic = "force-dynamic";@@ -146,12 +149,27 @@ export const GET = async (req: Request) => {});// Install the integration- await installIntegration({+ const installedIntegration = await installIntegration({integrationId: integration.id,userId: session.user.id,workspaceId,credentials,});++ waitUntil(+ (async () => {+ if (installedIntegration) {+ const hubSpotApi = new HubSpotApi({+ token: credentials.access_token,+ });++ await hubSpotApi.createPropertiesBatch({+ objectType: "0-1",+ properties: HUBSPOT_DUB_CONTACT_PROPERTIES,+ });+ }+ })(),+ );} catch (e: any) {return handleAndReturnErrorResponse(e);}diff --git a/apps/web/lib/integrations/hubspot/api.ts b/apps/web/lib/integrations/hubspot/api.tsnew file mode 100644index 0000000000..eafffe7e50--- /dev/null+++ b/apps/web/lib/integrations/hubspot/api.ts@@ -0,0 +1,135 @@+import { HUBSPOT_API_HOST } from "./constants";+import { hubSpotContactSchema, hubSpotDealSchema } from "./schema";++type FetchOptions = Omit<RequestInit, "body"> & {+ body?: Record<string, unknown>;+};++export class HubSpotApi {+ private readonly baseUrl = `${HUBSPOT_API_HOST}/crm/v3`;+ private readonly token: string;++ constructor({ token }: { token: string }) {+ this.token = token;+ }++ private async fetch<T>(+ input: string,+ options: FetchOptions = {},+ ): Promise<T> {+ const { body, headers, ...rest } = options;++ const url = `${this.baseUrl}${input}`;++ const fetchOptions: RequestInit = {+ ...rest,+ headers: {+ Authorization: `Bearer ${this.token}`,+ ...(body ? { "Content-Type": "application/json" } : {}),+ ...headers,+ },+ body: body ? JSON.stringify(body) : undefined,+ };++ const response = await fetch(url, fetchOptions);+ const result = await response.json();++ if (process.env.NODE_ENV === "development") {+ console.log("[HubSpot] API response", {+ url,+ result,+ });+ }++ if (!response.ok) {+ throw new Error(+ `[HubSpot] ${response.status} ${response.statusText} – ${+ (result as any)?.message || "Unknown error"+ }`,+ );+ }++ return result as T;+ }++ // Get the contact by contact id+ 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`,+ );++ return hubSpotContactSchema.parse(contact);+ } catch (error) {+ console.error(+ `[HubSpot] Failed to retrieve contact ${contactId}: ${error}`,+ );+ return null;+ }+ }++ // Get the deal by deal id+ async getDeal(dealId: number) {+ try {+ const deal = await this.fetch(+ `/objects/0-3/${dealId}?associations=contacts`,+ );++ return hubSpotDealSchema.parse(deal);+ } catch (error) {+ console.error(`[HubSpot] Failed to retrieve deal ${dealId}: ${error}`);+ return null;+ }+ }++ // Update the contact by contact id+ async updateContact({+ contactId,+ properties,+ }: {+ contactId: number | string;+ properties: Record<string, unknown>;+ }) {+ try {+ const result = await this.fetch(`/objects/contacts/${contactId}`, {+ method: "PATCH",+ body: {+ properties,+ },+ });++ return result;+ } catch (error) {+ console.error(+ `[HubSpot] Failed to update contact ${contactId}: ${error}`,+ );+ return null;+ }+ }++ // Create properties+ async createPropertiesBatch({+ objectType,+ properties,+ }: {+ objectType: "0-1" | "0-3";+ properties: Record<string, unknown>[];+ }) {+ try {+ const result = await this.fetch(+ `/properties/${objectType}/batch/create`,+ {+ method: "POST",+ body: {+ inputs: properties,+ },+ },+ );++ return result;+ } catch (error) {+ console.error(`[HubSpot] Failed to create properties: ${error}`);+ return null;+ }+ }+}diff --git a/apps/web/lib/integrations/hubspot/constants.ts b/apps/web/lib/integrations/hubspot/constants.tsindex 30ed9008f2..23f8092923 100644--- a/apps/web/lib/integrations/hubspot/constants.ts+++ b/apps/web/lib/integrations/hubspot/constants.ts@@ -15,6 +15,7 @@ export const HUBSPOT_APP_SCOPES = ["crm.objects.contacts.read","crm.objects.contacts.write","crm.objects.deals.read",+ "crm.schemas.contacts.write",];export const HUBSPOT_STATE_CACHE_PREFIX = "hubspot:install:state";@@ -24,4 +25,29 @@ export const HUBSPOT_OBJECT_TYPE_IDS = ["0-3", // deal] as const;-export const DEFAULT_CLOSED_WON_DEAL_STAGE_ID = "closedwon";+export const HUBSPOT_DEFAULT_CLOSED_WON_DEAL_STAGE_ID = "closedwon";++export const HUBSPOT_DUB_CONTACT_PROPERTIES = [+ {+ label: "Dub Id",+ name: "dub_id",+ type: "string",+ fieldType: "text",+ groupName: "contactinformation",+ formField: true, // Allow the property to be used in a HubSpot form.+ },+ {+ label: "Dub Link",+ name: "dub_link",+ type: "string",+ fieldType: "text",+ groupName: "contactinformation",+ },+ {+ label: "Dub Partner Email",+ name: "dub_partner_email",+ type: "string",+ fieldType: "text",+ groupName: "contactinformation",+ },+];diff --git a/apps/web/lib/integrations/hubspot/get-contact.ts b/apps/web/lib/integrations/hubspot/get-contact.tsdeleted file mode 100644index 883272c805..0000000000--- a/apps/web/lib/integrations/hubspot/get-contact.ts+++ /dev/null@@ -1,39 +0,0 @@-import { HUBSPOT_API_HOST } from "./constants";-import { hubSpotContactSchema } from "./schema";--export async function getHubSpotContact({- contactId,- accessToken,-}: {- contactId: number | string;- accessToken: string;-}) {- try {- const response = await fetch(- `${HUBSPOT_API_HOST}/crm/v3/objects/contacts/${contactId}?properties=email,firstname,lastname,dub_id,dub_link,dub_partner_email`,- {- method: "GET",- headers: {- Authorization: `Bearer ${accessToken}`,- },- },- );-- const result = await response.json();-- if (process.env.NODE_ENV === "development") {- console.log("HubSpot contact", result);- }-- if (!response.ok) {- throw new Error(result.message);- }-- return hubSpotContactSchema.parse(result);- } catch (error) {- console.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.tsdeleted file mode 100644index 70afd7fb56..0000000000--- a/apps/web/lib/integrations/hubspot/get-deal.ts+++ /dev/null@@ -1,37 +0,0 @@-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 (process.env.NODE_ENV === "development") {- console.log("HubSpot deal", result);- }-- 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/track-lead.ts b/apps/web/lib/integrations/hubspot/track-lead.tsindex 2ccce64ef5..2a2cb21366 100644--- a/apps/web/lib/integrations/hubspot/track-lead.ts+++ b/apps/web/lib/integrations/hubspot/track-lead.ts@@ -2,11 +2,9 @@ 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 { getHubSpotContact } from "./get-contact";-import { getHubSpotDeal } from "./get-deal";+import { HubSpotApi } from "./api";import { hubSpotLeadEventSchema } from "./schema";import { HubSpotAuthToken, HubSpotContact } from "./types";-import { updateHubSpotContact } from "./update-contact";export const trackHubSpotLeadEvent = async ({payload,@@ -19,12 +17,13 @@ export const trackHubSpotLeadEvent = async ({}) => {const { objectId, objectTypeId } = hubSpotLeadEventSchema.parse(payload);+ const hubSpotApi = new HubSpotApi({+ token: authToken.access_token,+ });+// A new contact is created (deferred lead tracking)if (objectTypeId === "0-1") {- const contactInfo = await getHubSpotContact({- contactId: objectId,- accessToken: authToken.access_token,- });+ const contactInfo = await hubSpotApi.getContact(objectId);if (!contactInfo) {return;@@ -57,7 +56,7 @@ export const trackHubSpotLeadEvent = async ({_updateHubSpotContact({contact: contactInfo,trackLeadResult,- accessToken: authToken.access_token,+ hubSpotApi,}),);}@@ -67,10 +66,7 @@ export const trackHubSpotLeadEvent = async ({// A deal is created for the contact (Eg: lead is tracked)if (objectTypeId === "0-3") {- const deal = await getHubSpotDeal({- dealId: objectId,- accessToken: authToken.access_token,- });+ const deal = await hubSpotApi.getDeal(objectId);if (!deal) {return;@@ -87,10 +83,7 @@ export const trackHubSpotLeadEvent = async ({// 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,- });+ const contactInfo = await hubSpotApi.getContact(contact.id);if (!contactInfo) {return;@@ -112,7 +105,7 @@ export const trackHubSpotLeadEvent = async ({_updateHubSpotContact({contact: contactInfo,trackLeadResult,- accessToken: authToken.access_token,+ hubSpotApi,}),);}@@ -123,11 +116,11 @@ export const trackHubSpotLeadEvent = async ({// Update the HubSpot contact with `dub_link` and `dub_partner_email`export const _updateHubSpotContact = async ({- accessToken,+ hubSpotApi,contact,trackLeadResult,}: {- accessToken: string;+ hubSpotApi: HubSpotApi;contact: HubSpotContact;trackLeadResult: TrackLeadResponse;}) => {@@ -163,9 +156,8 @@ export const _updateHubSpotContact = async ({return;}- await updateHubSpotContact({+ await hubSpotApi.updateContact({contactId: contact.id,- accessToken,properties,});};diff --git a/apps/web/lib/integrations/hubspot/track-sale.ts b/apps/web/lib/integrations/hubspot/track-sale.tsindex cbb872cbe0..da290ec860 100644--- a/apps/web/lib/integrations/hubspot/track-sale.ts+++ b/apps/web/lib/integrations/hubspot/track-sale.ts@@ -1,8 +1,7 @@import { trackSale } from "@/lib/api/conversions/track-sale";import { WorkspaceProps } from "@/lib/types";-import { DEFAULT_CLOSED_WON_DEAL_STAGE_ID } from "./constants";-import { getHubSpotContact } from "./get-contact";-import { getHubSpotDeal } from "./get-deal";+import { HubSpotApi } from "./api";+import { HUBSPOT_DEFAULT_CLOSED_WON_DEAL_STAGE_ID } from "./constants";import { hubSpotSaleEventSchema } from "./schema";import { HubSpotAuthToken } from "./types";@@ -18,7 +17,7 @@ export const trackHubSpotSaleEvent = async ({closedWonDealStageId?: string | null;}) => {closedWonDealStageId =- closedWonDealStageId ?? DEFAULT_CLOSED_WON_DEAL_STAGE_ID;+ closedWonDealStageId ?? HUBSPOT_DEFAULT_CLOSED_WON_DEAL_STAGE_ID;const { objectId, subscriptionType, propertyName, propertyValue } =hubSpotSaleEventSchema.parse(payload);@@ -42,11 +41,12 @@ export const trackHubSpotSaleEvent = async ({return;}- const deal = await getHubSpotDeal({- dealId: objectId,- accessToken: authToken.access_token,+ const hubSpotApi = new HubSpotApi({+ token: authToken.access_token,});+ const deal = await hubSpotApi.getDeal(objectId);+if (!deal) {return;}@@ -68,10 +68,7 @@ export const trackHubSpotSaleEvent = async ({// 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,- });+ const contactInfo = await hubSpotApi.getContact(contact.id);if (!contactInfo) {return;diff --git a/apps/web/lib/integrations/hubspot/ui/settings.tsx b/apps/web/lib/integrations/hubspot/ui/settings.tsxindex 00db1b44e2..255ae186d8 100644--- a/apps/web/lib/integrations/hubspot/ui/settings.tsx+++ b/apps/web/lib/integrations/hubspot/ui/settings.tsx@@ -6,7 +6,7 @@ import { Button } from "@dub/ui";import { useAction } from "next-safe-action/hooks";import { useState } from "react";import { toast } from "sonner";-import { DEFAULT_CLOSED_WON_DEAL_STAGE_ID } from "../constants";+import { HUBSPOT_DEFAULT_CLOSED_WON_DEAL_STAGE_ID } from "../constants";import { updateHubSpotSettingsAction } from "../update-hubspot-settings";export const HubSpotSettings = ({@@ -15,7 +15,7 @@ export const HubSpotSettings = ({}: InstalledIntegrationInfoProps) => {const { id: workspaceId } = useWorkspace();const [closedWonDealStageId, setClosedWonDealStageId] = useState(- (settings as any)?.closedWonDealStageId || DEFAULT_CLOSED_WON_DEAL_STAGE_ID,+ (settings as any)?.closedWonDealStageId || HUBSPOT_DEFAULT_CLOSED_WON_DEAL_STAGE_ID,);const { executeAsync, isPending } = useAction(updateHubSpotSettingsAction, {@@ -63,7 +63,7 @@ export const HubSpotSettings = ({<div className="relative mt-4 rounded-md shadow-sm"><inputclassName="w-full rounded-md border-neutral-300 text-neutral-900 placeholder-neutral-400 focus:border-neutral-500 focus:outline-none focus:ring-neutral-500 sm:text-sm"- placeholder={`Enter deal stage ID (e.g., ${DEFAULT_CLOSED_WON_DEAL_STAGE_ID})`}+ placeholder={`Enter deal stage ID (e.g., ${HUBSPOT_DEFAULT_CLOSED_WON_DEAL_STAGE_ID})`}type="text"autoComplete="off"name="closedWonDealStageId"diff --git a/apps/web/lib/integrations/hubspot/update-contact.ts b/apps/web/lib/integrations/hubspot/update-contact.tsdeleted file mode 100644index 3b59e2aad4..0000000000--- a/apps/web/lib/integrations/hubspot/update-contact.ts+++ /dev/null@@ -1,52 +0,0 @@-import { HUBSPOT_API_HOST } from "./constants";--export async function updateHubSpotContact({- contactId,- accessToken,- properties,-}: {- contactId: number | string;- accessToken: string;- properties: {- dub_link?: string;- dub_partner_email?: string;- };-}) {- try {- if (process.env.NODE_ENV === "development") {- console.log(- `Updating HubSpot contact ${contactId} with properties`,- properties,- );- }-- const response = await fetch(- `${HUBSPOT_API_HOST}/crm/v3/objects/contacts/${contactId}`,- {- method: "PATCH",- headers: {- Authorization: `Bearer ${accessToken}`,- "Content-Type": "application/json",- },- body: JSON.stringify({- properties,- }),- },- );-- const result = await response.json();-- if (process.env.NODE_ENV === "development") {- console.log("HubSpot contact update result", result);- }-- if (!response.ok) {- throw new Error(result.message || "Failed to update contact");- }-- return result;- } catch (error) {- console.error(`[HubSpot] Failed to update contact ${contactId}: ${error}`);- throw error;- }-}diff --git a/packages/hubspot-app/README.md b/packages/hubspot-app/README.mdindex 5eea5f61a3..5ae026fe56 100644--- a/packages/hubspot-app/README.md+++ b/packages/hubspot-app/README.md@@ -19,4 +19,7 @@ pnpm hs project install-deps# Add new feature to apppnpm hs project add++# List all accounts connected+pnpm hs account list```diff --git a/packages/hubspot-app/src/app/app-hsmeta.json b/packages/hubspot-app/src/app/app-hsmeta.jsonindex aa662fd4de..ef514720b3 100644--- a/packages/hubspot-app/src/app/app-hsmeta.json+++ b/packages/hubspot-app/src/app/app-hsmeta.json@@ -15,7 +15,8 @@"oauth","crm.objects.contacts.read","crm.objects.contacts.write",- "crm.objects.deals.read"+ "crm.objects.deals.read",+ "crm.schemas.contacts.write"],"optionalScopes": [],"conditionallyRequiredScopes": []