Integrating Thnks with HubSpot Using Python

This guide shows you how to automatically send Thnks gifts through HubSpot workflows using custom code actions with Python.

Prerequisites

  • HubSpot Operations Hub Professional or Enterprise license (required for custom code actions)
  • Thnks API Key (Authorization Token)
  • Thnks Gift ID for the gift you want to send
  • Access to HubSpot Workflows

Python Code for HubSpot Custom Code Action

Use the following Python code in your HubSpot custom code action to send Thnks gifts:
import requests

def main(event):
    url = "https://api.thnks.com/api/v1/gift_requests"
    
    # Get data from event
    email = event["inputFields"]["email"]
    first_name = event["inputFields"]["firstname"]
    owner_name = event["inputFields"]["hubspot_owner_id"]
    
    message = f"{first_name}, thank you for having a meeting with me. Please enjoy this box of delicious cookies as a token of my appreciation. I look forward to talking about your goals and objectives soon. - {owner_name}"
    
    payload = {
        "gift_id": <GIFT ID>,
        "recipients": [
            {
                "email": email,
                "first_name": first_name,
                "last_name": event["inputFields"]["lastname"],
                "message": message,
                "gift_redeem_type": "email"
            }
        ]
    }
    
    headers = {
        "Authorization": "<API TOKEN>",
        "Content-Type": "application/json"
    }
    
    try:
        response = requests.request("POST", url, json=payload, headers=headers)
        response.raise_for_status()  # Raise an exception for 4XX/5XX responses
        result = response.json()
        
        # Return the output data for later workflow actions
        return {
            "outputFields": {
                "email": email,
                "response_status": response.status_code,
                "response_data": str(result)
            }
        }
    except Exception as e:
        # Handle errors
        return {
            "outputFields": {
                "email": email,
                "error": str(e)
            }
        }

Setup Instructions

1

Create or Edit a HubSpot Workflow

  1. Log into HubSpot and navigate to Automation > Workflows
  2. Create a new workflow or edit an existing one
  3. Choose your enrollment trigger (e.g., after a meeting is logged, contact property change, etc.)
2

Add a Custom Code Action

  1. In the workflow editor, click the + button to add an action
  2. Select Custom code from the action options
  3. Choose Python 3.9 as the language
3

Configure Input Fields

Set up the following input fields in the custom code action:
  • email - Contact’s email address
  • firstname - Contact’s first name
  • lastname - Contact’s last name
  • hubspot_owner_id - The HubSpot owner’s name or ID
Map these to the appropriate contact properties using the dropdown menus.
4

Add the Python Code

  1. Copy the Python code provided above
  2. Paste it into the code editor
  3. Replace the placeholders:
    • Replace <GIFT ID> with your actual Thnks gift ID (e.g., 12345)
    • Replace <API TOKEN> with your Thnks API authorization token
5

Configure Output Fields

The code returns the following output fields that you can use in subsequent workflow actions:
  • email - The recipient’s email address
  • response_status - HTTP status code from the API call
  • response_data - Full response from the Thnks API
  • error - Error message if the request fails
6

Test the Workflow

  1. Save the custom code action
  2. Use the Test feature to run the workflow with a test contact
  3. Check the workflow execution logs to verify the gift was sent successfully
  4. Look for a 200 or 201 status code in the response
7

Activate the Workflow

Once testing is successful, turn on the workflow to start automatically sending Thnks gifts based on your trigger criteria.

Customization Options

Dynamic Messages

You can customize the message using any HubSpot contact properties. For example:
# Use company name in the message
company_name = event["inputFields"]["company"]
message = f"Hi {first_name}, thank you for taking the time to discuss how {company_name} can benefit from our solutions. Please enjoy this gift! - {owner_name}"

Different Gifts for Different Scenarios

You can use conditional logic to send different gifts:
# Send different gifts based on deal size
deal_amount = event["inputFields"]["deal_amount"]
if deal_amount > 50000:
    gift_id = 12345  # Premium gift
else:
    gift_id = 67890  # Standard gift

Multiple Recipients

To send to multiple recipients, expand the recipients array:
payload = {
    "gift_id": <GIFT ID>,
    "recipients": [
        {
            "email": email,
            "first_name": first_name,
            "last_name": event["inputFields"]["lastname"],
            "message": message,
            "gift_redeem_type": "email"
        },
        {
            "email": event["inputFields"]["manager_email"],
            "first_name": event["inputFields"]["manager_firstname"],
            "last_name": event["inputFields"]["manager_lastname"],
            "message": "Thank you for your team's time!",
            "gift_redeem_type": "email"
        }
    ]
}

Error Handling

The code includes error handling to catch and report issues:
  • Network errors
  • Invalid API credentials
  • Missing required fields
  • API rate limits
Check the workflow execution history to see any errors returned in the error output field.

Best Practices

  1. Test thoroughly - Always test with a small group before rolling out to all contacts
  2. Secure your API key - Never share your Thnks API token
  3. Monitor usage - Keep track of gifts sent to manage your Thnks account balance
  4. Use delays - Consider adding delays between enrollment and gift sending for better timing
  5. Add conditions - Use workflow branches to send gifts only for qualified contacts

Troubleshooting

Common Issues

  • 401 Unauthorized - Check your API token is correct and active
  • 400 Bad Request - Verify all required fields are populated and gift ID is valid
  • Network errors - Ensure HubSpot can reach the Thnks API endpoint
  • Missing data - Confirm all input fields are mapped to existing contact properties

Debug Tips

  1. Use the print() function to log values during testing
  2. Check the workflow history for detailed execution logs
  3. Verify your gift ID is active in your Thnks account
  4. Test with your own email first before sending to contacts

References