The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
Refactor HubSpot integration by replacing the refreshAccessToken function
Kiran Ke11b6ea508cc
diff --git a/apps/web/app/(ee)/api/hubspot/webhook/route.ts b/apps/web/app/(ee)/api/hubspot/webhook/route.tsindex 6d2f5bf05e..1b2888eb86 100644--- a/apps/web/app/(ee)/api/hubspot/webhook/route.ts+++ b/apps/web/app/(ee)/api/hubspot/webhook/route.ts@@ -1,13 +1,12 @@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 { hubSpotOAuthProvider } from "@/lib/integrations/hubspot/oauth";import {hubSpotSettingsSchema,hubSpotWebhookSchema,} from "@/lib/integrations/hubspot/schema";import { trackHubSpotLeadEvent } from "@/lib/integrations/hubspot/track-lead";import { trackHubSpotSaleEvent } from "@/lib/integrations/hubspot/track-sale";-import { HubSpotAuthToken } from "@/lib/integrations/hubspot/types";import { prisma } from "@dub/prisma";import crypto from "crypto";import { AxiomRequest, withAxiom } from "next-axiom";@@ -92,10 +91,7 @@ async function processWebhookEvent(event: any) {const workspace = installation.project;// Refresh the access token if needed- const authToken = await refreshAccessToken({- installationId: installation.id,- authToken: installation.credentials as HubSpotAuthToken,- });+ const authToken = await hubSpotOAuthProvider.refreshTokenForInstallation(installation);if (!authToken) {console.error(diff --git a/apps/web/lib/integrations/hubspot/oauth.ts b/apps/web/lib/integrations/hubspot/oauth.tsindex 9f007c636e..4b06542b36 100644--- a/apps/web/lib/integrations/hubspot/oauth.ts+++ b/apps/web/lib/integrations/hubspot/oauth.ts@@ -1,6 +1,9 @@+import { prisma } from "@dub/prisma";+import { InstalledIntegration } from "@dub/prisma/client";import { APP_DOMAIN_WITH_NGROK } from "@dub/utils";import { z } from "zod";-import { OAuthProvider } from "../oauth-provider";+import { OAuthProvider, OAuthProviderConfig } from "../oauth-provider";+import { HubSpotAuthToken } from "./types";const hubSpotTokenSchema = z.object({access_token: z.string(),@@ -11,9 +14,52 @@ const hubSpotTokenSchema = z.object({created_at: z.number().optional(),});-export const hubSpotOAuthProvider = new OAuthProvider<- typeof hubSpotTokenSchema->({+class HubSpotOAuthProvider extends OAuthProvider<typeof hubSpotTokenSchema> {+ constructor(config: OAuthProviderConfig) {+ super(config);+ }++ async refreshTokenForInstallation(+ installation: InstalledIntegration,+ ): Promise<HubSpotAuthToken> {+ const token = hubSpotTokenSchema.parse(installation.credentials);++ if (this.isTokenValid(token)) {+ return token;+ }++ const newToken = await this.refreshToken(token.access_token);++ const credentials = {+ ...newToken,+ created_at: Date.now(),+ };++ await prisma.installedIntegration.update({+ where: {+ id: installation.id,+ },+ data: {+ credentials,+ },+ });++ return credentials;+ }++ isTokenValid(token: HubSpotAuthToken) {+ if (!token.created_at) {+ return false;+ }++ const buffer = 60 * 1000; // refresh 1 min early+ const expiresAt = token.created_at + token.expires_in * 1000;++ return Date.now() < expiresAt - buffer;+ }+}++export const hubSpotOAuthProvider = new HubSpotOAuthProvider({name: "HubSpot",clientId: process.env.HUBSPOT_CLIENT_ID || "",clientSecret: process.env.HUBSPOT_CLIENT_SECRET || "",diff --git a/apps/web/lib/integrations/hubspot/refresh-token.ts b/apps/web/lib/integrations/hubspot/refresh-token.tsdeleted file mode 100644index 1d5bb8ab89..0000000000--- a/apps/web/lib/integrations/hubspot/refresh-token.ts+++ /dev/null@@ -1,72 +0,0 @@-import { prisma } from "@dub/prisma";-import {- HUBSPOT_API_HOST,- HUBSPOT_CLIENT_ID,- HUBSPOT_CLIENT_SECRET,-} from "./constants";-import { hubSpotAuthTokenSchema } from "./schema";-import { HubSpotAuthToken } from "./types";--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",- headers: {- "Content-Type": "application/x-www-form-urlencoded",- },- body: new URLSearchParams({- grant_type: "refresh_token",- refresh_token: authToken.refresh_token,- client_id: HUBSPOT_CLIENT_ID,- client_secret: HUBSPOT_CLIENT_SECRET,- }),- });-- const result = await response.json();-- if (!response.ok) {- console.error(result);- throw new Error(result.message);- }-- // Store the new auth token- const newAuthToken = hubSpotAuthTokenSchema.parse({- ...result,- created_at: Date.now(),- });-- await prisma.installedIntegration.update({- where: {- id: installationId,- },- data: {- credentials: newAuthToken,- },- });-- return newAuthToken;- } catch (error) {- console.error(- "[HubSpot] Error refreshing the access token:",- error instanceof Error ? error.message : String(error),- );- return null;- }-}--function isTokenValid(authToken: HubSpotAuthToken) {- const buffer = 60 * 1000; // refresh 1 min early- const expiresAt = authToken.created_at + authToken.expires_in * 1000;-- return Date.now() < expiresAt - buffer;-}diff --git a/apps/web/lib/integrations/oauth-provider.ts b/apps/web/lib/integrations/oauth-provider.tsindex 9ff9853dfa..ee44c1812f 100644--- a/apps/web/lib/integrations/oauth-provider.ts+++ b/apps/web/lib/integrations/oauth-provider.ts@@ -23,6 +23,7 @@ const codeExchangeSchema = z.object({export class OAuthProvider<T extends z.ZodSchema> {constructor(private provider: OAuthProviderConfig) {}+ // Generate the authorization URL for the OAuth providerasync generateAuthUrl(contextId: string) {const state = nanoid(16);await redis.set(`${this.provider.redisStatePrefix}:${state}`, contextId, {@@ -40,6 +41,7 @@ export class OAuthProvider<T extends z.ZodSchema> {return `${this.provider.authUrl}?${searchParams.toString()}`;}+ // Exchange the authorization code for a tokenasync exchangeCodeForToken(request: Request): Promise<{contextId: string;token: z.infer<T>;@@ -69,23 +71,51 @@ export class OAuthProvider<T extends z.ZodSchema> {}),});- const data = await response.json();+ const result = await response.json();if (!response.ok) {- console.error(`[${this.provider.name}] exchangeCodeForToken`, data);+ console.error(`[${this.provider.name}] exchangeCodeForToken`, result);throw new Error(`[${this.provider.name}] Failed to exchange authorization code. Please try again.`,);}- const token = this.provider.tokenSchema.parse(data);+ const token = this.provider.tokenSchema.parse(result);return {token,contextId,};}++ // Refresh the token+ async refreshToken(refreshToken: string): Promise<z.infer<T>> {+ const response = await fetch(this.provider.tokenUrl, {+ method: "POST",+ headers: {+ "Content-Type": "application/x-www-form-urlencoded",+ },+ body: new URLSearchParams({+ grant_type: "refresh_token",+ refresh_token: refreshToken,+ client_id: this.provider.clientId,+ client_secret: this.provider.clientSecret,+ }),+ });++ const result = await response.json();++ if (!response.ok) {+ console.error(`[${this.provider.name}] refreshToken`, result);++ throw new Error(+ `[${this.provider.name}] Failed to refresh the access token. Please try again.`,+ );+ }++ return this.provider.tokenSchema.parse(result);+ }}// TODO: