const axios = require("axios");
exports.main = async (event, callback) => {
const hubspotApiKey = process.env.HUBSPOT_PRIVATE_APP_TOKEN;
const orderId = event.object.objectId;
console.log(`🔧 Starting script for Order ID: ${orderId}`);
try {
// Step 1: Get associated Contact
const contactAssociations = await axios.get(
`https://api.hubapi.com/crm/v3/objects/orders/${orderId}/associations/contacts`,
{
headers: {
Authorization: `Bearer ${hubspotApiKey}`,
"Content-Type": "application/json",
},
}
);
const contactId = contactAssociations.data.results?.[0]?.id;
console.log(`👤 Contact ID: ${contactId}`);
if (!contactId) throw new Error("No contact associated with the order.");
// Step 2: Get associated Company for Contact
const companyAssociations = await axios.get(
`https://api.hubapi.com/crm/v3/objects/contacts/${contactId}/associations/companies`,
{
headers: {
Authorization: `Bearer ${hubspotApiKey}`,
"Content-Type": "application/json",
},
}
);
const companyId = companyAssociations.data.results?.[0]?.id;
console.log(`🏢 Company ID: ${companyId}`);
if (!companyId) throw new Error("No company associated with the contact.");
// Step 3: Associate Company with Order
await axios.put(
`https://api.hubapi.com/crm/v3/objects/orders/${orderId}/associations/companies/${companyId}/order_to_company`,
{},
{
headers: {
Authorization: `Bearer ${hubspotApiKey}`,
"Content-Type": "application/json",
},
}
);
console.log(`✅ Associated company ${companyId} with order ${orderId}`);
callback({
outputFields: {
status: "Success",
},
});
} catch (error) {
console.error(`❌ Error: ${error.message}`);
callback({
outputFields: {
status: `Error: ${error.message}`,
},
});
}
};