Skip to content

Instantly share code, notes, and snippets.

@jackcoldrick90
Created July 26, 2023 12:32
Show Gist options
  • Save jackcoldrick90/b431cd7c443844edcc907b84d46bd7cf to your computer and use it in GitHub Desktop.
Save jackcoldrick90/b431cd7c443844edcc907b84d46bd7cf to your computer and use it in GitHub Desktop.
Script below can be used in a HubSpot Contact Workflow to associate a contact to a company using the value stored in the "company name" property. If the company exists it is associated. If the company does not exist, it is created and associated. Requires authentication with a private app.
// Import the Hubspot NodeJS Client Library - this will allow us to use the HubSpot APIs
const hubspot = require('@hubspot/api-client');
//Instantiate a new HubSpot API client using an access token (private app)
const hubspotClient = new hubspot.Client({
accessToken: process.env.HUBSPOTTOKEN
});
// Helper function to associate Company to Contact using HubSpot Client
function associateCompanyToContact(companyId, contactId) {
const AssociationSpec = [{
"associationCategory": "HUBSPOT_DEFINED",
"associationTypeId": 2
}];
hubspotClient.apiRequest({
method: 'PUT',
path: `/crm/v4/objects/company/${companyId}/associations/contact/${contactId}`,
body: AssociationSpec
})
}
// Function called when custom coded worklow action executes
exports.main = (event) => {
// Search for company using the contacts company name property
const filter = {
propertyName: 'name',
operator: 'EQ',
value: event.inputFields['company_name']
}
const filterGroup = {
filters: [filter]
}
const properties = ['name']
const publicObjectSearchRequest = {
filterGroups: [filterGroup],
properties,
}
hubspotClient.crm.companies.searchApi.doSearch(publicObjectSearchRequest).then(searchCompanyResponse => {
if (searchCompanyResponse.total) { // If match found associate contact to company
associateCompanyToContact(searchCompanyResponse.results[0].id, event.object.objectId);
} else { // If no companies found create company and associate contact to company
//Create a Company object
const companyObj = {
properties: {
name: event.inputFields['company_name'],
}
}
hubspotClient.crm.companies.basicApi.create(companyObj).then(results => {
associateCompanyToContact(results.id, event.object.objectId);
});
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment