0

I'm currently creating a Google Apps Script for my company. We're a marketing agency in control of many Facebook ad accounts. Shortly, we have to update numbers on our own Google Sheet with spending from the clients ad accounts every day. I hated the robotic, manual labor, so I decided to come up with this solution.

The cell would contain the following formula:

=FacebookReporting("ad_acc_id","[{since:'2022-08-01',until:'2022-08-08'}]") 

That way we could create these formulas for each of our ad accounts for whatever timeframe, and the numbers would update automatically every time we entered our sheet.

So far, my code looks like this:

function FacebookReporting(input1, input2) {
    
var AD_ACCOUNT_ID = input1
var TIME_RANGES = input2

// ad, adset, campaign, account
const LEVEL = 'account'

// https://developers.facebook.com/docs/marketing-api/insights/parameters#fields
const FIELDS = 'spend'

// Your user access token
const TOKEN = 'EAAORfG6N4U4BAONzrmHW18PDC0FCGgifwZCCPc692CiQ1UtGvdQoUb0usjdUpWV0cLe9g1sfeWu9XqGcVjexSWvMEkWTpFTqXjWb0skFL5ZCpknaGMZAi5WO9VNubgFL0556NHh2jqAhipZCI0zbOm8f57YCdnM3S7EXTLEZBtrFlJ7Ob0CIG'



  // Builds the Facebook Ads Insights API URL
  const facebookUrl = `https://graph.facebook.com/v14.0/act_${AD_ACCOUNT_ID}/insights?level=${LEVEL}&fields=${FIELDS}&time_ranges=${TIME_RANGES}&access_token=${TOKEN}&limit=1000`;

  const encodedFacebookUrl = encodeURI(facebookUrl);
  
  const options = {
    'method' : 'post'
  };
  
  // Fetches & parses the URL 
  const fetchRequest = UrlFetchApp.fetch(encodedFacebookUrl, options);
  const results = JSON.parse(fetchRequest.getContentText());


// Formats only spend in the cell

var data = [];


results.data.forEach(function(pieceOfData){
  data.push(pieceOfData.spend)
});

return data;

}

I've removed the access token, but that would usually be there. I'm able to open the website, by entering all the right variables, and then the data displays. Screenshot attached of how it looks. Now trying to figure out how to exclude only the number after the spend part and to show it in the cell where the formula is in. With the current code, the cell with the formula is empty.

Any help or suggestions is appreciated, I'm trying to save me and my coworkers about 30% of our time :D

screenshot

The data that I'm able to get from FB is the following:

{
   "data": [
      {
         "spend": "41389.73",
         "date_start": "2022-08-01",
         "date_stop": "2022-08-08"
      }
   ],
   "paging": {
      "cursors": {
         "before": "MAZDZD",
         "after": "MAZDZD"
      }
   }
}

The end goal is that 41389.73 shows up in the cell with the formula.

7
  • 1.You aren't returning anything from your function. 2.Also Why are there two functions? 3.Post data in text instead of screenshots.4. It isn't exactly clear, what data you're looking for. Add the expected output for your sample data.
    – TheMaster
    Aug 8, 2022 at 15:45
  • 1. Yup, got stuck at that. 2. At first I had made it as two different functions, they could be as one, but it doesnt seem to change anything. 3. Posted at the bottom of my post. 4. The data im looking for is the number right after "spend", also clarified that at the bottom of the post.
    – MIXD_Toms
    Aug 8, 2022 at 16:01
  • 2. The inside function never gets executed, because you're not calling it. Either remove it or call it: requestFacebookReport(). Even if you call it, you aren't returning anything from the second function. It's better to remove it. 5. You're basically rewriting the input here:var input1 = 'AD_ACCOUNT_ID' var input2 = 'TIME_RANGES'. Were you trying to do var AD_ACCOUNT_ID =input1 var TIME_RANGES = input2?
    – TheMaster
    Aug 8, 2022 at 16:08
  • Gotcha, removed the function. Yes the variables where the other way around, edited the code post to be correct.
    – MIXD_Toms
    Aug 8, 2022 at 19:45
  • 2
    You just exposed your user token here, so you should go invalidate it now - otherwise anyone finding it here, will be able to make API requests in your name for as long as it is valid (which is currently Oct 07 2022.)
    – CBroe
    Aug 9, 2022 at 6:08

3 Answers 3

1

The solution was to remove options from

const fetchRequest = UrlFetchApp.fetch(encodedFacebookUrl, options);

and to add

  
results.data.forEach(function (pieceOfData){
  data.push(pieceOfData.spend);
});

return data;
0

If I understand correctly you're trying to get the value of spend which is stored under results and then return it, this is how to get it based on the example:

var spend = results.data[0].spend;
return spend;

This assumes that you get only one set of data values.

0

If this data structure is always returned, you should instead programmatically obtain the values of the results constant and format them yourself to an array of your desired size. The reason why I suggest this is because the structure you have is not a simple 1D or 2D array, it is the following:

const: results
├─ array: data
│  ├─ object
│  │  ├─ spend
│  │  ├─ date_start
│  │  ├─ date_stop
├─ paging
│  ├─ cursors
│  │  ├─ before
│  │  ├─ after

To obtain the exact value of the spend property you will need to open the array, they use indexes and the first index is 0 just like @Bryan said.

I suggest you use this code after the const results = JSON.parse(fetchRequest.getContentText()); line:

var data = [];
  
results.data.forEach(function (pieceOfData){
  data.push(pieceOfData.spend);
});

return data;

Since data is an array you could receive multiple spending values, this will list them all in a different row.

5
  • There is an error it's giving me on the sheet imgur.com/a/2xj5dah
    – MIXD_Toms
    Aug 8, 2022 at 20:10
  • Also, the const LEVEL = 'account' is so that FB only sends the adspend of the whole ad account, so there should always only be one value.
    – MIXD_Toms
    Aug 8, 2022 at 20:40
  • In that case using var data = results.data[0].spend; return data; (the same structure suggested in the other answer) should address the problem. If you get the same error message where some property is undefined add a console.log(results); on a line before getting the error and under "Executions" in Apps Script check the most recent one with that data and provide a screenshot it is possible the structure is not the same. Aug 9, 2022 at 15:17
  • Pretty much getting the same error. This is what it looks like: imgur.com/a/Q9hykZ2 and imgur.com/a/FK7tYeE
    – MIXD_Toms
    Aug 9, 2022 at 21:37
  • I would like to see the output you got with the console.log added in line 23. You will find it on the execution logs, more details about these logs are in this page developers.google.com/apps-script/guides/…. Aug 10, 2022 at 0:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.