Created
February 20, 2023 02:10
-
-
Save jensen/1d80ed0d31649a1dd60049621cfd3c58 to your computer and use it in GitHub Desktop.
Adding profiles with Klaviyo API
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const BASE_URL = "https://a.klaviyo.com/api"; | |
const baseHeaders = new Headers({ | |
accept: "application/json", | |
revision: "2023-01-24", | |
Authorization: `Klaviyo-API-Key ${process.env.KLAVIYO_API_KEY}`, | |
}); | |
const getHeaders = new Headers(baseHeaders); | |
const postHeaders = new Headers(baseHeaders); | |
postHeaders.append("Content-Type", "application/json"); | |
export const subscribeUserWithEmail = async ( | |
user: Omit<User, "plan" | "name"> & { description: string } | |
) => { | |
const profiles = await fetch( | |
`${BASE_URL}/profiles?filter=equals(email,"${user.email}")`, | |
{ | |
method: "GET", | |
headers: getHeaders, | |
} | |
).then((response) => response.json()); | |
if (profiles.data.length === 0) { | |
const profile = await fetch(`${BASE_URL}/profiles`, { | |
method: "POST", | |
headers: postHeaders, | |
body: JSON.stringify({ | |
data: { | |
type: "profile", | |
attributes: { | |
email: user.email, | |
external_id: user.id, | |
first_name: user.first_name, | |
last_name: user.last_name, | |
properties: { | |
"Which best describes you?": user.description, | |
}, | |
}, | |
}, | |
}), | |
}).then((response) => response.json()); | |
console.log(profile); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment