Hi guys,
I’m trying to integrate Klaviyo through GTM for a custom website and no native integration. I’m trying to capture a user email on the website on a newsletter form, then sync it to Klaviyo and also subscribe it to email marketing and push that user into a list. However, I tried to follow the API sample code but it always return 401 error unauthorized. It works on Postman if I put the API Key into Authorization section instead of Header section. The API I’m using is https://developers.klaviyo.com/en/v1-2/reference/subscribe. Here’s my script on GTM:
<script>
var email = document.querySelectorAll("input[id='subscr_email723']")[0].value;
var _learnq = _learnq || [];
_learnq.push(['identify', {
'$email' : email,
'from_source': "Newsletter"
}]);
setTimeout(function() {
var options = {
method: 'POST',
headers: {
accept: 'application/json',
revision: '2023-12-15',
'content-type': 'application/json',
'Authorization': 'Klaviyo-API-Key pk_…...'
},
body: JSON.stringify({
data: {
type: 'profile-subscription-bulk-create-job',
attributes: {
custom_source: 'Marketing Event',
profiles: {
data: [
{
type: 'profile',
attributes: {
email: email,
subscriptions: {
email: {marketing: {consent: 'SUBSCRIBED'}},
}
}
}
]
}
},
relationships: {list: {data: {type: 'list', id: '….’}}}
}
})
};
fetch('https://a.klaviyo.com/api/profile-subscription-bulk-create-jobs/', options)
.then(function(response) {
return response.json();
})
.then(function(response) {
console.log(response);
})
.catch(function(err) {
console.error(err);
});
}, 2000);
</script>