Sync contacts from Magento to Hubspot using REST API

Last updated on 15th September 2022

Hubspot is a CRM platform that provides all the necessary tools to manage a organization's interactions with its customers. It helps build customer relationships, improve customer service and increase sale and in marketing. On the other hand, Magento(now Adobe Commerce) is an open-source e-Commerce platform. Integrating these two platforms will help increase online sales, increaese repeat sales and also build and maintain strong customer relationship.

One of the main benefits of integrating Magento and Hubspot is that you can get all the customer details from Magento in to Hubspot. Here is a demo program written in Python which gets all customer records from Magento and create them as contacts in Hubspot using REST API.

This script is for demo purposes only should not be used in a production environment.

Before you can run this script, you need to generate the API Access tokens for Magento and Hubspot. Please refer to the following article for generating access token in Magento. Enable API access on Magento

For Hubspot API token, go to Settings → Account Setup → Integrations → Private Apps → Create a Private App Create an app and select the resources to generate the token.

Python script to add Magento customers as contacts in Hubspot

Here is a summary or how this program works.

  1. Import Python packages request and json. The request package is used to send HTTP GET and POST requests to the REST API endpoints. We also require the json package to encode and decode the data that is exchanged.

  2. Define the base url and API access tokens for Magento and Hubspot.

  3. Define the request headers. Header provides additional information to the request such as content type and authorization information of the client for the resource that is requested.

  4. get_hub_contacts() function sends a GET request to get all the contacts from Hubspot.

  5. batch_create_hub_contacts(payload) function send a POST request to create the contacts in Hubspot as a batch job. The payload parameter passed to the function contains contact details such as email, first name and lastname.

  6. get_mag_customers() function send a GET request get all customers from Magento.

  7. In the main() function, first we get all the customers from Magento. Then iterate through each customer and adds it to a list of contacts. The list is finally converted in to the JSON format and passed as a parameter to the batch_create_hub_contacts() function.

    If a contact with same email already exists in Hubspot then the response from batch_create_hub_contacts() will show a error message and none of the contacts will be created.

  8. Finally, you call the get_hub_contacts() function to get all contacts from Hubspot

import requests
import json

# Define API base url and access token variables
mag_baseURL = "http://<host>/rest/default/V1/"
mag_token = "<magento_api_access_token>"

hub_baseURL = "https://api.hubapi.com/crm/v3/objects/"
hub_token = "<hubspot_api_access_token>"

mag_headers = {
   "Accept": "application/json",
   "Content-Type": "application/json",
   "Authorization" : 'Bearer '+ mag_token
}

hub_headers = {
   "Accept": "application/json",
   "Content-Type": "application/json",
   "Authorization" : 'Bearer '+ hub_token
}

# get hubspot contacts
def get_hub_contacts():
    url = hub_baseURL + "contacts?" + 
         "properties=email&properties=firstname&properties=lastname"
    response = requests.request(
        "GET", 
        url,
        headers=hub_headers
    )
    return(json.loads(response.text)['results'])  

# Batch create hubspot contacts
def batch_create_hub_contacts(payload):
    url =  hub_baseURL + "contacts/batch/create"
    response = requests.request(
        "POST", 
        url,
        headers=hub_headers,
        data=payload
    )
    return(json.loads(response.text))  
  
# Get all Magento Customers
def get_mag_customers():
    url = mag_baseURL + 
        "customers/search?searchCriteria='" + 
        "&fields=items[id,email,firstname,lastname]" #+ 
        #"&fields=items[id, email]"
    response = requests.request(
        "GET", 
        url,
        headers=mag_headers
    )
    return(json.loads(response.text))  

def main():
    # Get Magento customers
    mag_customers = get_mag_customers()
    print("Magento Customers:")
    print(mag_customers)
  
    # Create payload for batch creation
    lst=[]
    for c in mag_customers["items"]:    
        lst.append({"properties":{"email": c["email"],
                    "firstname": c["firstname"],
                    "lastname": c["lastname"]}
          })
    payload = json.dumps({"inputs": lst})
    
    # Batch create contacts in hubspot
    resp = batch_create_hub_contacts(payload)
    print(resp)

	# Get Hubspot contacts
    hub_contacts = get_hub_contacts()
    print("Huspot Contacts:")
    print(hub_contacts)
  
if __name__ == "__main__":
    main()

Looking for Hubspot-Magento or other CRM/ERP system integration? Contact us for a quote.


Post a comment

Comments

Nothing yet..be the first to share wisdom.