Automating Lead Scoring, Contact Segmentation, and Data Synchronization

Custom code in HubSpot workflows can significantly enhance your ability to automate and organize processes. Here are a few examples on how to utilise HubSpot to automate common tasks, streamline operations, and enrich CRM data.

Example 1: Automate Lead Scoring Based on Interaction

Scenario: Increase a contact’s lead score based on their interaction level, such as email opens, click rates, or website visits.

JavaScript (Node.js) Example:

const hubspot = require('@hubspot/api-client');

exports.main = async (event, callback) => {
  const hubspotClient = new hubspot.Client({
    apiKey: process.env.API_KEY
  });

  try {
    const contactId = event.object.objectId;
    // Fetch the current lead score (assuming 'lead_score' is a custom property)
    const response = await hubspotClient.crm.contacts.basicApi.getById(contactId, ["lead_score"]);
    let leadScore = parseInt(response.body.properties.lead_score) || 0;

    // Increase lead score based on certain conditions
    leadScore += 10; // Simplified scoring logic

    // Update the contact's lead score
    await hubspotClient.crm.contacts.basicApi.update(contactId, {
      properties: {
        lead_score: leadScore.toString()
      }
    });

    callback({
      outputFields: {
        message: "Lead score updated successfully"
      }
    });
  } catch (err) {
    console.error(err);
    throw err; // Ensure retries on failure, respecting HubSpot's retry logic
  }
};

Example 2: Segment Contacts into Lists Based on Custom Criteria

Scenario: Automatically segment contacts into different marketing lists based on custom criteria such as job title, industry, or engagement level.

Python Example:

import os
from hubspot import HubSpot
from hubspot.crm.contacts import ApiException

def main(event):
  hubspot_client = HubSpot(access_token=os.getenv('ACCESS_TOKEN'))

  try:
    contact_id = event.get('object').get('objectId')
    # Assume we fetch the contact's job title and industry for segmentation
    ApiResponse = hubspot_client.crm.contacts.basic_api.get_by_id(contact_id, properties=["job_title", "industry"])
    job_title = ApiResponse.properties.get('job_title', '')
    industry = ApiResponse.properties.get('industry', '')

    # Logic to determine list assignment
    list_id = None
    if 'Manager' in job_title and industry == 'Software':
      list_id = '123'  # Example list ID for software managers

    # Update contact's list membership
    if list_id:
      # Here you would use the HubSpot API or custom logic to add the contact to the list
      print(f"Contact {contact_id} added to list {list_id}")

    return {
      "outputFields": {
        "list_id": list_id or "Not assigned"
      }
    }

  except ApiException as e:
    print(e)
    raise  # Trigger retries for rate limiting errors

Example 3: Sync Contacts with External Database

Scenario: Automatically synchronize HubSpot contacts with an external database, ensuring that external records are up-to-date with the latest HubSpot data.

JavaScript (Node.js) Example:

const hubspot = require('@hubspot/api-client');
const mysql = require('mysql');

exports.main = async (event, callback) => {
  const hubspotClient = new hubspot.Client({
    apiKey: process.env.HUBSPOT_API_KEY
  });

  const connection = mysql.createConnection({
    host: "example.database.host",
    user: "username",
    password: "password",
    database: "dbname"
  });

  try {
    const contactId = event.object.objectId;
    const contactResponse = await hubspotClient.crm.contacts.basicApi.getById(contactId, ["email", "firstname", "lastname"]);
    const contactData = contactResponse.body.properties;

    const sql = "INSERT INTO Contacts (email, firstName, lastName) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE firstName = ?, lastName = ?";
    const values = [contactData.email, contactData.firstname, contactData.lastname, contactData.firstname, contactData.lastname];

    connection.query(sql, values, (err, result) => {
      if (err) throw err;
      console.log("Contact synced with external database:", result);
      callback({
        outputFields: {
          message: "Contact synced successfully"
        }
      });
    });

  } catch (err) {
    console.error(err);
    throw err; // Ensure retries on failure
  } finally {
    connection.end();
  }
};