Coder Social home page Coder Social logo

fredericharnois / facebook-ads-reporting-google-apps-script Goto Github PK

View Code? Open in Web Editor NEW
149.0 20.0 45.0 24 KB

This script pushes Facebook Ads data to Google Sheets.

License: MIT License

JavaScript 100.00%
google-apps-script google-sheets facebook-api facebook-ads

facebook-ads-reporting-google-apps-script's Introduction

Exporting Facebook Ads data to Google Sheets

This script was built to export Facebook Ads data to Google Sheets on a recurring basis for use in a dashboard.

In order to bypass limits around the amount of data that can be processed by the Facebook Marketing API and Google App Script's 6 minute runtime maximum, the script makes asynchronous requests to the Facebook Marketing API.

Setup

You'll first want to create a Facebook App and add the Marketing API product to it.

You can then get a short-lived user access token through the Graph API Explorer.

If you're going to be using this script on an ongoing basis, I recommend you exchange your short-lived token for a long-lived one using this method.

Once you've entered your credentials as well as all parameters, you'll want to make sure that request-facebook-report.js is scheduled to run before get-facebook-report.js.

facebook-ads-reporting-google-apps-script's People

Contributors

fredericharnois avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

facebook-ads-reporting-google-apps-script's Issues

{"error":{"message":"(#100) param filtering must be an array."

Hi,

I am using the below format in for filtering (in request-facebook script).

var FILTERING = [{"field":"action_type","operator":"IN","value":["link_click"]}]

And it returns the following error:

Request failed for https://graph.facebook.com returned code 400. Truncated server response: {"error":{"message":"(#100) param filtering must be an array.","type":"OAuthException","code":100,"fbtrace_id":"xx"}} (use muteHttpExceptions option to examine full response) (line 59, file "request-facebook-report.js")

Should I put this in some other format?

export-report in local language

Hello Frederic, thank you for putting this together. I am at the cross roads between parsing the JSON and using the export-report provided by Facebook. I need a few of the actions/conversions and also using all the attribution windows options so its a bit fickle to set up the object parsing and the all encompassing report from Facebook is attractive. However since I am currently in Spain the CSV output comes in Spanish. I have been searching for a way to force it to output in English as I don't want the report to change depending on where in the world I am at.. any idea of how to do that?

Otherwise I will go ahead and parse the JSON (I do it Ad by Ad and with a daily reporting).

regards,
Lars

Love What I'm Seeing But I May Need Some Help...

I've got everything in place per the instructions in the articles that led me here, but I am left with a couple of questions as I am very interested in using this on a continuous basis and I have very little technical knowledge.

First, is how do I get the long term access key? I understand that there is a method that is outlined in the link provided, but does this go in its own separate script or does it go right above the access token input in the script called?

Second, I am having trouble getting all of the columns that I need in the right order. Currently, I have this in place:
const FIELDS = "['date_start','date_stop','campaign_id','campaign_name','adset_id','adset_name','ad_id','ad_name','spend','conversions','purchase_roas']"
However, I get 'purchase_roas' placed after 'date_stop' and 'conversions' is not even showing up at all.

Third, I want to run this in a way that saves the data pulled and does not clear it before each run. If there is a way to remove the clear function and have the data appended instead, that would be ideal.

I know this is a lot of customization that I should probably learn to do myself, but if anyone is out there that has run into these issues and has a solution, it would go a long way!

Cannot get conversions

Hello

The conversions field appears like it's ignored, no data comes for that column.
Can conversions be pulled from the graph api / reporting ?

I'm using this:

var LEVEL = 'campaign'
var FIELDS = "['account_id','account_name','campaign_name','impressions','inline_link_clicks',
'website_ctr','cpc','conversions','conversion_values','cost_per_conversion','spend']"
var DATE_RANGE = 'last_month'

Filter results for ads that have insights - Question

Thank you for this script! It is very helpful. Is there a way to filter for only the ads that have insights (i.e. exclude all the ads that were paused between 2016 - 2019)? I'm pulling a report for an account that has been running for many years and they have over 3000 ads in total (and only +/- 30 are active), so the request is unnecessarily large.

I've tried

<BUSINESS_ID>?fields=client_ad_accounts{ads{name,insights{impressions,inline_link_clicks,spend}}}&filtering=[{field: "impressions",operator:"GREATER_THAN", value:"0"}]

But that did not do anything - thousands of inactive ads still appeared in the response.

Thank you in advance for your help :)

