Below, I've posted the code that works for returning ad account adspend into a Google Sheets cell. I'm trying to output the ad account limits to a different cell. This way, we could calculate the remaining budget on ad accounts, by subtracting the adspend from the account limit. Below, I'll post my code that worked for returning the adspend from certain accounts and certain timeframes:
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 = 'my_access_token'
// 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);
const results = JSON.parse(fetchRequest.getContentText());
// Returns the spend
var data = [];
results.data.forEach(function (pieceOfData){
data.push(Number(pieceOfData.spend));
});
if (data >= 0.01)
return data;
else
return 0;
}
This is the formula that we use in Google Sheets to get the ad account spending:
=FacebookReporting("ad_acc_id,"[{since:'2022-08-01',until:'2022-08-30'}]")
The ad_acc_id and my_access_token would usually be filled in. I tried to replace the FIELDS=spend with spend_cap, which I had heard as a parameter from another GitHub post, but it didnt work. I've also posted the same issue to Facebook Developers, so If a solution arises I'll be sure to share it here too.
All and any suggestions are appreciated.