Ian Brant
Ian Brant

Reputation: 49

POST Request to Google Analytics with Measurement Protocol from the App Script returns valid response but doesnt work

I'm trying to send offline conversions data to Google Analytics using the Measurement Protocol

I'm sending this POST Request using the Google AppScripts:

function hitPageViewGA (line,sheet) {

  var range = sheet.getRange(line,1,1,10);
  var values = range.getValues();

  var origem = values[0][6];
  var campanha = values[0][7]

  var data =    {'v': '1',
                 'tid': 'UA-81598809-3',
                 'cid': generateUUID_(),
                 'z': Math.floor(Math.random()*10E7),
                 't':'pageview',
                 'dl':'https://77digitalmarketing.com/teste',
                 'cs':origem,
                 'cn':campanha
                };

   var payload = Object.keys(data).map(function(key) {
                                        return encodeURIComponent(key) + '=' + encodeURIComponent(data[key]);
                                    }).join('&');

  var options = {
  'method' : 'POST',
  'payload' : payload,
  'headers' : {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36'}
    }; 


  var response = UrlFetchApp.fetch('https:/www.google-analytics.com//collect',options);

  return response; 
}

When I send the request to https://www.google-analytics.com/debug/collect to validate the request, I get a valid response. Also, when I test the generated payload in the Request Builder , it works! I just doesnt work when the request is done by the Google App Scripts.

Does someone know why that would happen?

Thanks!

Upvotes: 1

Views: 1459

Answers (2)

jogo
jogo

Reputation: 111

First of all, you have a typo in the code '//collect'. That might have caused it...

I have been 'banging my head against the wall' whole morning to make Analytics work with Apps Script...

I had a working Apps Script code for another Analytics property. I set up a new property, copied the code and events were not showing up at all. When I sent the same request from Postman I saw it immediately in the real-time dashboard...

To make the story short as I am still quite pissed off and to save you some frustration :) simply disable bot filtering! Go to Admin -> View Settings and disable Bot Filtering option.

For some reason requests coming from Apps Script environment are treated as suspicious...

Upvotes: 2

Ian Brant
Ian Brant

Reputation: 49

Well, turns out it was an IP issue. Google AppsScripts send the requests using some standard IPs that Google Analytics identifies as being bots, so I just needed to specify the IP adress in the request.

Upvotes: 3

Related Questions