date_preset value error

Hi @fredericharnois

Many thanks for the code, it will help me a lot.
I have an issue related with the value of date_preset parameter.
I see in the documentation the accepted values are:
today, yesterday, this_month, last_month, this_quarter, lifetime, last_3d, last_7d, last_14d, last_28d, last_30d, last_90d, last_week_mon_sun, last_week_sun_sat, last_quarter, last_year, this_week_mon_today, this_week_sun_today, this_year, but whatever value I use i get the following error:
Exception: Request failed for https://graph.facebook.com returned code 400. Truncated server response: {"error":{"message":"(#100) date_preset is not valid for fields param. please check https://developers.facebook.com/docs/marketing-api/referen... (use muteHttpExceptions option to examine full response). (line 50, file "Code")

My code is:
const TIME_RANGE = 'yesterday';
const facebookUrl = https://graph.facebook.com/v6.0/act_${AD_ACCOUNT_ID}/insights?level=${LEVEL}&fields=${FIELDS}&date_preset=${TIME_RANGE}&access_token=${TOKEN}&time_increment=${TIME_INCREMENT}&limit=5000;

Can you help me with this issue?

Thanks a lot!

Issue with Parsing Text

Hello @fredericharnois,

First of all, thank you so much for your generosity to share this! It has been super helpful in pulling reports that could have been super tedious to do via the Facebook Ad Manager UI.

The script worked out quite well after some tweaks but for some reason, I kept encountering the following issues:

  • the 'request-facebook-report' script would work out smoothly but the get-facebook-report script would show the "unable to parse text at line 27" error at least a few times. It would require a few persistent manual runs before the raw data gets pushed onto Google Sheets. Wondering what could have caused this?
  • once the data is generated on Google Sheet, the header does not seem to align with the "field sequence". For my case: the
    Post Comments | Post Shares | Link Clicks | Landing Page Views headers would be placed before Campaign Name | Ad Name | Ad Set Name ones. Would you happen to know what could have led this and is there any way to change that?

Here's the version that I replicated on my end:

`// MODIFY YOUR REPORT HERE //

// ad account ID
const AD_ACCOUNT_ID = 'xxxxxxxx'

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

// https://developers.facebook.com/docs/marketing-api/insights/parameters#fields
const FIELDS = 'campaign_name,ad_name,adset_name,impressions,clicks,spend,cpc,actions,conversions,frequency,video_p75_watched_actions,cost_per_thruplay'

// https://developers.facebook.com/docs/marketing-api/insights/parameters#param
const DATE_RANGE = 'this_year'

// user access token linked to a Facebook app
const TOKEN = 'xxxxx'

// number of days from 1 to 90
const TIME_INCREMENT = 'monthly'

// https://developers.facebook.com/docs/marketing-api/insights/parameters#param
const FILTERING = "[{'field':'action_type','operator':'IN','value':['comment','like','post','video_view','link_click','landing_page_view']}]"

// DO NOT MODIFY ANYTHING BELOW //

function requestFacebookReport() {

// Builds the Facebook Ads Insights API URL
const facebookUrl = https://graph.facebook.com/v9.0/act_${AD_ACCOUNT_ID}/insights?level=${LEVEL}&fields=${FIELDS}&date_preset=${DATE_RANGE}&access_token=${TOKEN}&time_increment=${TIME_INCREMENT}&filtering=${FILTERING}&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());

// Caches the report run ID
const reportId = results.report_run_id;
const cache = CacheService.getScriptCache();
const cached = cache.get('campaign-report-id');

if (cached != null) {
cache.put('campaign-report-id', [], 1);
Utilities.sleep(1001);
cache.put('campaign-report-id', reportId, 21600);
} else {
cache.put('campaign-report-id', reportId, 21600);
};

Logger.log(cache.get('campaign-report-id'));
}

// MODIFY YOUR SETTINGS HERE //

// url of the google sheets where the report will be
const SPREADSHEET_URL = 'XXX'

// name of the sheet where the report will be
const TAB_NAME = 'XXX'

// DO NOT MODIFY ANYTHING BELOW //

function getFacebookReport() {

// Selects the chosen sheet and tab
const ss = SpreadsheetApp.openByUrl(SPREADSHEET_URL);
const sheet = ss.getSheetByName(TAB_NAME);

// Clears the sheet
sheet.clear();

// Gets the Facebook report run ID
const cache = CacheService.getScriptCache();
const reportId = cache.get('campaign-report-id');

// Fetches the report as a csv file
const url = https://www.facebook.com/ads/ads_insights/export_report?report_run_id=${reportId}&format=csv&access_token=${TOKEN};
const fetchRequest = UrlFetchApp.fetch(url);
const results = Utilities.parseCsv(fetchRequest);

// Pastes the csv file in the sheet
sheet.getRange(1,1, results.length, results[0].length).setValues(results);
}`

Appreciate your advice on this and once again thank you so much for sharing this knowledge!

No response

Hi! Thank you so much for writing this code! It will be super helpful once I figure out how to run it.

I'm a complete beginner with Javascript, and I'm not getting a response when either running request or get using Node. Does the code need to be run in specific environment? or am I just missing something in the parameters?

image

Could not parse text. (line 47, file "get-facebook-report.js")

Hi there Frederic,

Thank you for providing the script, very useful however I'm encountering the below error when running get-facebook-report.js

screenshot

The script appears to run when TIME_INCREMENT is set to '90' in request-facebook-report.gs as below but fails if set to '1'

image

Any help would be greatly appreciated!

Many thanks,
Tom

action_type question

Hello,

Great script, thank you so much.

I'm having a problem getting specific actions out to Sheets. I'm effectively passing this to FB through your script:

/insights?level=ad&fields=campaign_name,adset_name,ad_name,actions&action_breakdowns=action_type&filtering=[{"field":"action_type","operator":"IN","value":["link_click"]}]

Which builds the CSV with every single possible action as columns and Sheets throws the following:

"This action would increase the number of cells in the workbook above the limit of 5000000 cells. (line 48, file "get-facebook-report")"

Presume this isn't intended behaviour on FB's part and I'm being moronic?

Thanks

No output to Google Sheet

Hi Frederic,

Somehow I can't get the script to put actual data to my spreadsheet.
The script itself works without any visible errors, it generates and fetches the report ID just fine, but I still get an empty sheet as a result.
The document is open to editing by anyone with the link, so it seems it's not an issue with access.
Shouldn't be an issue with API version either (I have updated it to 9.0), since the csv report generates correctly.
Could you help me look into it? My end code follows.

/**
*

  • Export Facebook Ads Data to Google Sheets
  • Requests a Facebook report asynchronously and caches the report ID
  • Version: 2.2
  • Google Apps Script maintained by Frederic Harnois
  • [email protected]

**/

// MODIFY YOUR REPORT HERE //

// ad account ID
const AD_ACCOUNT_ID = 'xxx'

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

// https://developers.facebook.com/docs/marketing-api/insights/parameters#fields
const FIELDS = ['account_name','campaign_name','adset_name','ad_name','reach','impressions','clicks','spend','actions']

// https://developers.facebook.com/docs/marketing-api/insights/parameters#param
const DATE_RANGE = 'lifetime'

// user access token linked to a Facebook app
const TOKEN = 'xxx'

// number of days from 1 to 90
const TIME_INCREMENT = '1'

// https://developers.facebook.com/docs/marketing-api/insights/parameters#param
const FILTERING = "[{field: 'action_type',operator:'NOT_IN', value: ['offsite_conversion.fb_pixel_purchase','offsite_conversion.fb_pixel_lead','offsite_conversion.fb_pixel_view_content','add_to_cart','omni_purchase','omni_view_content','offsite_conversion.fb_pixel_add_to_cart','lead']}]"

// DO NOT MODIFY ANYTHING BELOW //

function requestFacebookReport() {

// Builds the Facebook Ads Insights API URL
const facebookUrl = https://graph.facebook.com/v9.0/act_${AD_ACCOUNT_ID}/insights?level=${LEVEL}&fields=${FIELDS}&date_preset=${DATE_RANGE}&access_token=${TOKEN}&time_increment=${TIME_INCREMENT}&filtering=${FILTERING}&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());

// Caches the report run ID
const reportId = results.report_run_id;
const cache = CacheService.getScriptCache();
const cached = cache.get('campaign-report-id');

if (cached != null) {
cache.put('campaign-report-id', [], 1);
Utilities.sleep(1001);
cache.put('campaign-report-id', reportId, 21600);
} else {
cache.put('campaign-report-id', reportId, 21600);
};

Logger.log(cache.get('campaign-report-id'));
}
/**
*

  • Export Facebook Ads Data to Google Sheets
  • Pushes the Facebook asynchronous report to Google Sheets
  • Version: 2.2
  • Google Apps Script maintained by Frederic Harnois
  • [email protected]

**/

// MODIFY YOUR SETTINGS HERE //

// url of the google sheets where the report will be
const SPREADSHEET_URL = 'xxx'

// name of the sheet where the report will be
const TAB_NAME = 'data'

// DO NOT MODIFY ANYTHING BELOW //

function getFacebookReport() {

// Selects the chosen sheet and tab
const ss = SpreadsheetApp.openByUrl(SPREADSHEET_URL);
const sheet = ss.getSheetByName(TAB_NAME);

// Clears the sheet
sheet.clear();

// Gets the Facebook report run ID
const cache = CacheService.getScriptCache();
const reportId = cache.get('campaign-report-id');

// Fetches the report as a csv file
const url = https://www.facebook.com/ads/ads_insights/export_report?report_run_id=${reportId}&format=csv&access_token=${TOKEN};
const fetchRequest = UrlFetchApp.fetch(url);
const results = Utilities.parseCsv(fetchRequest);

// Pastes the csv file in the sheet
sheet.getRange(1,1, results.length, results[0].length).setValues(results);
}

Thanks,
Anton

Can't add Results column

Hi Fred,
Thanks for this script, it helps save a lot of time.
It works perfectly fine for me except I can't add the 'Results' column from my Facebook Ads Data.

const FIELDS = 'campaign_name,adset_name,ad_name,clicks,impressions,frequency,cpm,actions,cost_per_action_type,conversions'

const FILTERING = "[{'field':'action_type','operator':'IN','value':['cost_per_action_type','offsite_conversion.custom.Results','ad_name','cpm','clicks','impressions','adset_name','campaign_name','frequency']}]"
The ID for the column I want is 'Results' in the Facebook Ads data.
Could you please help solve this problem.

Originally posted by @Angad-Boparai in #9 (comment)

Day/Date column

Hi Fred, I must say that this is a great script and really easy to implement.

I was setting this up and I thing that it would be interesting to bring a date column so I can use the data to plot a few charts and see how the data flows between dates.

I can't seem to find a way to do it but I'm a noob, so, any help is welcome!

Thanks in advance.

outdated API version

The script is calling V3.2 API. Replace all v3.2 instances to V3.3 works fine.

I am faced this issue while execute the code

This is the error I am facing when I execute requestFacebookReport function.

Exception: Request failed for https://graph.facebook.com returned code 400. Truncated server response: {"error":{"message":"(#100) conversations is not valid for fields param. please check https://developers.facebook.com/docs/marketing-api/refer... (use muteHttpExceptions option to examine full response)

Please let me know how can I fix it?

Export Conversion

Hi Frederic!

First of all thank you so much for your amazing script!
It is running great after I changed to API v6.0.

I have the following question:

Can you advise how to export conversions?
For example the conversion view content, added to cart or custom conversions.

As far as I understood, conversions can be defined through ads action stats:
https://developers.facebook.com/docs/marketing-api/reference/ads-action-stats/

Another possibly easy solution would be to export a predefined report.
The report can be created in the ads manager with clicks and drag and drop and then saved.
Only the report ID is needed to export it:
#https://developers.facebook.com/docs/marketing-api/insights/best-practices/#export-reports

Is there a way to use your script to do this?

Thank you so much in advance!

Organizing report results

Frederic,
Thanks for the scripts.

How can I sort by Campaign name? (I am able to sort by reach is it only numbers that can be sort?)
I see the following explanation but looks like I am missing something when trying it.

sort
list
Default value: Array
Field to sort the result, and direction of sorting. You can specify sorting direction by appending "_ascending" or "_descending" to the sort field. For example, "reach_descending". For actions, you can sort by action type in form of "actions:<action_type>". For example, ["actions:link_click_ascending"]. This array supports no more than one element. By default, the sorting direction is ascending.

Once again many thanks...

Request failed for https://www.facebook.com/ads/ads_insights/export_report?

Hello!

Apologies as I am relatively new to this but I am getting the following error:

Request failed for https://www.facebook.com/ads/ads_insights/export_report?

I also have the two scripts all in one project, is that correct? What is the best way to have one to fire after the other?

My script is below but i have removed the token for security:

/**
*

  • Export Facebook Ads Data to Google Sheets
  • Requests a Facebook report asynchronously and caches the report ID
  • Version: 2.1
  • Google Apps Script maintained by Frederic Harnois

**/

// MODIFY YOUR REPORT HERE //

// ad account ID
var AD_ACCOUNT_ID = 'xxx'

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

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

// https://developers.facebook.com/docs/marketing-api/insights/parameters#param
var DATE_RANGE = 'last_90d'

// user access token linked to a Facebook app
var TOKEN = 'xxx'

// number of days from 1 to 90
var TIME_INCREMENT = 'all_days'

// https://developers.facebook.com/docs/marketing-api/insights/parameters#param
var FILTERING = 'Array'

// DO NOT MODIFY ANYTHING BELOW //

function requestFacebookReport() {

// Builds the Facebook Ads Insights API URL
var facebookUrl =
'https://graph.facebook.com/v3.3' +
'/act_' + AD_ACCOUNT_ID +
'/insights?level=' + LEVEL +
'&fields=' + FIELDS +
'&date_preset=' + DATE_RANGE +
'&access_token=' + TOKEN +
'&time_increment=' + TIME_INCREMENT +
'&filtering=' + FILTERING +
'&limit=1000';
var encodedFacebookUrl = encodeURI(facebookUrl);
var options = {
'method' : 'post'
};

// Fetches & parses the URL
var fetchRequest = UrlFetchApp.fetch(encodedFacebookUrl, options);
var results = JSON.parse(fetchRequest.getContentText());

// Caches the report run ID
var reportId = results.report_run_id;
var cache = CacheService.getScriptCache();
var cached = cache.get("campaign-report-id");

if (cached != null) {
cache.put("campaign-report-id", [], 1);
Utilities.sleep(1001);
cache.put("campaign-report-id", reportId, 21600);
}
else {
cache.put("campaign-report-id", reportId, 21600);
}
Logger.log(cache.get('campaign-report-id'));
}/**
*

  • Export Facebook Ads Data to Google Sheets
  • Pushes the Facebook asynchronous report to Google Sheets
  • Version: 2.1
  • Google Apps Script maintained by Frederic Harnois

**/

// MODIFY YOUR SETTINGS HERE //

// url of the google sheets where the report will be
var SPREADSHEET_URL = 'xxx'

// name of the sheet where the report will be
var TAB_NAME = 'report'

// user access token linked to a Facebook app
var TOKEN = xxx

// DO NOT MODIFY ANYTHING BELOW //

function getfacebookReport() {

// Selects the chosen sheet and tab
var ss = SpreadsheetApp.openByUrl(SPREADSHEET_URL);
var sheet = ss.getSheetByName(TAB_NAME);

// Clears the sheet
sheet.clear();

// Gets the Facebook report run ID
var cache = CacheService.getScriptCache();
var reportId = cache.get('campaign-report-id')

// Fetches the report as a csv file
var url =
'https://www.facebook.com/ads/ads_insights/export_report' +
'?report_run_id=' + reportId +
'&format=csv' +
'&access_token=' + TOKEN;
var fetchRequest = UrlFetchApp.fetch(url);
var results = Utilities.parseCsv(fetchRequest);

// Pastes the csv file in the sheet
sheet.getRange(1,1, results.length, results[0].length).setValues(results);
}

Could parse text

Hi,

I have faced with the issue very consistently.

When I run the script, I can see from the execution log that I can get URL from the insights API, so I tried to paste it in a browser tab, expected behavior is for it to download a CSV.
For some reason, in some cases, it doesn't do that directly but instead requires a login to Facebook
When I paste the URL in a browser tab 30 mins later, it still requires a login; ; for most URLs, we can download the CSV directly, even after a set period of time

I am not sure if what causing the script to fail is the requirement to log in, or some delay that's needed, or some error in the API, or frequency of running the API, or anything else?

Please see this screenshot to see how's the error looks like: https://prnt.sc/12tqpsf

Thank you very much,
Ruby

Super helpful script. Thank you.

Than you so much for this script. So helpful.

However, can I ask why the below only pulls in 50% of the fields. Also, I cannot get things like leads, landing page views, cost per landing page view, conversions, cost_per_conversion or any custom metrics that exist in my account. Also, do all custom conversions need an ID? Thank you for your continuing guidance.

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

// https://developers.facebook.com/docs/marketing-api/insights/parameters#fields
const FIELDS = 'frequency,spend,conversions,cost_per_conversion,cpm,impressions,full_view_impressions,cpp,reach,full_view_reach,unique_outbound_clicks,unique_outbound_clicks_ctr,cost_per_unique_outbound_click,website_ctr,ctr,cost_per_action_type'
// https://developers.facebook.com/docs/marketing-api/insights/parameters#param
const DATE_RANGE = 'lifetime'

// user access token linked to a Facebook app
const TOKEN = 'EA'

// number of days from 1 to 90
const TIME_INCREMENT = '1'

// https://developers.facebook.com/docs/marketing-api/insights/parameters#param
const FILTERING = "[{'field':'action_type','operator':'IN','value':['offsite_conversion.fb_pixel_lead','offsite_conversion.fb_pixel_view_content','outbound_click','link_click']}]"

Just a question about caching and campaign report id

First, thanks a lot for your code! I've begun modifying it a bit and using it for work. It's been a great learning experience to try and understand how each line works. Had a couple questions:

  • What is the difference between report_run_id and campaign_report_id? Fetching the .csv using the report_run_id seems to work fine.
  • What is the purpose of caching the campaign_report_id? My guess is to be able to utilize it in the other file get-facebook-report.js?

