# Hubspot

## Overview <a href="#overview-1" id="overview-1"></a>

Hubspot is a popular marketing automation software tool. In early 2022, Hubspot added Custom Code functionality to their Workflows, enabling a direct connection to Lob. Hubspot’s Workflows can be used to automatically trigger a mailpiece to be sent, via Lob.

## Video walkthrough <a href="#video-walkthrough-2" id="video-walkthrough-2"></a>

{% embed url="<https://lob.wistia.com/medias/8i5n3cksrc>" %}

## Step-by-step walkthrough <a href="#step-by-step-walkthrough-3" id="step-by-step-walkthrough-3"></a>

### Create accounts

A developer plan for testing with Lob is free, but you will need to [create a Lob account](https://dashboard.lob.com/login) to get your API Keys.&#x20;

If you do not already have one, [create a Hubspot account here](https://app.hubspot.com/signup-hubspot/crm?uuid=ff52f537-4146-48e8-8cd2-8545c26b767d\&step=landing_page). You’ll want to enable Operations Hub / Marketing Hub Professional trial (note this lasts 14 days): **Automation > Workflows > Start 14 Day Trial**

### Create contacts

You can create manually, or import from a CSV by clicking **Contacts > Import**. From there, walk through the flow to import a file from your computer: **Start an Import > File From Computer > One File > One Object > Contacts**. Ensure your contacts have address parameters; you can [use this CSV](https://s3.us-west-2.amazonaws.com/public.lob.com/solutions/Hubspot_demo/Hubspot_demo_Contacts_10.csv) as an example.

{% hint style="warning" %}
We will be creating a list in the next step, so for this walkthrough, do not select “Create a List from this Import”.&#x20;
{% endhint %}

In the Map File screen, for ‘**Address2**’, select ‘**Create A New Property**’, and name it ‘**Address2**’.&#x20;

<figure><img src="/files/vSi6q5B7u4R4PcZSbHB6" alt=""><figcaption></figcaption></figure>

### Create a List <a href="#create-a-list-5" id="create-a-list-5"></a>

**Contacts** > **Segments (Lists)** > **Create Segment > Create a segment of Contacts > Add filter > Memberships > Import membership > Select the CSV you just imported.**

<figure><img src="/files/iox41DnR7srDztmvipSI" alt=""><figcaption></figcaption></figure>

Choose processing type "Static", then save and process segment.

### Create a Workflow <a href="#create-a-workflow-6" id="create-a-workflow-6"></a>

Select **Automation** > **Workflows**

<figure><img src="/files/ExiFz7X9cqd7v7sSXQz3" alt=""><figcaption></figcaption></figure>

Click **Create Workflow > From scratch**

![](/files/Q3jTYI6jF8cBnV9x0ap6)<br>

### Set Up Trigger

For example, **List Memberships** > **Select List you previously created** > **Is Member of List**

<figure><img src="/files/WJv1lBLVKWqsmVpm5iB4" alt=""><figcaption></figcaption></figure>

### Create a resulting Action <a href="#create-a-resulting-action-7" id="create-a-resulting-action-7"></a>

Click **+** button on Workflow, beneath the Trigger, then from the **Data ops** dropdown, select **Custom code**

<figure><img src="/files/rEV9X4UsMIhOMJlXARHO" alt=""><figcaption></figcaption></figure>

Here you can select Python or NodeJS. For this example, we will select **Language: Python**. Then we will map Lob’s API fields to Hubspot properties, and enter our custom code. For this example, **Map Properties To Include in Code** as follows:

<figure><img src="/files/pfgLIA53Ou7znkoiAi33" alt=""><figcaption></figcaption></figure>

Finally, enter your Python code, with properties defined as per the prior step. See example code below to test with.

#### Example Python code <a href="#example-python-code-8" id="example-python-code-8"></a>

```python
import requests
import json
import base64
import os
from hubspot import HubSpot
from hubspot.crm.contacts import ApiException
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry


def retry_session(retries, session=None, backoff_factor=1):
    session = session or requests.Session()
    retry = Retry(
        total=retries,
        read=retries,
        connect=retries,
        backoff_factor=backoff_factor,
        status_forcelist=[500, 502, 503, 504, 429],
        allowed_methods=['POST']
    )
    adapter = HTTPAdapter(max_retries=retry)
    session.mount('http://', adapter)
    session.mount('https://', adapter)
    return session


def main(event):
    address = event.get('inputFields').get('address')
    address2 = event.get('inputFields').get('address2')
    city = event.get('inputFields').get('city')
    state = event.get('inputFields').get('state')
    zip_code = event.get('inputFields').get('zip_code')
    email = event.get('inputFields').get('email')
    hs_object_id = event.get('inputFields').get('hs_object_id')
    phone = event.get('inputFields').get('phone')
    firstname = event.get('inputFields').get('firstname')
    lastname = event.get('inputFields').get('lastname')

    url = "https://api.lob.com/v1/postcards"

    payload = {
        "description": "HUBSPOT DEMO POSTCARD",
        "to[name]": firstname + ' ' + lastname,
        "to[address_line1]": address,
        "to[address_line2]": address2,
        "to[address_city]": city,
        "to[address_state]": state,
        "to[address_zip]": zip_code,
        "front": "https://s3.us-west-2.amazonaws.com/public.lob.com/solutions/retail_pdfs/4x6+Retail+front.pdf",
        "back": "https://s3.us-west-2.amazonaws.com/public.lob.com/solutions/retail_pdfs/4x6+Retail+back.pdf",
        "size": "4x6",
        "metadata[customer_id]": hs_object_id,
        "metadata[campaign]": "HUBSPOT_TEST",
        "metadata[phone]": phone,
        "metadata[email]": email,
        "metadata[front_creative_name]": "demo_hubspot_front_creative",
        "metadata[back_creative_name]": "demo_hubspot_back_creative",
        "metadata[address_city]": city,
        "metadata[address_state]": state,
        "metadata[address_zip]": zip_code
    }

    session = retry_session(retries=5)
    r = session.post(url, auth=requests.auth.HTTPBasicAuth(YOUR_API_KEY, ''), data=payload)
    j = r.json()
    print(j)
```

{% hint style="warning" %}
If copying and pasting the Python code above, it is advised to run it through a Python code validator to ensure that no formatting issues occur as a result.&#x20;
{% endhint %}

### Add your API Keys <a href="#add-your-api-keys-11" id="add-your-api-keys-11"></a>

Next we need API credentials from our Lob account. Retrieve these credentials from your Lob dashboard by clicking on the **Settings** menu on the sidebar, then clicking on the API Keys tab.

In the example Python code, replace `YOUR_API_KEY` with your **Test API Key**.&#x20;

{% hint style="danger" %}
**ENSURE YOU ARE USING YOUR TEST API KEY**
{% endhint %}

### **Update Creative**

You should also replace the front and back "`HUBSPOT_CREATIVE`" with your own HTML, template IDs, or links to hosted static creatives. For example:&#x20;

```
"front": "https://s3.us-west-2.amazonaws.com/public.lob.com/solutions/retail_pdfs/4x6+Retail+front.pdf",
```

```
"back": "https://s3.us-west-2.amazonaws.com/public.lob.com/solutions/retail_pdfs/4x6+Retail+back.pdf",
```

### Testing <a href="#testing-9" id="testing-9"></a>

Make sure to hit **‘Save’.** Then you can open your custom code back up, scroll to the bottom of the panel, and click **Test Action.** Select a contact, and click **Test** to fire off a test request. <br>

<figure><img src="/files/G4kDmp5VL3WEF96nBgiu" alt=""><figcaption></figcaption></figure>

You can then log into your Lob account to verify that a mailpiece was generated.

### Utilizing workflow <a href="#utilizing-workflow-10" id="utilizing-workflow-10"></a>

Once you’ve tested, you can **Publish** your workflow. From there, it will run whenever the trigger you set is fired. For example, if you followed the above example, you can now add some contacts to your list. This should automatically create mailpieces for each person on the list.&#x20;

Now you can replace the Test API key in your Python code with your Base64 Encoded Live API Key, and your Automation is live. If you are using other test resources like address IDs or template IDs, those will also need to be transferred to your live environment.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://help.lob.com/print-and-mail/integrations/api-integrations/hubspot.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
