71 lines
2.3 KiB
TypeScript
71 lines
2.3 KiB
TypeScript
/**
|
|
* HubSpot contact-create / update adapter (Phase 05 #79).
|
|
* Uses Hubspot CRM v3 contacts API + private-app token auth.
|
|
*/
|
|
|
|
import {
|
|
adapterFetch,
|
|
MarketingAdapterConfigError,
|
|
type AdapterResult,
|
|
type MarketingLeadPayload,
|
|
type MarketingOutboundAdapter,
|
|
} from "../types.js";
|
|
|
|
export interface HubSpotConfig {
|
|
/** HubSpot private-app token (Bearer). */
|
|
accessToken: string;
|
|
}
|
|
|
|
export function buildHubSpotPayload(payload: MarketingLeadPayload): { url: string; body: Record<string, unknown> } {
|
|
const properties: Record<string, string> = {
|
|
email: payload.email.trim().toLowerCase(),
|
|
};
|
|
if (payload.firstName) properties.firstname = payload.firstName;
|
|
if (payload.lastName) properties.lastname = payload.lastName;
|
|
if (payload.company) properties.company = payload.company;
|
|
if (payload.utm?.source) properties.utm_source = payload.utm.source;
|
|
if (payload.utm?.medium) properties.utm_medium = payload.utm.medium;
|
|
if (payload.utm?.campaign) properties.utm_campaign = payload.utm.campaign;
|
|
// Use the v3 contacts create endpoint; HubSpot returns 409 on conflict
|
|
// which is a recoverable "already exists" — the worker handler treats
|
|
// 409 as a successful no-op.
|
|
return {
|
|
url: "https://api.hubapi.com/crm/v3/objects/contacts",
|
|
body: { properties },
|
|
};
|
|
}
|
|
|
|
export const hubspotAdapter: MarketingOutboundAdapter<HubSpotConfig> = {
|
|
type: "hubspot",
|
|
parseConfig(config: unknown): HubSpotConfig {
|
|
if (!config || typeof config !== "object") {
|
|
throw new MarketingAdapterConfigError("hubspot config must be an object");
|
|
}
|
|
const c = config as Record<string, unknown>;
|
|
if (typeof c.accessToken !== "string" || c.accessToken.length === 0) {
|
|
throw new MarketingAdapterConfigError("hubspot config requires accessToken");
|
|
}
|
|
return { accessToken: c.accessToken };
|
|
},
|
|
async send({ payload, config, ctx }): Promise<AdapterResult> {
|
|
const built = buildHubSpotPayload(payload);
|
|
const res = await adapterFetch(
|
|
built.url,
|
|
{
|
|
method: "POST",
|
|
headers: {
|
|
"content-type": "application/json",
|
|
authorization: `Bearer ${config.accessToken}`,
|
|
},
|
|
body: JSON.stringify(built.body),
|
|
},
|
|
ctx
|
|
);
|
|
if (!res.ok && res.status === 409) {
|
|
// Idempotent — contact already exists.
|
|
return { ok: true, status: 409 };
|
|
}
|
|
return res;
|
|
},
|
|
};
|