Gareth Wilson Gareth Wilson

Building CRM enrichment with HubSpot and OpenAI

Published · Updated


A prospect fills out a "Request a demo" form on your marketing site. Within seconds of the contact being created in HubSpot, an AI enrichment step has identified the company from the email domain, classified the prospect's role from their job title, looked up the company's funding stage and headcount, scored the lead from 1 to 5 against your ICP, summarised what they wrote in the free-text field, and written all of it back to the HubSpot record as custom properties. By the time the SDR opens HubSpot in the morning, the lead is already triaged — they know which prospects to call first and what to say.

That's the workflow most B2B teams are after with HubSpot, an LLM, and a thin glue layer. The HubSpot side is easy. The LLM side is easy. The glue (what happens between the contact-created event and the property-update API call) is where it falls over, especially as you start ingesting leads from a second, third, and fourth source.

This guide walks through that glue layer end to end: the architecture, seven concrete steps to wire it up, and the production concerns you'll hit the moment you start running real volume.

The flow

POST batchfilter + transform+ rate limitread contactLLM callPOST enriched recordtransform + retryHubSpotcontact created/updatedHubSpotwebhookOther lead sourcesTypeform, ads,partner APIsHookdeckinbound sourceOpenAIenrichment handlerHubSpot APIcontact lookupGPT-4 / GPT-4oHookdeckcallback sourceHubSpot APIproperty update
POST batchfilter + transform+ rate limitread contactLLM callPOST enriched recordtransform + retryHubSpotcontact created/updatedHubSpotwebhookOther lead sourcesTypeform, ads,partner APIsHookdeckinbound sourceOpenAIenrichment handlerHubSpot APIcontact lookupGPT-4 / GPT-4oHookdeckcallback sourceHubSpot APIproperty update

There are two webhook flows that need to be reliable:

  1. HubSpot's contact event into the AI step — must not drop an event, and must not waste tokens on leads that don't deserve enrichment. HubSpot batches events and signs them with x-hubspot-signature-v3, but it doesn't filter, it doesn't rate-limit your downstream, and it doesn't deduplicate against prior runs.
  2. The enriched record back into HubSpot — must reach HubSpot reliably. HubSpot's API has rate limits and occasional 5xx; a failed update means the SDR sees an un-triaged lead.

Most teams build this with a POST /webhooks/hubspot endpoint that calls OpenAI inline, then calls HubSpot's API to write the result back. That's enough to demo. It's not enough to run, and the reasons it isn't enough are where Hookdeck Event Gateway helps.

What you'll need

  • A HubSpot account with a private app and webhook subscriptions enabled
  • An OpenAI API key with access to a chat completions model
  • A Hookdeck Event Gateway account — the free tier covers this entire workflow at low volume
  • Hookdeck CLI installed: npm install hookdeck-cli -g or brew install hookdeck
  • A handler somewhere — a Cloudflare Worker, a Vercel function, or a small Node service — that receives the lead payload, reads the contact from HubSpot's API, calls OpenAI, and POSTs the result back

Step 1: Create the Hookdeck Event Gateway source for HubSpot

In the Hookdeck Event Gateway dashboard:

  • Create Connection → New Source
  • Type: HubSpot (Event Gateway has a pre-configured source for HubSpot — see the HubSpot webhooks guide)
  • Name: hubspot-contact-events
  • Hookdeck will ask for your HubSpot client secret so it can verify the x-hubspot-signature-v3 header on every request

Copy the generated source URL.

Step 2: Subscribe HubSpot webhooks to the Hookdeck URL

In HubSpot, open your Private App → Webhooks → Create subscription:

  • Target URL: paste the Hookdeck source URL from step 1
  • Subscriptions: enable contact.creation and contact.propertyChange (and any others you care about)
  • Active: yes

HubSpot batches events into a single request, so a single payload can carry multiple contact creations. The transformation in step 4 reduces each batch to a list of contact IDs, and your handler works through that list.

