Last active
October 7, 2024 20:53
-
-
Save jackcoldrick90/faa4f25eb6f07a6bc50b84589a574b3d to your computer and use it in GitHub Desktop.
This custom code snippet can be used to associate a contact to a company based on the company name property that is stored at a contact level. It's particularly useful if your customers are using a freemail address and aren't supplying a company website - just the name of their company. If no company is found a new record will be created in the …
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Import the Hubspot NodeJS Client Library - this will allow us to use the HubSpot APIs | |
const hubspot = require('@hubspot/api-client'); | |
/* | |
This function is called when the custom code action is executed. It takes 2 arguements. The first is the event object which contains information on the currently enrolled object. | |
The second is the callback function which is used to pass data back to the workflow. | |
*/ | |
exports.main = (event, callback) => { | |
// Instantiate a new HubSpot API client using the HAPI key (secret) | |
const hubspotClient = new hubspot.Client({ | |
accessToken: process.env.HUBSPOTTOKEN | |
}); | |
// Retrive the currently enrolled contacts "company" property | |
hubspotClient.crm.contacts.basicApi.getById(event.object.objectId, ["company"]) | |
.then(results => { | |
// Get data from the results and store in variables | |
let companyName = results.body.properties.company; | |
//console.log("SEARCH TERM: " + companyName); // - FOR DEBUG | |
// Create search criteria | |
const filter = { propertyName: 'name', operator: 'EQ', value: companyName } | |
const filterGroup = { filters: [filter] } | |
const sort = JSON.stringify({ propertyName: 'name', direction: 'DESCENDING'}) | |
const properties = ['name'] | |
const limit = 1 | |
const after = 0 | |
const searchCriteria = { | |
filterGroups: [filterGroup], | |
sorts: [sort], | |
properties, | |
limit, | |
after | |
} | |
// Search the CRM for Companies matching "companyName" variable defined earlier | |
hubspotClient.crm.companies.searchApi.doSearch(searchCriteria).then(searchCompanyResponse => { | |
//console.log("RESULTS: " + searchCompanyResponse.body.total); // - FOR DEBUG | |
// If total equals 0 no results found | |
if(searchCompanyResponse.body.total == 0){ //NO MATCH FOUND - CREATE COMPANY AND ASSOCIATE | |
// console.log("COMPANY " + companyName + "NOT FOUND: CREATE + ASSOCIATE") // - FOR DEBUG | |
//Create a Company object | |
const companyObj = { | |
properties: { | |
name: companyName, | |
}, | |
} | |
//Create the Company using Company object above | |
hubspotClient.crm.companies.basicApi.create(companyObj).then(companyCreateResponse =>{ | |
//Associate Company with Contact using the ID returned from the previous request | |
hubspotClient.crm.companies.associationsApi.create(companyCreateResponse.body.id,'contacts', event.object.objectId,'company_to_contact'); | |
}); | |
}else{ // MATCH FOUND - ASSOCIATE COMPANY TO CONTACT | |
// console.log("COMPANY " + companyName + " FOUND: ASSOCIATE RECORDS"); // - FOR DEBUG | |
//Associate Company with Contact | |
hubspotClient.crm.companies.associationsApi.create(searchCompanyResponse.body.results[0].id,'contacts', event.object.objectId,'company_to_contact'); | |
} | |
}); | |
callback({outputFields: {}}); | |
}) | |
.catch(err => { | |
console.error(err); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hey @jackcoldrick90, Im getting this code.. Im new to coding and hubspot API.. I tried to copy and paste your code.. I also created the Private app key to allow read and write contacts and companies. Im not sure what to change, I named my private app as HUBSPOTTOKEN.
what should be changed in your code so I can get it working?
2024-10-07T20:47:33.277Z ERROR ApiException [Error]: HTTP-Code: 401
Message: An error occurred.
Body: {"status":"error","message":"Authentication credentials not found. This API supports OAuth 2.0 authentication and you can find more details at https://developers.hubspot.com/docs/methods/auth/oauth-overview","correlationId":"8a4f31ee-e1d2-447e-9969-177fb1983ad3","category":"INVALID_AUTHENTICATION"}
Headers: {"access-control-allow-credentials":"false","cf-cache-status":"DYNAMIC","cf-ray":"8cf0bf387e6c8262-IAD","connection":"keep-alive","content-length":"299","content-type":"application/json;charset=utf-8","date":"Mon, 07 Oct 2024 20:47:33 GMT","nel":"{"success_fraction":0.01,"report_to":"cf-nel","max_age":604800}","report-to":"{"endpoints":[{"url":"https:\/\/a.nel.cloudflare.com\/report\/v4?s=612KJLOxSRgjV%2BOs705p%2B07FOqiTMyS5bdVIx6p%2FZSwTvShSMajOHx3pQDUQ%2FCbgoa%2FrYObIN9g9CzzQ6oF1Jfp6ItNvlUZDAR%2BIT4w171LXziRWArtVK0y1RaR65UtD"}],"group":"cf-nel","max_age":604800}","server":"cloudflare","strict-transport-security":"max-age=31536000; includeSubDomains; preload","vary":"origin, Accept-Encoding","x-content-type-options":"nosniff","x-hubspot-auth-failure":"401 Unauthorized","x-hubspot-correlation-id":"8a4f31ee-e1d2-447e-9969-177fb1983ad3"}
at BasicApiResponseProcessor. (/opt/nodejs/node_modules/@hubspot/api-client/lib/codegen/crm/contacts/apis/BasicApi.js:227:23)
at Generator.next ()
at fulfilled (/opt/nodejs/node_modules/@hubspot/api-client/lib/codegen/crm/contacts/apis/BasicApi.js:5:58)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5) {
code: 401,
body: {
status: 'error',
message: 'Authentication credentials not found. This API supports OAuth 2.0 authentication and you can find more details at https://developers.hubspot.com/docs/methods/auth/oauth-overview',
correlationId: '8a4f31ee-e1d2-447e-9969-177fb1983ad3',
category: 'INVALID_AUTHENTICATION'
},
headers: {
'access-control-allow-credentials': 'false',
'cf-cache-status': 'DYNAMIC',
'cf-ray': '8cf0bf387e6c8262-IAD',
connection: 'keep-alive',
'content-length': '299',
'content-type': 'application/json;charset=utf-8',
date: 'Mon, 07 Oct 2024 20:47:33 GMT',
nel: '{"success_fraction":0.01,"report_to":"cf-nel","max_age":604800}',
'report-to': '{"endpoints":[{"url":"https:\/\/a.nel.cloudflare.com\/report\/v4?s=612KJLOxSRgjV%2BOs705p%2B07FOqiTMyS5bdVIx6p%2FZSwTvShSMajOHx3pQDUQ%2FCbgoa%2FrYObIN9g9CzzQ6oF1Jfp6ItNvlUZDAR%2BIT4w171LXziRWArtVK0y1RaR65UtD"}],"group":"cf-nel","max_age":604800}',
server: 'cloudflare',
'strict-transport-security': 'max-age=31536000; includeSubDomains; preload',
vary: 'origin, Accept-Encoding',
'x-content-type-options': 'nosniff',
'x-hubspot-auth-failure': '401 Unauthorized',
'x-hubspot-correlation-id': '8a4f31ee-e1d2-447e-9969-177fb1983ad3'
}
}