Relevant code from request-facebook-report.js

  const reportId = results.report_run_id;
  const cache = CacheService.getScriptCache();
  const cached = cache.get('campaign-report-id');

Thank you!

Is there a way to have a daily breakdown?

hi! thank you for this awesome script, but I'm having issues recreating a "simple" report: what I want to do is get four columns, Day, Campaign Name, Click, Amount Spent.

Day and Campaign Name would be the "breakdowns" and Click and Amount Spent the "fields" or "metrics".

But I don't see anything in the documentation to add simple Day and Campaign Name breakdowns. Am I missing something?

Code 500 Error

I am using this code for some of my accounts but I am having this problem. Not in all ...

Exception: Request failed for https://www.facebook.com returned code 500. Truncated server response: <title>Error</title><meta http-equiv="Cache-Control" content="no-cache" ... (use muteHttpExceptions option to examine full response)
getFacebookReport @ Code.gs:67

Does someone knows whats happening ?

Error at line 39

Hi Frederic,

Thanks for a great bit of code.

Unfortunately, I am getting an error at line 39:

const fetchRequest = UrlFetchApp.fetch(url);

in the Export Facebook Ads Data to Google Sheets file.

It worked perfectly until 10 days ago, and then it just stopped. I did not change anything in the set-up or with my account info. I can download the FB data in a CSV with no problems, but the data will not export into the Sheet.

Do you have any ideas what the issue might be?

Thanks

Zak

Could not parse text - get-facebook-report.js.gs:40

FYI: I've been getting this error today (on some, but not all projects) in get-facebook-report.js:

Exception: Could not parse text.
getFacebookReport @ get-facebook-report.js.gs:40

The error is a strange one. For 3 projects I pasted over the script from another that is working with no problems. For the 3, 1 started to work, and 2 did not. I have no idea why.

BTW, you may wish to update line 41 in request-facebook-report.js to version 9.0. This will work until 2023, after that it will fail as the current code does not work with v10 of the graph api

OAuth problems

Hi Frederich,
I am new to google scripts and want to use this script for my work. I keep getting the same problem which is, "Request failed for https://graph.facebook.com returned code 400. Truncated server response: {"error":{"message":"Invalid OAuth access token.","type":"OAuthException","code":190,"fbtrace_id":" for the request-facebook-report. Does this error mean that there is something wrong with my token? I have tried resetting the token a few times and made sure I had all the right information. Can you please help me? Thanks.

// ad account ID
var AD_ACCOUNT_ID = 'xxxx'

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

// https://developers.facebook.com/docs/marketing-api/insights/parameters#fields
const FIELDS = 'adset_name,ad_name,clicks,impressions,spend,converted_product_quantity,website_purchase_roas'

// https://developers.facebook.com/docs/marketing-api/insights/parameters#param
const DATE_RANGE = 'last_30d'

// user access token linked to a Facebook app
const TOKEN = 'EAAGJILbuh.....'

// number of days from 1 to 90
const TIME_INCREMENT = 'all_days'

// https://developers.facebook.com/docs/marketing-api/insights/parameters#param
const FILTERING = "[{'field':'action_type','operator':'IN','value':['link_click']}]"

// DO NOT MODIFY ANYTHING BELOW //

function requestFacebookReport() {

// Builds the Facebook Ads Insights API URL
const facebookUrl = 'https://graph.facebook.com/v7.0/act_${AD_ACCOUNT_ID}/insights?level=${LEVEL}&fields=${FIELDS}&date_preset=${DATE_RANGE}&access_token=${TOKEN}&time_increment=${TIME_INCREMENT}&filtering=${FILTERING}&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());

// Caches the report run ID
const reportId = results.report_run_id;
const cache = CacheService.getScriptCache();
const cached = cache.get('campaign-report-id');

if (cached != null) {
cache.put('campaign-report-id', [], 1);
Utilities.sleep(1001);
cache.put('campaign-report-id', reportId, 21600);
} else {
cache.put('campaign-report-id', reportId, 21600);
};

Logger.log(cache.get('campaign-report-id'));
}


// url of the google sheets where the report will be
const SPREADSHEET_URL = 'https://docs.google.com/spreadsheets/d/....'

// name of the sheet where the report will be
const TAB_NAME = 'Stats'

// DO NOT MODIFY ANYTHING BELOW //

function getFacebookReport() {

// Selects the chosen sheet and tab
const ss = SpreadsheetApp.openByUrl(SPREADSHEET_URL);
const sheet = ss.getSheetByName(TAB_NAME);

// Clears the sheet
sheet.clear();

// Gets the Facebook report run ID
const cache = CacheService.getScriptCache();
const reportId = cache.get('campaign-report-id');

// Fetches the report as a csv file
const url = https://www.facebook.com/ads/ads_insights/export_report?report_run_id=${reportId}&format=csv&access_token=${TOKEN};
const fetchRequest = UrlFetchApp.fetch(url);
const results = Utilities.parseCsv(fetchRequest);

// Pastes the csv file in the sheet
sheet.getRange(1,1, results.length, results[0].length).setValues(results);
}

Trying to append a Row instead of updating the existing one

Hello guys, I was trying with some code tweaks to append a row instead of updating the existing one, but I can't figure out how. Is there anyone who can help me?

Really appreciated.

This is the code:

/**
*

  • Export Facebook Ads Data to Google Sheets
  • Pushes the Facebook asynchronous report to Google Sheets
  • Version: 2.2
  • Google Apps Script maintained by Frederic Harnois
  • [email protected]

**/

// MODIFY YOUR SETTINGS HERE //

// url of the google sheets where the report will be
const SPREADSHEET_URL = 'https://docs.google.com/spreadsheets/d/1tUZodzO9FK6uQyz8pDqAeKIAvIsmiHQ5yRYkqObJDWM/'

// name of the sheet where the report will be
const TAB_NAME = 'Report'

// DO NOT MODIFY ANYTHING BELOW //

function getFacebookReport() {

// Selects the chosen sheet and tab
const ss = SpreadsheetApp.openByUrl(SPREADSHEET_URL);
const sheet = ss.getSheetByName(TAB_NAME);

// Clears the sheet
sheet.clear();

// Gets the Facebook report run ID
const cache = CacheService.getScriptCache();
const reportId = cache.get('campaign-report-id');

// Fetches the report as a csv file
const url = https://www.facebook.com/ads/ads_insights/export_report?report_run_id=${reportId}&format=csv&access_token=${TOKEN};
const fetchRequest = UrlFetchApp.fetch(url);
const results = Utilities.parseCsv(fetchRequest);

// Pastes the csv file in the sheet
sheet.getRange(1,1, results.length, results[0].length).setValues(results);

}

PS: This tool is magic!

Unable to import all columns data

Hi Frederic!

Thank you so much for the this easy to use script. I am facing an odd error with the data export - it is only exporting Impressions and Spends data though I have selected Outbound click, App Installs as well.

Screenshot 2020-06-08 at 5 40 17 PM

Also, any way to pre-define the language of the headers? It is auto inputting a regional language which I would want to change.

Field actions empty

Hey Frederich,

First of all thank you for the code.

I set up a trigger to download data every day. But now im having a problem with the field actions & action_values. It returns empty data, it dont happen with other metrics.

Do you now what could happen ? From one day to another

Is the code being affect by iOS 14.5 ?

"Facebook will no longer be able to aggregate non-inline conversion metric values across iOS 14.5 and non-iOS 14.5 campaigns due to differences in attribution logic. Querying across iOS 14.5 and non-iOS 14.5 campaigns will result in no data getting returned for non-inline conversion metrics such as app installs and purchases. Inline event metrics like impressions, link clicks, and video views, however, can still be aggregated. Please visit our changelog for more information."_

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.