How to make Associations (Company & Contact) in HubSpot API

How to make Associations (Company & Contact) in HubSpot API

Share

Finally, HubSpot API & Associations

It’s pretty difficult to find out about associations in HubSpot API in their own API documentarians. So it’s good idea to check hits out.

<?php
// Association.php
use HubSpot\Client\Crm\Associations\V4\ApiException;
use HubSpot\Client\Crm\Associations\V4\Model\AssociationSpec;
use HubSpot\Client\Crm\Associations\V4\Model\BatchInputPublicAssociationMultiPost;
use HubSpot\Client\Crm\Associations\V4\Model\PublicAssociationMultiPost;


class Association
{
    private $client;

    public function __construct($client)
    {
        $this->client = $client;
    }

    public function associate(string $contactId, string $companyId)
    {

        $associationSpec = new AssociationSpec([
            'association_category' => 'HUBSPOT_DEFINED',
            'association_type_id' => 1 // Typically, '1' is used for associating a contact with a company, but confirm this in the HubSpot API documentation
        ]);

        // Define the association from the contact to the company
        $publicAssociationMultiPost = new PublicAssociationMultiPost([
            'types' => [$associationSpec],
            'from' => ['id' => $contactId],
            'to' => ['id' => $companyId]
        ]);

        $batchInputPublicAssociationMultiPost = new BatchInputPublicAssociationMultiPost([
            'inputs' => [$publicAssociationMultiPost],
        ]);

        try {
            // Create the association; replace 'contacts' and 'companies' with the actual object types you're associating
            $this->client->crm()->associations()->v4()->batchApi()->create('contacts', 'companies', $batchInputPublicAssociationMultiPost);

        } catch (ApiException $e) {
            new HSErrorHandler($e->getMessage(),  __LINE__ . __FILE__, $e->getCode());
            return;
        }

    }

}

Prerequisites

Before embarking on this journey, ensure you’re equipped with a solid understanding of PHP, including classes, interfaces, methods, and loops. Additionally, Composer, a dependency manager for PHP, should be installed on your system. It’s the tool that will manage the libraries our project relies on.

If you need assistance with something in HubSpot API, you can always contact me for free to consult.

Setting Up Your PHP Environment

  1. Install Composer: If you haven’t already, download and install Composer from its official website.
  2. Initialize Your PHP Project: In your project directory, execute composer init. Follow the prompts to set up your project.
  3. Include the HubSpot API Client: Run composer require hubspot/api-client to add the HubSpot API client library to your project.
  4. Follow our two posts and get the classes for companies and contact

Crafting the Code

Our codebase will primarily consist of two files: Association.php for handling associations between contacts and companies, and an error handling class to gracefully manage any exceptions that arise.

Association.php: The Core of Our Integration

Access Token Setup

define("HUBSPOT_ACCESS_TOKEN", "YOUR_ACCESS_TOKEN");

Replace "YOUR_ACCESS_TOKEN" with your actual HubSpot API access token. Storing this token securely is crucial, and you might consider saving it in your database for enhanced security.

Importing HubSpot Classes

We’ll need to import several classes from the HubSpot API client library to interact with the contacts part of HubSpot’s CRM, handle data models, and manage exceptions.

use HubSpot\Factory;
use HubSpot\Client\Crm\Contacts\Model\SimplePublicObjectInputForCreate;
use HubSpot\Client\Crm\Contacts\Model\SimplePublicObjectInput;
use HubSpot\Client\Crm\Contacts\ApiException;
use HubSpot\Client\Crm\Contacts\Model\Filter;
use HubSpot\Client\Crm\Contacts\Model\FilterGroup;
use HubSpot\Client\Crm\Contacts\Model\PublicObjectSearchRequest;

The Association Class

This class is the cornerstone of our project, facilitating the creation of associations between contacts and companies in HubSpot.

  • Properties:
    • $client: Holds the HubSpot client instance.
    • $id: Stores the ID of the current contact.
    • $contact: Stores the contact object.
    • $properties: An array to hold contact properties like email, firstname, and lastname.
  • Constructor __construct($client): Initializes the class with a HubSpot client instance.
  • Method create($properties): Handles the creation of a new contact or updates an existing one based on the provided properties. It validates the input, checks for the existence of the contact by email, and either updates the existing contact or creates a new one.
  • Method update(): Updates the properties of an existing contact using the HubSpot API.
  • Method findByEmail($email): Searches for a contact by email, constructing a filter to perform the search. If found, it stores and returns the contact ID; otherwise, it returns null.

