// All Actions should start with a function called output()
async function output({ first_name, last_name, email }) {
// @TODO: Replace with your actual company name,
// and provide the API key to Embeddables to store securely on the backend
const API_KEY_IDENTIFIER = "{{YOUR_COMPANY_NAME---klaviyo---api_key}}";
// @TODO: Update to match your User Data keys, and add any additional data you want to send
const importProfileBody = {
data: {
type: "profile",
attributes: {
email: email || "",
first_name: first_name || "",
last_name: last_name || "",
},
},
};
// Constructs the fetch options object
const importProfileRequestOptions = {
method: "POST",
headers: {
accept: "application/vnd.api+json",
revision: "2024-10-15",
"content-type": "application/vnd.api+json",
Authorization: API_KEY_IDENTIFIER
},
body: JSON.stringify(importProfileBody),
};
// Sets the URL to the Klaviyo API endpoint
const url = "https://a.klaviyo.com/api/profile-import/";
// Sends POST request, using the Embeddables backend proxy to keep the API key secure
const response = await fetch(`https://proxy-secure.trysavvy.com/?url=${encodeURIComponent(url)}`, importProfileRequestOptions)
.then(response => response.json())
.catch(err => {
console.error("Error importing profile", err);
throw err;
});
// If the response doesn't contain an id, throw an error
if (!response?.data?.id) {
console.error("Failed to import profile - no id returned");
throw new Error("Failed to import profile");
}
// If the response is successful, add the user to a list
const id = response.data.id;
const listId = "listID";
const addToListBody = {
data: [
{
type: "profile",
id: id,
},
],
};
// Constructs the fetch options object
const addToListRequestOptions = {
method: "POST",
headers: {
accept: "application/vnd.api+json",
revision: "2024-10-15",
"content-type": "application/vnd.api+json",
Authorization: API_KEY_IDENTIFIER,
},
body: JSON.stringify(addToListBody),
};
// Constructs the URL to the Klaviyo API endpoint
const url = `https://a.klaviyo.com/api/lists/${listId}/relationships/profiles`;
// Sends POST request, using the Embeddables backend proxy to keep the API key secure
fetch(
`https://proxy-secure.trysavvy.com/?url=${encodeURIComponent(url)}`,
addToListRequestOptions
)
.then(response => {
console.log("Response adding to list", response);
})
.catch(err => {
console.error("Error adding to list", err);
throw err;
});
}