If you want to centralise lead ingestion across additional sources (a Typeform, a Webflow form, an ad-network webhook, a partner API), point them all at the same Hookdeck source. The transformation step in step 4 normalises every shape into one canonical payload before it reaches OpenAI.

Step 3: Add the destination — your OpenAI enrichment handler

Your handler is a small service that:

  1. Receives the canonical lead payload, a list of HubSpot contact IDs
  2. Reads each contact's properties from HubSpot's API
  3. Skips leads with a personal email domain or no job title
  4. Calls OpenAI with an enrichment prompt
  5. Parses the model's structured output
  6. POSTs the enriched record to a second Hookdeck source (step 6)

A minimal Cloudflare Worker version:

const PERSONAL_EMAIL = /@(gmail|yahoo|hotmail|outlook|aol|icloud)\.com$/i;

export default {
  async fetch(request, env) {
    const { leads } = await request.json();

    for (const lead of leads) {
      // Fetch contact details from HubSpot
      const contact = await fetch(
        `https://api.hubapi.com/crm/v3/objects/contacts/${lead.hubspot_contact_id}?properties=email,firstname,lastname,jobtitle,company,notes_last_contacted`,
        { headers: { authorization: `Bearer ${env.HUBSPOT_TOKEN}` } }
      ).then(r => r.json());

      const { email, firstname, lastname, jobtitle, company, notes_last_contacted } = contact.properties;

      // Don't spend OpenAI tokens on leads that don't deserve enrichment
      if (!email || PERSONAL_EMAIL.test(email) || !jobtitle) continue;

      const completion = await fetch('https://api.openai.com/v1/chat/completions', {
        method: 'POST',
        headers: {
          'authorization': `Bearer ${env.OPENAI_API_KEY}`,
          'content-type': 'application/json',
        },
        body: JSON.stringify({
          model: 'gpt-4o-mini',
          response_format: { type: 'json_object' },
          messages: [
            { role: 'system', content: ENRICHMENT_PROMPT },
            {
              role: 'user',
              content: JSON.stringify({
                ...lead,
                email,
                first_name: firstname,
                last_name: lastname,
                job_title: jobtitle,
                company,
                notes: notes_last_contacted,
              }),
            },
          ],
        }),
      });

      const result = await completion.json();
      const enrichment = JSON.parse(result.choices[0].message.content);

      // Send enriched record back through Hookdeck for write-back to HubSpot
      await fetch(env.HOOKDECK_CALLBACK_URL, {
        method: 'POST',
        headers: { 'content-type': 'application/json' },
        body: JSON.stringify({
          contact_id: lead.hubspot_contact_id,
          enrichment,
        }),
      });
    }

    return new Response('ok', { status: 200 });
  },
};

Set HUBSPOT_TOKEN to your private app's access token. The private app needs read access to contacts.

Configure the destination in Hookdeck Event Gateway:

  • Type: HTTP
  • URL: your handler URL
  • Authentication: an HTTP header carrying a shared secret so your handler can verify the request came through Hookdeck
  • Delivery timeout: long enough for a full batch. HubSpot can send up to 100 events in one request, and the handler makes up to one OpenAI call per contact.

Step 4: Add filter, transformation, and rate-limit rules

This is where Hookdeck Event Gateway does most of its work.

Transformation — normalize HubSpot's batched, ID-only payload into a canonical lead shape your handler expects. HubSpot's contact.creation event carries the contact ID but not the contact's properties. Transformations can't reach the network, so the transformation passes the IDs to your handler, which reads the properties from HubSpot's API in step 3:

addHandler('transform', (request, context) => {
  const events = request.body; // array of HubSpot events
  const leads = [];

  for (const event of events) {
    if (event.subscriptionType !== 'contact.creation') continue;

    leads.push({
      source: 'hubspot',
      hubspot_contact_id: event.objectId,
      received_at: new Date().toISOString(),
    });
  }

  request.body = { lead_count: leads.length, leads };
  return request;
});

If you're also ingesting from Typeform or an ad webhook, add if/else branches that map each source into the same leads array. Those payloads carry the form values and have no HubSpot contact ID, so your handler needs a branch that uses the values directly.

Filter — drop batches with nothing to enrich. Step 2 also subscribes to contact.propertyChange, so some batches contain no contact creations. Run this rule after the transformation so it can read lead_count:

{
  "body": {
    "lead_count": {
      "$gte": 1
    }
  }
}

The payload at this point has no email address or job title to match on, so the handler in step 3 skips personal email domains and missing job titles after its HubSpot lookup. Edit PERSONAL_EMAIL there as your ICP definition evolves.

Rate limit — protect OpenAI from bursty HubSpot batches. A new ad campaign or a marketing automation can fire hundreds of contact.creation events in a minute. Hookdeck limits deliveries rather than contacts, and your handler makes up to one OpenAI call per contact in a delivery, so cap how many batches it works on at once:

Hookdeck Event Gateway queues the rest and feeds them to your handler at a sustainable rate.

Retry policy — handle transient OpenAI errors and your handler's cold-starts:

  • Initial delay: 30 seconds
  • Max attempts: 10
  • Strategy: exponential
  • Apply on status codes: 408, 429, 500, 502, 503, 504

Step 5: Test the inbound leg locally with the CLI

Before hitting the live OpenAI API, route the inbound connection to the CLI:

hookdeck login
hookdeck listen 3000 hubspot-contact-events

Run a local server that prints the transformed payload and stubs the OpenAI call:

// inspect.js
const http = require('http');
http.createServer((req, res) => {
  let body = '';
  req.on('data', chunk => body += chunk);
  req.on('end', () => {
    console.log('Canonical leads:', JSON.parse(body));
    res.writeHead(200);
    res.end('ok');
  });
}).listen(3000);

Trigger a test contact creation in HubSpot. The CLI streams the transformed payload to your terminal so you can verify the shape before your handler sees it. Press r to replay the most recent event without re-triggering — useful when you're iterating on the prompt or the canonical shape.

Once it looks correct, point the destination back at your real handler.

Step 6: Wire the enriched record back through Hookdeck

When the handler finishes, it POSTs the enriched record to a second Hookdeck Event Gateway source that fans it out to HubSpot and any other system that needs to know.

Create a second connection:

  • Source: an HTTP source named lead-enrichment-results
  • Destination: https://api.hubapi.com/crm/v3/objects/contacts, with Custom HTTP Method set to PATCH and your private app's access token as a bearer token

A transformation adds the contact ID to the path and reshapes the enrichment output into HubSpot's property-update format:

addHandler('transform', (request, context) => {
  const { contact_id, enrichment } = request.body;

  request.path = `/${contact_id}`;
  request.body = {
    properties: {
      ai_lead_score: String(enrichment.score),
      ai_company_size: enrichment.company_size,
      ai_funding_stage: enrichment.funding_stage,
      ai_icp_fit: enrichment.icp_fit,
      ai_summary: enrichment.summary,
      ai_enriched_at: new Date().toISOString(),
    },
  };

  return request;
});

Retry policy — aggressive on this leg. Losing the write-back means the SDR sees an un-triaged lead:

  • Initial delay: 15 seconds
  • Max attempts: 15
  • Strategy: exponential

If you want enrichment results to also reach Slack (for high-scoring leads) or a data warehouse, add additional connections from lead-enrichment-results with filters on enrichment.score.

Step 7: Run the full chain end to end

Create a test contact in HubSpot with a real business email. You should see, in order:

  1. HubSpot fires a contact.creation event into hubspot-contact-events
  2. Hookdeck Event Gateway normalises into the canonical shape, filters, and delivers to your handler
  3. The handler reads the contact's properties from HubSpot, calls OpenAI, and posts the enriched record to lead-enrichment-results
  4. Hookdeck Event Gateway transforms into HubSpot's PATCH format and writes back
  5. The HubSpot contact record now shows the AI-enriched properties