Error Handling with HSErrorHandler

The HSErrorHandler class is our custom error logging mechanism. It captures and logs errors for debugging purposes, making it an essential component for robust error management in our integration.

class HSErrorHandler
{
    private $message;
    private $code;
    private $path;

    public function __construct($message, $path, $code)
    {
        $this->message = $message;
        $this->code = $code;
        $this->path = $path;
        $this->log();
    }

    public function log()
    {
        // Logging logic here
    }
}
  • Properties:
    • $message: The error message.
    • $code: The error code.
    • $path: The file path where the error occurred.
  • Method __construct($message, $path, $code): Initializes the class with the error details.
  • Method log(): Formats and logs the error. You can use error_log() or write the error to a file.

Bringing It All Together

The final step involves creating an instance of the Association class with the HubSpot client, setting the contact properties, and executing the contact creation or update process. Upon successful execution, the contact ID is retrieved for further operations.

This snippet showcases the simplicity and power of integrating with HubSpot’s API using PHP. By understanding and utilizing these code constructs, you can overcome the limitations of HubSpot’s standard forms and automate complex CRM tasks, paving the way for more streamlined and efficient business processes.

Remember, this is just the beginning. The full potential of HubSpot’s API, combined with the flexibility of PHP, opens up a vast landscape of possibilities waiting to be explored.

$client = Factory::createWithAccessToken(HUBSPOT_ACCESS_TOKEN);
$association = new Association($client);
$contactProperties = [
    'firstname' => 'John',
    'lastname' => 'Doe',
    'email' => 'john.doe@example.com',
    // Additional properties...
];

// Create or update the contact
$association->create($contactProperties);
$contactId = $association->getContactId();

// Handle errors or further operations
if ($contactId === null) {
    // Error handling or early exit
}

Example:

use HubSpot\Factory;

class HSFormIntegration
{
    private $formId;
    private string $hubSpotAccessToken;
    private string $hubSpotSecretKey;
    private $hubSpotClient;

    //assign the companies and contact into the properties
    private $properties = ['companies', 'contacts'];



    public function getHubSpotAccessToken()
    {
        return $this->hubSpotAccessToken;
    }

    public function getHubSpotSecretKey()
    {
        return $this->hubSpotSecretKey;
    }

    public function submitEntryToHubSpot()
    {
        //we need to create a client, then contact, company, association and thats it
        $this->hubSpotClient = Factory::createWithAccessToken($this->hubSpotAccessToken);
        // $data = json_encode($this->processedEntryFormFieldsWithValues);
        $this->connect();
    }

    private function connect()
    {
        // initialize contact, companies, association 
        $contact = new Contact($this->hubSpotClient);
        $contactProperties = $this->properties['contacts'];

        // Create a contact and retrieve the contact ID
        $contact->create($contactProperties);
        // error_log(json_encode(var_dump($re)));
        $contactId = $contact->getContactId();

        if ($contactId === null)
            return;

        // Check if company properties exist and are not empty
        if (!empty ($this->processedEntryFormFieldsWithValues['companies'])) {
            $companyProperties = array_filter($this->properties['companies'], function ($company) {
                // Remove any empty values from the company array
                $filteredCompany = array_filter($company, function ($value) {
                    // Define conditions for a value to be considered non-empty
                    return !empty ($value) && $value !== '';
                });
                // A company is considered effectively empty if the filtered array is empty
                return !empty ($filteredCompany);
            });

            // Proceed only if there are non-empty company arrays
            if (!empty ($companyProperties)) {
                $companies = new Company($this->hubSpotClient);

                // Initialize an array to store the IDs of the companies that are successfully created
                $companyIds = [];
                $companies->create($companyProperties);
                $companyIds = $companies->getCompanyIds();
                // new HSErrorHandler(json_encode($companyIds), __FILE__, __LINE__);
                // Check if any companies were created
                if (count($companyIds) > 0) {
                    $association = new Association($this->hubSpotClient);

                    foreach ($companyIds as $companyId) {
                        $association->associate($contactId, $companyId); // Assuming associate() method exists
                    }
                }
            }
        }


    }


}

Download Composer here:

Composer