Automatically creating contacts & deals in Hubspot using Netlify Functions
Tags: php, javascript, node, serverless
Published: 2020-06-13 09:03:51

Here at Memories 2 Digital, we deploy our website as a static site to Netlify. This makes the website super fast & means we don't need to maintain servers. While this is awesome, we don't have a traditional back end to automate stuff like interactions with our CRM (HubSpot).

Using the Hubspot API with Netlify Functions.
---------------------------------------------

Luckily for us, Netlify provides a quick way to add serverless functions to your static site code. There's a couple of steps required to make this work.

First off, we need to add our Hubspot API key in the Netlify build settings. You'll find the in your site's settings under "Build and Deploy"

![Add the variable your environment variables (these can be used in your function)](https://memories2digital.com.au/img/env.png?1)

Add the variable your environment variables (these can be used in your function)

First, we need to create a `netlify.toml` (if you don't already have one) with the following content (to instruct netlify where your functions live)
```
[build]
functions = "./functions"
```
Next, jump into your prefered code editor and create a new folder in the root of your project called `functions`, and inside this create a `deal` folder. Finally, create a `deal.js` file in the folder (where you'll write your code).

Here's the code for the function. I've commented the important parts, but it's pretty simple.

```javascript
exports.handler = async (event, context) => {
  try {
    if (event.httpMethod !== 'POST') {
      // Block GET requests
      return { statusCode: 400, body: null }
    }

    const Hubspot = require('hubspot')
    // This will use your build enviroment varible
    const hubspot = new Hubspot({ apiKey: process.env.HUBSPOT_KEY })

    const body = JSON.parse(event.body)

    // Create the contact for the deal. This will update the existing one if it already exists

    const properties = [
      { 'property': 'firstname', 'value': body.firstName },
      { 'property': 'lastname', 'value': body.lastName },
      { 'property': 'phone', 'value': body.phone },
    ]

    const contact = await hubspot.contacts.createOrUpdate(body.form.email, { properties })

    const deal = await hubspot.deals.create({
      // Use the contact ID from the previous call
      associations: { associatedVids: [contact.vid] },
      properties: [
        {
          'value': `Website Order for ${body.firstName} ${body.lastName}`,
          'name': 'dealname',
        },
        {
          // You'll want to grab from your deal stage config in Hubspot (click the code symbol to find this number)
          'value': 2413030,
          'name': 'dealstage',
        },
        {
          'value': 'default',
          'name': 'pipeline',
        },
        {
          // This is a float, for example 10.50
          'value': body.estimate,
          'name': 'amount',
        },
        {
          // Add any other fields you want
          'value': body.whatever,
          'name': 'whatever',
        },
      ],
    })

    // Return a 200 if it succeeds
    return { statusCode: 200, body: JSON.stringify({ success: true }) }

  } catch (err) {
    return { statusCode: 500, body: err.toString() }
  }
}
```

Push your code up & netlify will deploy your functions. You can test them in an API tool like Postman using the following URL:

`http://your.domain/.netlify/functions/order`

You can now wire it up on the frontend, using javascript or a plain form to submit the data directly to your serverless function!

You're now running dynamic code on your static site!