-1

Sample Code:

function fetchFacebookData() {
  var baseUrl = "https://graph.facebook.com/v20.0/me";
  var fields = "name,adaccounts{amount_spent,name,adspixels{name,stats{start_time,data}}}";
  var accessToken = "TOKEN";
  
  var url = baseUrl + "?" + encodeURI("fields=" + fields) + "&access_token=" + accessToken;

  try {
    var response = UrlFetchApp.fetch(url);
    var data = JSON.parse(response.getContentText());

    var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
    sheet.clear();

    var headers = [
      "Start Date",
      "Campaign Name",
      "Amount Spent",
      "Purchases",
      "Leads"
    ];
    
    var headerColors = ["#FF9800", "#FF9800", "#FFEB3B", "#F44336", "#3F51B5"];
    for (var i = 0; i < headers.length; i++) {
      sheet.getRange(1, i + 1).setValue(headers[i]).setBackground(headerColors[i]).setFontWeight("bold").setFontColor("#FFFFFF");
    }

    var dataRows = [];

    // Set the date range to the last 30 days
    var today = new Date();
    var last30Days = new Date();
    last30Days.setDate(today.getDate() - 30);

    if (data.adaccounts && data.adaccounts.data) {
      data.adaccounts.data.forEach(function(account) {
        var purchases = 0, leads = 0;
        var startDate = "";

        if (account.adspixels && account.adspixels.data) {
          account.adspixels.data.forEach(function(pixel) {
            if (pixel.stats && pixel.stats.data) {
              pixel.stats.data.forEach(function(stat) {
                startDate = stat.start_time || startDate;
                var statDate = new Date(startDate);

                if (statDate >= last30Days) {  // Only include data from the last 30 days
                  stat.data.forEach(function(event) {
                    if (event.value === "Purchase") purchases += event.count;
                    if (event.value === "Leads") leads += event.count;
                  });
                }
              });
            }
          });
        }

        var amountSpent = account.amount_spent ? parseInt(account.amount_spent) / 100 : "N/A";

        if (startDate && (new Date(startDate) >= last30Days)) {
          dataRows.push([
            startDate,
            account.name || "N/A",
            amountSpent,
            purchases || "N/A",
            leads || "N/A"
          ]);
        }
      });
    }

    // Sort dataRows by date in descending order
    dataRows.sort(function(a, b) {
      return new Date(b[0]) - new Date(a[0]);
    });

    // Write sorted data to the sheet
    for (var i = 0; i < dataRows.length; i++) {
      sheet.getRange(i + 2, 1, 1, dataRows[i].length).setValues([dataRows[i]]);
    }

  } catch (error) {
    Logger.log("Error: " + error.toString());
  }
}

It only retrieves data of a single date I want to extract previous 6 months data into google sheet script please help

There is no error in this code I only want to fetch data into sheets of the previous 6 months

I tried every timestamp query also from original meta docs please help someone

1
  • Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking.
    – Community Bot
    Commented Sep 6 at 14:36

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.