Skip to content

Instantly share code, notes, and snippets.

@jackcoldrick90
Created July 25, 2023 15:19
Show Gist options
  • Save jackcoldrick90/143d429971a46bbb871e3d8471c7625c to your computer and use it in GitHub Desktop.
Save jackcoldrick90/143d429971a46bbb871e3d8471c7625c to your computer and use it in GitHub Desktop.
Code snippets to be used in two separate Hubspot workflows to create a referral program. The first will generate a random number (referral ID) the second will be used to attribute referrals back to the referring contact.
//1. Import required libaries
const Promise = require("bluebird"); // Javascript Promise Library
const randomNumber = require("random-number-csprng"); // Javascript Random Number Generator
exports.main = (event, callback) => {
//2. Using a Promise, we first try to generate a random number
Promise.try(function() {
return randomNumber(10000, 50000); // Generate Random Number between a defined range
}).then(function(number) { // When the number is successfully generated we do this
// 3. Pass data back to worklfow using outputFields - make sure to also define data output types
callback({
outputFields: {
referrer_id: number
}
});
}).catch({ // If there are any issues we can throw an error
code: "RandomGenerationError"
}, function(err) {
console.log("Something went wrong!");
});
}
//1. Import required libraries
const hubspot = require('@hubspot/api-client'); // HubSpot Node Client will allow us to make calls to HubSpot API
exports.main = (event, callback) => {
//2. Create our client
const hubspotClient = new hubspot.Client({
accessToken: process.env.ReferralProgram
});
//3. Store the referrer ID linked to the enrolled contact in a variable
const referrer = event.inputFields['referrer'];
//4. Create and configure our search filters
const filter = {
propertyName: 'referrer_id',
operator: 'EQ',
value: referrer
}
const filterGroup = {
filters: [filter]
}
const properties = ['referrer_id', 'number_of_referrals', 'firstname', 'lastname', 'email']
const publicObjectSearchRequest = {
filterGroups: [filterGroup],
properties,
}
//5. Search the CRM for the contact using the query defined above
hubspotClient.crm.contacts.searchApi.doSearch(publicObjectSearchRequest).then(results => {
//6. Store data in variables
let contactId = results.results[0].id; // Id of the referring contact
let referred_by = results.results[0].properties.firstname + " " + results.results[0].properties.lastname; // full name of the referring contact
let totalReferrals = 0;
//7. Check to see if this is their first referral. If it is we set "totalReferrals" property to "0"
if (results.results[0].properties.number_of_referrals === null || results.results[0].properties.number_of_referrals === undefined || results.results[0].properties.number_of_referrals === "") {
totalReferrals = 0;
} else { // Otherwise we retrieve the current number of referrals
totalReferrals = parseInt(results.results[0].properties.number_of_referrals)
}
let totalReferralsUpdated = totalReferrals + 1; // Increment referrals
//8. Create a new date (todays date)
var d = new Date();
d.setUTCHours(0, 0, 0, 0);
//9. Update Referred Contact's "referred by" property
hubspotClient.crm.contacts.basicApi.update(event.object.objectId, {
"properties": {
"referred_by": referred_by
}
})
//10. Update Referring Contacts "number of referrals" and "recent referral date" properties
hubspotClient.crm.contacts.basicApi.update(contactId, {
"properties": {
"number_of_referrals": totalReferralsUpdated,
"recent_referral_date": d
}
})
});
}
@abhianub
Copy link

abhianub commented Feb 22, 2024

Hi @jackcoldrick90 , The code in Workflow-2 is running but not returning the values for number_of_referrals, referred_by, recent_referral_date. The code in use is

// 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) => {
    try {
        // 2. Create our client
        const hubspotClient = new hubspot.Client({
            accessToken: process.env.ReferralProgram
        });

        // 3. Store the referrer ID linked to the enrolled contact in a variable
        const referrer = event.inputFields['referrer'];

        // 4. Create and configure our search filters
        const filter = {
            propertyName: 'referrer_id',
            operator: 'EQ',
            value: referrer
        }
        const filterGroup = {
            filters: [filter]
        }

        const properties = ['referrer_id', 'number_of_referrals', 'firstname', 'lastname', 'email']
        const publicObjectSearchRequest = {
            filterGroups: [filterGroup],
            properties,
        }

        // 5. Search the CRM for the contact using the query defined above
        const results = await hubspotClient.crm.contacts.searchApi.doSearch(publicObjectSearchRequest);

        if (results.total === 0) {
            throw new Error("No contact found with the provided referrer ID.");
        }

        // 6. Store data in variables
        const contactId = results.results[0].id; // Id of the referring contact
        const referred_by = `${results.results[0].properties.firstname} ${results.results[0].properties.lastname}`; // full name of the referring contact
        let totalReferrals = 0;

        // 7. Check to see if this is their first referral. If it is, set "totalReferrals" property to "0"
        if (results.results[0].properties.number_of_referrals) {
            totalReferrals = parseInt(results.results[0].properties.number_of_referrals);
        }

        const totalReferralsUpdated = totalReferrals + 1; // Increment referrals

        // 8. Create a new date (today's date)
        var d = new Date();
        d.setUTCHours(0, 0, 0, 0);

        // 9. Update Referred Contact's "referred by" property
        await hubspotClient.crm.contacts.basicApi.update(event.object.objectId, {
            "properties": {
                "referred_by": referred_by
            }
        });

        // 10. Update Referring Contacts "number of referrals" and "recent referral date" properties
        await hubspotClient.crm.contacts.basicApi.update(contactId, {
            "properties": {
                "number_of_referrals": totalReferralsUpdated,
                "recent_referral_date": d
            }
        });

        callback(null, {});
    } catch (error) {
        callback(error);
    }
};

@abhianub
Copy link

Please find the images for reference @jackcoldrick90
Screenshot 2024-02-22 171050
Screenshot 2024-02-22 165427
Screenshot 2024-02-22 165408
Screenshot 2024-02-22 165350

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment