HubSpot
Audience: Sales, management, support, engineering · Where in app: Settings → Integrations → CRM → HubSpot (Configure → HubSpot settings) · Plan availability: All plans (verify)
HubSpot was brought to GHL parity in October 2026 (15fda18a9 → 0606652b0 → a71bf7577 → review fixes 24c614a4a/6c7dd2a7b, frontend 42cdc6d1/11a5da52/4809d484/564d8fa8, ms-comm e5d0f18/3860237/3f77893, ms-ai 84bc1993a/7fb4a0c7c). It is the second CRM in the port's precedence (ghl → hubspot → salesforce → jobber), so everything that used to be GHL-only — Agent K delivery, the Nox funnel, Nox follow-ups, visit logging, call logging, tags, booking — now runs on HubSpot when GHL isn't connected.
What it does
- Leads → HubSpot contacts (email, then phone/name lookup; duplicate-email 409 links the existing contact), filling empty name/phone on matches.
- Chat transcripts → notes; phone + widget AI calls → HubSpot call engagements (
CrmCallLogJob); finished visits → notes (opt-in,CrmVisitActivityJob); lead-source note +hs_google_click_id. - Tags → the
kk_tagscontact property (HubSpot has no tags). hubspotutkcookie →crmidentity on the session (POST /user-session/hubspot-utk).- App webhooks: merge/delete relink, email replies, deal create/stage, meetings booked.
- Workflow actions (AI call / AI SMS) and a contact-record app card.
- HubSpot Meetings as a scheduling provider (
hubspot-meetings). - Agent K push mode, Nox enrichment/tasks/scheduled work, funnel stage tags + reconcile on HubSpot.
How it works
The app and credentials
- The tenant app is a HubSpot project in
hubspot-app/(HubSpot account 46054048, app id 56681322;src/app/{app,webhooks,workflow-actions,cards}) — it replaced the unused original app. Our own portal's platform-CRM token is unrelated (configs/platformCrm.js,HUBSPOT_ACCESS_TOKEN). app/configs/hubspot.jsreadsHUBSPOT_CLIENT_ID/HUBSPOT_CLIENT_SECRETwith no defaults.hooks.jsloadspublicHubspotonly when both are set; otherwiseGET /hubspot/install-urlandPOST /hubspot/webhooksanswer 503 and everyglobal.publicHubspotcaller degrades. Flux: the client id is in the backend and schedular configmaps, the secret in bothsecret.sops.yaml(9a0409b2,987a527a) — a key added only to backend silently breaks every cron (CRM sync, call logs, visit activity, kk-token sweep).
OAuth
PublicHubspotService (app/services/PublicHubspotService.js):
- Authorize at
app.hubspot.com/oauth/authorize; token/refresh/revoke on/oauth/2026-03/*. - Required scopes: contacts/companies objects read+write, contacts/companies schemas read+write,
crm.lists.read,crm.objects.deals.read/.write,crm.objects.owners.read,oauth. Deals moved from optional to required in0606652b0(the frontend's deal-scope reconnect prompt was dropped,0693c75e). - Optional scopes (
optional_scope, some tiers can't grant them):sales-email-read(reply detection, latest incoming email),automation(workflow list/enroll),scheduler.meetings.meeting-link.read(HUBSPOT_MEETING_LINK_SCOPE— meetings booking). The card lists missing ones ("Not yet allowed: workflows, email replies, meeting links") with Reconnect to allow. - State is signed (
lib/oauthState) and single-use:getInstallUrlparks a nonce inHubspotOauthHandshakeModel(1h expiry) andclaimInstallStateconsumes it atomically (findOneAndDelete) — a replayed callback is rejected. - Callback
GET /hubspot/installstores tokens +access_token_expires_at(expires_in − 120 s) +hub_id+ grantedscopes, clearsconnection_status, firesensureKkProperties(best-effort), and redirects to/settings/integrations?integration=hubspot&success=…(failures redirect too, never a JSON error). A differenthub_idthan before triggers_clearHubspotLinks(sessions/profilescrm_links,chats.hubspot_id,service_rooms.hubspot_call_log_id).hubspot.meeting_slugis kept only for the same portal with the meeting-link scope still granted. - Refresh rejected →
hubspot.connection_status = 'expired'; the port, jobs and webhooks treat that as disconnected, and the card shows "Reconnection needed". Reinstall clears it. - Disconnect
DELETE /hubspot/uninstall: uninstalls the app from the portal (DELETE /appinstalls/2026-03/external-install, HubSpot emails the portal's admins) only when no other connected company shares thehub_id, revokes the refresh token, then resetscompanies.hubspotto{ hub_id }(kept so a reconnect can detect a portal change). Revoke/uninstall are best-effort; the local disconnect always completes. Frontend confirms withConfirmDialog.
companies.hubspot (strict subdoc)
| Field | Notes |
|---|---|
access_token, refresh_token | select:false — never reach the portal; read with +hubspot.access_token |
access_token_expires_at | The connected marker (set at install/refresh, reset on uninstall) |
connection_status | null or 'expired' |
scopes, hub_id | Granted scopes and portal id |
log_visit_activity | Opt-in visit notes (Configure → Log website visits) |
meeting_slug | Meeting link the AI books on; '' = HubSpot doesn't book |
Connected test (port IS_CONNECTED.hubspot, REQUIRED_FIELDS): access_token_expires_at && connection_status !== 'expired'. GHL tokens and go_high_level.secret_key went select:false in the same change, so the frontend judges both CRMs on access_token_expires_at. Public GET /company/:_id loads hubspot and strips it for callers who can't manage the company — excluding -hubspot in the projection collides with Mongoose's automatic -hubspot.access_token (1be5aa638). The settings modal writes hubspot.log_visit_activity/hubspot.meeting_slug and kk_tokens.* through PUT /company/:id, which never accepts integration tokens/ids.
KK contact properties
ensureKkProperties creates a KK property group with kk_token, kk_why_now (textarea), kk_source, kk_signal, kk_linkedin_url, and kk_tags — once per portal per process (keyed company:hub_id), at install and on demand. kk_tags is the tag store: semicolon-separated (HubSpot's multi-value format; workflows trigger on "contains"), written by addContactTags under a per-contact Redis lock (lib/redisLock, wait ≥ TTL, compare-and-delete release). Post-call outcome tags, Agent K nextlevel … tags, funnel stage tags and nextlevel returned-to-site (kk-click) all land there.
kk_token on HubSpot: app-created stamping (kk_tokens.app_contacts), the hourly KkTokenSyncJob sweep (kk_tokens.auto_sync, now every connected CRM; an 'all' sweep survives a GHL failure), and POST /knox/agent-k/kk-backfill with provider: 'hubspot' — HubSpot filters untokenized contacts server-side (listUntokenized), so there's no picker, just "Add tokens to all contacts". Backfill progress is shown only on the CRM it belongs to (isBackfillFor). /user-session/kk-click stitches and tags HubSpot contacts.
hubspotutk visitor identification (5b55a0b55)
public/widget.js_maybeIdentifyHubspot()reads the tenant's ownhubspotutkcookie (32 hex) after the session is ready, only whenConsentGate.fingerprintAllowed(), and posts{ company_id, user_session_id, utk }to publicPOST /user-session/hubspot-utk. Local-storage memo per company: once per session+utk; an anonymous utk is re-asked at most every 10 min. Re-checked on SPA navigation and on HubSpot form submit (6c7dd2a7b).UserSessionController.hubspotUtk: 400 on a malformed utk;identified:falsefor bot UAs /suspected_bot, a disconnected/expired HubSpot, GDPR person-level block (personResolver._personLevelBlocked), or the Redis limiter (hubspot_utk_lookup:<session>, 10 min, one utk per session).- Lookup is HubSpot's legacy v1 contact-by-utk (
getContactByUtk) — there is no v3 lookup by usertoken. On a hit:crmLinks.setLink(user_session, 'hubspot', id)thenpersonResolver.resolve(..., source: 'crm')—crmoutranks device/IP claims but not the visitor's own form. - This replaced
_maybeTriggerCrmLanding, which never worked (it hit an api-key route → always 401, and sent the utk as a contact id). Its GHL?contact_id=half was dropped as spoofable — see GoHighLevel.
Outbound sync
Through the CRM port's HubSpot adapter (app/services/crm/adapters/HubspotAdapter.js); HubSpot now declares every capability in crm/capabilities.js, including call_log and task_create (GHL has neither — GHL calls go to Conversations and GHL sends follow-ups itself).
| Path | What |
|---|---|
CrmSyncQueueService (crm-sync) | sync-contact, sync-hubspot-chat-transcript (escaped), lead-source note, plus HubSpot webhook events (hubspotWebhook) |
CrmCallLogJob (1 min) | Phone AI calls (stamped crm_call_sync.<crm> by AiCallContactExtractedController, waits for the summary) and widget AI calls (service_rooms type ai, once the room is quiet) → HubSpot calls with summary, transcript, recording URL (white-label host) and outcome tags; fills the call record CrmSyncHelper.syncCallLog created at hang-up instead of adding a second; never back-fills before rollout or a stale backlog |
CrmVisitActivityJob (15 min, renamed from the GHL job) | logActivity per finished visit: GHL internal comment / HubSpot note; per-CRM flag + watermark (hubspot_visit_activity_synced_at), backoff 30m→4h then give up (hubspot_visit_activity_failures/_retry_at); no longer re-picks the same 200 sessions |
Notes and call logs are created with inline associations (no orphan engagements). SDK retries 429/5xx; _api tolerates non-JSON bodies. Deal stage / enrichment use the v4 associations API (contacts.associationsApi doesn't exist in SDK 13.5). Every call is still recorded in hubspot_requests.
crm_links on contact-keyed records (lib/crmContact.js)
The record-side twin of lib/crmLinks: 10 record models carry crm_links: crmContact.SCHEMA — NoxActionModel, ScheduledNoxActionModel, CommitmentModel, NoxSuggestionDecisionModel, LeadLifecycleEventModel, FunnelContactModel, NoxFunnelReconItemModel, NoxFunnelAuditLogModel, AgentKLinkedInSequenceModel, SmsAgentMessageModel.
- GHL ids dual-write
ghl_contact_id+crm_links; HubSpot ids are array-only — a non-GHL id never goes intoghl_contact_id. providerOf(company_id)(portresolveProvider, 60 s cache) picks the provider for writes;fields/fieldsFor,match/matchAny(either column),LINKED,idOf,providerOfRecord,ID_EXPRfor aggregations. GHL (alphanumeric) and HubSpot (numeric) ids can't collide, somatch()needs no provider.- Funnel/lifecycle rows keep HubSpot ids under the
hubspotprovider; funnel stage tags / hydration / sweep use the record's own CRM. - Backfill:
lib/crmLinksBackfill.jssweepRecordsgives every record with aghl_contact_iditscrm_linksrow; Agent K rows pushed to HubSpot (crm_provider: 'hubspot') had the HubSpot id inghl_contact_id— those move to a hubspot link and the column is cleared (records_moved_off_ghl_column). Retries a company on a Mongo timeout (a9301ed8b). Run viaPOST /migrations/backfill-crm-links(dry-run first).
App webhooks (POST /hubspot/webhooks)
Signed v3 (verifySignatureV3, x-hubspot-signature-v3 + timestamp); 401 otherwise, 503 without credentials. Answered 200 immediately, each event enqueued on crm-sync and handled by HubspotWebhookHelper for every company connected to that portalId (expired ones skipped, each company isolated; retried only when nothing applied):
Subscription (hubspot-app/src/app/webhooks/webhooks-hsmeta.json) | Handling |
|---|---|
contact.deletion, contact.privacyDeletion | Unlink the contact everywhere |
contact.merge | Relink merged-away ids to the survivor |
contact.propertyChange hs_sales_email_last_replied / hs_email_last_reply_date | Shared inbound-reply handling (sales / marketing email); deduped on the reply (email id / timestamp), released on failure; unsubscribe replies suppress HubSpot leads |
contact.propertyChange engagements_last_meeting_booked | Funnel booking signal |
deal.creation, deal.propertyChange dealstage | Funnel row + Knox stage mirror per associated contact (lib/crmStageEvent) |
Workflow actions and contact card
POST /hubspot/actions/options?kind=call|sms(agent dropdown),/actions/call,/actions/sms— "Knock Knock: AI phone call" / "Knock Knock: AI text message". Verified byverifyActionSignature(v3 when sent, else v2); one execution percallbackId(Redishubspot:action:<id>, 3 days, fails open). They hit the same internal/ai-outbound/webhook//ai-sms/webhookas the GHL custom actions, passing the HubSpotcontact_idonly when HubSpot is the company's CRM; always answer 200 withhs_execution_state+kk_status.GET /hubspot/card/contact(signed v3, HubSpot appendsportalId/userId) — last seen, lead score, page views, funnel stage, source, top pages.
HubSpot Meetings booking (hubspot-meetings)
- Backend
app/services/scheduling/adapters/HubspotMeetingsAdapter.jsoncompany.hubspot.meeting_slug(else the caller'scalendar_id). Availability pages by calendar month in the invitee zone (≤ 4 months); booking resolves HubSpot's required first+last names (stated, then the existing contact's — never overwritten — then email-prefix/-placeholders), books via the scheduler API (HubSpot creates the contact, CRM meeting and invite), recovers a lost-response retry asalready_booked(own meeting at that instant created in the last 10 min), keysprovider_event_idon the CRM meeting id, returns the real conference URL, and flagsis_offline. Reschedule/cancel are refused (the scheduler API can't); the Meetings page marks HubSpot rows not cancellable. Errors are classified on every path:MISSING_SCOPES("an administrator must reconnect HubSpot and approve the scheduler permission"),AUTH_EXPIRED,SLOT_TAKEN. GET /hubspot/meeting-linksfeeds the settings picker (scope_missing: truewithout the scope → "Reconnect HubSpot to list your meeting links (HubSpot offers them on Professional plans)").- Ladder rung 1b:
isHubspotMeetingsEnabled= connected + not expired +meeting_slug+ meeting-link scope. Automatic order: GHL withcalendar_id→ HubSpot Meetings → Calendly → Cal.com → Google → Outlook → GHL connected → Jobber → Semble → PracSuite → ServiceM8 → custom; a tenantcalendar_choiceofhubspot-meetingsoverrides it while usable. The same rule lives in ms-comm's single ladder mirrorSchedulingClientHelper(hubspotMeetingsEnabled()); ms-commCompanyModelmirrorshubspot.meeting_slug/scopes. A failed HubSpot/Jobber availability lookup now answers the widget instead of hanging. booking_type: 'hubspot'onuser_sessions.bookings[](hubspot_meeting_id); the enum matches across backend, ms-comm and ms-sessions (59738cc); widget maps it for voice bookings (3fe69bf).- ms-ai:
hubspot-meetingsis a calendar action/hint routed to the backend central path only (like Jobber);book_meetingpasses the booker's name. Offline bookings reply "The team has been notified and will confirm by email" (ms-comm3f77893) instead of promising an invite.
Agent K, Nox and funnel on HubSpot
- Agent K delivers to GHL if connected, else HubSpot; lead rows record
crm_provider. Push mode only — compose & send (Mode B) is hidden on HubSpot (no 1:1 send API).ai_agent_k.crm_delivery:workflow(default; tenant workflow onkk_tagscontainsnextlevel agent-k-lead, Professional tiers) ortask(AgentKPushServicecreates a HubSpot task with the why-now + tracked link).ai_agent_k.ghl_fieldsis ignored on HubSpot: LinkedIn →kk_linkedin_url, job title → nativejobtitle, company/website native. Feeders, reactivation, push button and kk-token sync include HubSpot; reactivation counts only newly queued leads; the trickle cap counts each parked lead once and distinct leads forreleasedToday; quiet hours read the HubSpot portal timezone. Contact links:app.hubspot.com/contacts/<hub_id>/record/0-1/<id>(lead pane reads the id fromcrm_links). - Nox: enrichment (
getContactProfile), deal search filtered by contact, provider-aware task contact search / pipelines / handle resolution, follow-ups as HubSpot tasks (createTask), scheduled tasks, an outbound gate, and a HubSpot CRM prompt section. ms-aiknox_crmdescriptions no longer claim HubSpot lacks phone/name search or deals-by-contact (7fb4a0c7c). Nox settings-by-chat has a HubSpot visit-log config op (84bc1993a). - Funnel: actions, stage tags (
kk_tags), reconcile, settings and lifecycle on HubSpot; the frontend funnel settings are CRM-aware (GHL, else HubSpot, else Salesforce).
Configuration & options
| Action | Route |
|---|---|
| Install URL (passport) | GET /hubspot/install-url |
| OAuth callback | GET /hubspot/install |
| Disconnect (passport) | DELETE /hubspot/uninstall |
| Meeting links (passport) | GET /hubspot/meeting-links |
| App webhooks | POST /hubspot/webhooks |
| Workflow actions | POST /hubspot/actions/{options,call,sms} |
| Contact card | GET /hubspot/card/contact |
| Visitor identification (public) | POST /user-session/hubspot-utk |
| kk_token backfill | POST /knox/agent-k/kk-backfill { provider: 'hubspot' } |
HubspotService.js is the private-token client for internal/admin operations; PublicHubspotService.js is the per-tenant OAuth client (publicHubspot global). The dead HubspotHelper was removed.
Behaviors & edge cases
- Several companies, one portal: webhooks and workflow actions fan out to every company with that
hub_id; uninstall leaves the portal app in place while another company still uses it. - Upsert key: email first; phone and free-text name search exist now. A 409 duplicate-email links the existing contact instead of failing.
- Jobber-only tenants get
unsupportedfor notes instead ofno_crm_connected. - Enrichment-guessed contact push is off (
LeadContactSyncJobdisabled); enrichment guesses (apollo,lead_sync) reach GHL only. - Historical backfill of old chats remains an admin-only operation.
Technical implementation
backend:app/services/PublicHubspotService.js,HubspotService.js,crm/adapters/HubspotAdapter.js,scheduling/adapters/HubspotMeetingsAdapter.js;app/controllers/HubspotController.js;app/helpers/HubspotWebhookHelper.js;app/jobs/{CrmCallLogJob,CrmVisitActivityJob,KkTokenSyncJob}.js;app/lib/{crmContact,crmStageEvent,redisLock}.js;app/models/HubspotOauthHandshakeModel.js; routesapp/routes/hubspotRoutes.js; teststest/hubspot-utk-identification.spec.js.- ms-comm:
hubspotMeetingsEnabled()+SchedulingClientHelper(is_offline). ms-ai: calendar routerhubspot-meetings. - Frontend:
components/integrations/HubSpotCard.vue,HubSpotSettingsModal.vue(vee-validate + zod),common/helpers/agentK.js(agentKCrm,CRM_LABEL,isBackfillFor). - HubSpot project:
hubspot-app/(own git repo). - Subsystem: CRM & External Integration · Identity Graph.
What Nox can tell you
- Connection state and last successful sync (
hubspot_requests). - Whether a person is in HubSpot, their deals and stage (
knox-crm, any of email/phone/name).