Hi,
I’m new to Hubspot custom code option in workflow. I have some code in workflow custom code. Please help me what is this code related to.
//1. Import required libraries
const hubspot = require(‘@hubspot/api-client’); // HubSpot Node Client will allow us to make calls to HubSpot API
exports.main = async (event, callback) => {
const hubspotClient = new hubspot.Client({“accessToken”:“pat-na1-XXXXXXXXXXXXXXXX”});
//2. Get email address of Contact (Prospect in Salesforce) Owner assigned by SF in a variable
var sfOwnerEmail = event.inputFields[‘sf_owner_email’];
const sfOwnerName = event.inputFields[‘prospect_owner__sf_’];
console.log(“Salesforce Owner Email ::::::” + sfOwnerEmail);
console.log(“Salesforce Owner Name ::::::” + sfOwnerName);
if(sfOwnerName == “abc”){
sfOwnerEmail = “test@abc.com”;
}
else if(sfOwnerName == “xyz”){
sfOwnerEmail = “test1@abc.com”;
}
try {
//5. Sending the request to HS Owner API to get desired HS User details.
const response = await hubspotClient.apiRequest({
method: ‘get’,
path: ‘/owners/v2/owners’,
qs: {email: sfOwnerEmail}
})
console.log(“Response JSON String ::::::” + JSON.stringify(response.body, null, 2));
var i;
loop1:
for(i=0; i < response.body.length; i++){
for(var propertyKey in response.body[i]) {
// console.log(“key:”+propertyKey+“, propertyValue:”+response.body[i][propertyKey]);
if(propertyKey == “type” && response.body[i][propertyKey] == “PERSON”){
break loop1;
}
}
}
//6.. Extracting the first PERSON OwnerId property from response JSON
var ownerId = response.body[i].ownerId;
var ownerEmail = response.body[i].email;
console.log(“OwnerId PropertyValue::::::” + ownerId);
console.log(“Email Property::::::” + ownerEmail);
//7. Updating the Contact that triggered the workflow, with OwnerId to assign owner.
const apiResponse = await hubspotClient.crm.contacts.basicApi.update(event.object.objectId, {
“properties”: {
“hubspot_owner_id”: ownerId
}
})
}
catch (e) {
e.message === ‘HTTP request failed’ ? console.error(JSON.stringify(e.response, null, 2)) : console.error(e)
}
}