Solved

401 Unauthorized API Call on Google Tag Manager

  • 9 January 2024
  • 3 replies
  • 91 views

Badge +2

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>

 

icon

Best answer by saulblum 9 January 2024, 13:48

View original

3 replies

Userlevel 5
Badge +7

Hi! If you’re calling this from the browser JavaScript, you’ll want to use the Create Client Subscription call: https://developers.klaviyo.com/en/reference/create_client_subscription

You can specify the ID of a list to which to add the profile.

You should never expose private API keys in JavaScript.

Badge +2

Hi! If you’re calling this from the browser JavaScript, you’ll want to use the Create Client Subscription call: https://developers.klaviyo.com/en/reference/create_client_subscription

You can specify the ID of a list to which to add the profile.

You should never expose private API keys in JavaScript.

Thank you for your answer. I used the Create Client Subscription API and it worked!

Userlevel 5
Badge +7

Good to hear!

Reply