0

Create or Update Contact

by
Published today

Create a contact, or update it when a contact with this email already exists.

Script hubspot Verified

The script

Submitted by hugo989 Typescript (fetch-only)
Verified 4 hours ago
1
//native
2

3
/**
4
 * Create or Update Contact
5
 * Create a contact, or update it when a contact with this email already exists. `properties` maps internal property names to values (firstname, lastname, phone, ...).
6
 */
7
export async function main(
8
  auth: RT.Hubspot,
9
  email: string,
10
  properties: { [key: string]: any } | undefined
11
) {
12
  const response = await fetch(
13
    "https://api.hubapi.com/crm/v3/objects/contacts/batch/upsert",
14
    {
15
      method: "POST",
16
      headers: {
17
        Authorization: `Bearer ${auth.token}`,
18
        "Content-Type": "application/json",
19
        Accept: "application/json",
20
      },
21
      body: JSON.stringify({
22
        inputs: [
23
          { id: email, idProperty: "email", properties: properties ?? {} },
24
        ],
25
      }),
26
    }
27
  )
28

29
  if (!response.ok) {
30
    throw new Error(`${response.status} ${await response.text()}`)
31
  }
32

33
  const { results } = (await response.json()) as { results: any[] }
34
  return results[0]
35
}
36