The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
Add HubSpot integration with OAuth callback and config
Kiran K96e6a7bd70c6
diff --git a/apps/web/.env.example b/apps/web/.env.exampleindex a144ead0e0..e5843cb88e 100644--- a/apps/web/.env.example+++ b/apps/web/.env.example@@ -150,4 +150,8 @@ STRIPE_APP_SECRET_KEY=FIRECRAWL_API_KEY=# Set a global token to identify Singular events-SINGULAR_WEBHOOK_TOKEN=\ No newline at end of file+SINGULAR_WEBHOOK_TOKEN=++# Hubspot+HUBSPOT_CLIENT_ID=+HUBSPOT_CLIENT_SECRET=\ No newline at end of filediff --git a/apps/web/app/(ee)/api/hubspot/callback/route.ts b/apps/web/app/(ee)/api/hubspot/callback/route.tsnew file mode 100644index 0000000000..ade3c4017c--- /dev/null+++ b/apps/web/app/(ee)/api/hubspot/callback/route.ts@@ -0,0 +1,110 @@+import { DubApiError, handleAndReturnErrorResponse } from "@/lib/api/errors";+import { getSession } from "@/lib/auth";+import { hubSpotEnv } from "@/lib/integrations/hubspot/env";+import { installIntegration } from "@/lib/integrations/install";+import z from "@/lib/zod";+import { prisma } from "@dub/prisma";+import { Project } from "@dub/prisma/client";+import { getSearchParams } from "@dub/utils";+import { redirect } from "next/navigation";++export const dynamic = "force-dynamic";++const oAuthCallbackSchema = z.object({+ code: z.string(),+ state: z.string(),+});++// GET /api/hubspot/callback - OAuth callback from HubSpot+export const GET = async (req: Request) => {+ const { searchParams } = new URL(req.url);+ let workspace: Pick<Project, "id" | "slug" | "plan"> | null = null;++ // Local development redirect since the callback might be coming through ngrok+ if (+ process.env.NODE_ENV === "development" &&+ !req.headers.get("host")?.includes("localhost")+ ) {+ return redirect(+ `http://localhost:8888/api/hubspot/callback?${searchParams.toString()}`,+ );+ }++ try {+ const session = await getSession();++ if (!session?.user.id) {+ throw new DubApiError({+ code: "unauthorized",+ message: "Unauthorized. Please login to continue.",+ });+ }++ const { code, state } = oAuthCallbackSchema.parse(getSearchParams(req.url));++ // // Find workspace that initiated the Stripe app install+ // const workspaceId = await redis.get<string>(+ // `hubspot:install:state:${state}`,+ // );++ // if (!workspaceId) {+ // throw new DubApiError({+ // code: "bad_request",+ // message: "Unknown state. Please try again.",+ // });+ // }++ const workspaceId = "clrei1gld0002vs9mzn93p8ik";++ workspace = await prisma.project.findUniqueOrThrow({+ where: {+ id: workspaceId,+ },+ select: {+ id: true,+ slug: true,+ plan: true,+ },+ });++ const body = new URLSearchParams({+ code,+ grant_type: "authorization_code",+ redirect_uri: hubSpotEnv.HUBSPOT_REDIRECT_URI,+ client_id: hubSpotEnv.HUBSPOT_CLIENT_ID,+ client_secret: hubSpotEnv.HUBSPOT_CLIENT_SECRET,+ });++ // Exchange authorization code for access token+ const response = await fetch("https://api.hubapi.com/oauth/v1/token", {+ method: "POST",+ headers: {+ "Content-Type": "application/x-www-form-urlencoded",+ },+ body,+ });++ const credentials = await response.json();++ // Find the integration+ const integration = await prisma.integration.findUniqueOrThrow({+ where: {+ slug: "hubspot",+ },+ });++ console.log(credentials);++ // Install the integration+ await installIntegration({+ integrationId: integration.id,+ userId: session.user.id,+ workspaceId,+ credentials,+ });+ } catch (e: any) {+ return handleAndReturnErrorResponse(e);+ }++ redirect(`/${workspace.slug}/settings/integrations/hubspot`);+};diff --git a/apps/web/lib/integrations/hubspot/env.ts b/apps/web/lib/integrations/hubspot/env.tsnew file mode 100644index 0000000000..3b5823d950--- /dev/null+++ b/apps/web/lib/integrations/hubspot/env.ts@@ -0,0 +1,3 @@+import { hubSpotEnvSchema } from "./schema";++export const hubSpotEnv = hubSpotEnvSchema.parse(process.env);diff --git a/apps/web/lib/integrations/hubspot/schema.ts b/apps/web/lib/integrations/hubspot/schema.tsnew file mode 100644index 0000000000..b80ecbcf65--- /dev/null+++ b/apps/web/lib/integrations/hubspot/schema.ts@@ -0,0 +1,18 @@+import z from "@/lib/zod";+import { APP_DOMAIN_WITH_NGROK } from "@dub/utils";++export const hubSpotEnvSchema = z.object({+ HUBSPOT_CLIENT_ID: z.string().default(""),+ HUBSPOT_CLIENT_SECRET: z.string().default(""),+ HUBSPOT_REDIRECT_URI: z+ .string()+ .default(`${APP_DOMAIN_WITH_NGROK}/api/hubspot/callback`),+});++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(),+});diff --git a/apps/web/scripts/create-integration.ts b/apps/web/scripts/create-integration.tsindex fcfb244f5b..7e3171aa66 100644--- a/apps/web/scripts/create-integration.ts+++ b/apps/web/scripts/create-integration.ts@@ -7,9 +7,9 @@ async function main() {const integration = await prisma.integration.create({data: {id: createId({ prefix: "int_" }),- name: "Singular",- slug: "singular",- description: "Track Singular events with Dub.",+ name: "HubSpot",+ slug: "hubspot",+ description: "Track HubSpot events with Dub.",developer: "Dub",website: "https://dub.co",verified: true,diff --git a/apps/web/scripts/hubspot.ts b/apps/web/scripts/hubspot.tsnew file mode 100644index 0000000000..44323fff4d--- /dev/null+++ b/apps/web/scripts/hubspot.ts@@ -0,0 +1,28 @@+import "dotenv-flow/config";+import { hubSpotEnv } from "@/lib/integrations/hubspot/env";+import { nanoid } from "@dub/utils";++async function main() {+ const SCOPES = [+ "oauth",+ "crm.objects.contacts.read",+ "crm.objects.contacts.write",+ "crm.objects.leads.read",+ ];++ const REDIRECT_URI =+ "https://accurate-caribou-strictly.ngrok-free.app/api/hubspot/callback";++ const authUrl =+ "https://app.hubspot.com/oauth/authorize" ++ `?client_id=${encodeURIComponent(hubSpotEnv.HUBSPOT_CLIENT_ID)}` ++ `&scope=${encodeURIComponent(SCOPES.join(" "))}` ++ `&redirect_uri=${encodeURIComponent(REDIRECT_URI)}` ++ `&state=${encodeURIComponent(nanoid(10))}`;++ console.log(authUrl);++ return;+}++main();diff --git a/packages/hubspot-app/package.json b/packages/hubspot-app/package.jsonindex 92c9abf58d..4b615a31ce 100644--- a/packages/hubspot-app/package.json+++ b/packages/hubspot-app/package.json@@ -4,14 +4,7 @@"description": "HubSpot app for Dub","private": true,"type": "module",- "main": "./dist/index.js",- "types": "./dist/index.d.ts",- "exports": "./dist/index.js","scripts": {- "dev": "tsup --watch",- "build": "tsup",- "typecheck": "tsc --noEmit",- "clean": "rimraf dist","hs": "hs"},"dependencies": {diff --git a/packages/hubspot-app/src/app/app-hsmeta.json b/packages/hubspot-app/src/app/app-hsmeta.jsonindex 35ed69581e..acbc98ead8 100644--- a/packages/hubspot-app/src/app/app-hsmeta.json+++ b/packages/hubspot-app/src/app/app-hsmeta.json@@ -7,7 +7,10 @@"distribution": "marketplace","auth": {"type": "oauth",- "redirectUrls": ["http://localhost:3000/oauth-callback"],+ "redirectUrls": [+ "https://accurate-caribou-strictly.ngrok-free.app/api/hubspot/callback",+ "https://dub.co/api/hubspot/callback"+ ],"requiredScopes": ["oauth","crm.objects.contacts.read",diff --git a/packages/hubspot-app/tsconfig.json b/packages/hubspot-app/tsconfig.jsondeleted file mode 100644index 6b6b2c19be..0000000000--- a/packages/hubspot-app/tsconfig.json+++ /dev/null@@ -1,9 +0,0 @@-{- "extends": "../tsconfig/base.json",- "compilerOptions": {- "outDir": "./dist",- "rootDir": "./src"- },- "include": ["src/**/*"],- "exclude": ["node_modules", "dist"]-}diff --git a/packages/hubspot-app/tsup.config.ts b/packages/hubspot-app/tsup.config.tsdeleted file mode 100644index faf3167a2a..0000000000--- a/packages/hubspot-app/tsup.config.ts+++ /dev/null@@ -1,9 +0,0 @@-import { defineConfig } from "tsup";--export default defineConfig({- entry: ["src/index.ts"],- format: ["esm"],- dts: true,- clean: true,- sourcemap: true,-});