If anything fails (a malformed prompt, an OpenAI rate limit, a HubSpot 5xx) the Hookdeck Event Gateway dashboard tells you exactly where, with full request/response payloads at every step.

Why Hookdeck and not just a try/except in your app server?

Three properties of CRM enrichment workflows make a direct integration the wrong choice once you're past the demo:

Lead events come from many sources, not just HubSpot. Over time you'll add a Typeform, an ad-network webhook, a Clearbit form, a partner API. Hookdeck Event Gateway consolidates all of them into a single ingestion point with a single canonical shape, so your enrichment logic doesn't grow a tangle of source-specific branches. Adding a new source becomes a new connection in the dashboard with a new transformation, not a refactor of the enrichment service.

Filtering keeps low-quality leads out of the AI step. OpenAI tokens have a cost. Personal email domains, missing job titles, test entries, and duplicate submissions are all noise. Hookdeck Event Gateway's filter rules drop anything the payload can identify before it reaches your handler, such as batches with no contact creations or sources that send form values directly. HubSpot's contact.creation events carry only contact IDs, so the handler skips those leads after its lookup and before its OpenAI call. Both checks save tokens, money, and engineering time spent figuring out why your lead score column is full of null.

Replay lets you re-process leads when the prompt is updated. Enrichment prompts evolve. You realise the score should weight headcount more heavily, or you want to add a "buying intent" field. Without Hookdeck Event Gateway, re-running enrichment on the last 30 days of contacts means writing a backfill script. You can then select the time range in the dashboard and click Replay — every contact created since the cutoff gets re-enriched against the new prompt.

You can build all of this on your own: a queue, a retry worker, a transformation step, a filter engine, an observability layer, a replay tool. That's the work Hookdeck Event Gateway collapses into a connection in a dashboard. The hours you don't spend building that infrastructure are hours you spend on the enrichment prompt, the ICP definition, and the downstream SDR experience.

Going to production

Observability that finds the silent failures. Hookdeck Event Gateway's Issues feature surfaces failure patterns automatically — repeated retries, signature verification failures, payload spikes. Set up a Slack alert when the enrichment write-back starts failing, so it doesn't go undetected for a week and SDRs lose trust in the scores.

Dedupe across sources. If the same prospect fills out two forms or hits two ad campaigns, you'll get two contact-creation events, and a retry re-runs every contact in its batch. Use your handler's idempotency check (against hubspot_contact_id and a recent timestamp) to avoid double-enrichment.

Cost control. A per-hour max delivery rate on the destination paces enrichment, so an accidentally-imported CSV of 50,000 contacts queues instead of running up an OpenAI bill overnight, and you have time to cancel the queued events. Adjust the rate as you scale.

Handle PII responsibly. Names, emails, job titles, and any free-text notes pass through this pipeline. A transformation can remove fields your handler doesn't need, but Hookdeck Event Gateway still stores the original request and shows it in the dashboard. Before you go live, use a private project and add only the people who should see that data.

What to build next

This pattern generalizes: The same architecture handles ticket classification in Zendesk, contract analysis triggered by a DocuSign event, transcript summarisation from a Gong webhook, and dozens of other "event happens, AI reasons about it, result writes back somewhere" workflows.

If you're building any of this, the fastest way to get past the demo phase is to stop maintaining your own webhook infrastructure. The AI Agents & LLMs use case covers the Hookdeck setup this pattern relies on: delivery timeouts, concurrency limits, filters and replay. Start with the Hookdeck free tier (you can run this entire workflow without paying anything until you hit real volume) and use the CLI to keep your development loop fast.


Gareth Wilson

Gareth Wilson

Product Marketing

Multi-time founding marketer, Gareth is PMM at Hookdeck and author of the newsletter, Community Inc.