Skip to content

Instantly share code, notes, and snippets.

@unrelentingfox
Created June 23, 2021 06:37
Show Gist options
  • Select an option

  • Save unrelentingfox/ac2e5742d981a189f3138978f1a2a5af to your computer and use it in GitHub Desktop.

Select an option

Save unrelentingfox/ac2e5742d981a189f3138978f1a2a5af to your computer and use it in GitHub Desktop.

Revisions

  1. unrelentingfox created this gist Jun 23, 2021.
    43 changes: 43 additions & 0 deletions facebook-ad-insights.gs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,43 @@
    // https://www.benlcollins.com/apps-script/api-tutorial-for-beginners/
    function main() {
    let accessToken = "YOUR_ACCESS_TOKEN"
    let fields = "account_id,account_name,date_start,date_stop,impressions,spend"
    let accountIds = getAccountIds(accessToken)
    let jsonData = getAdInsights(accountIds, fields, accessToken)
    let sheet = SpreadsheetApp.getActiveSheet()
    let dataKeys = Object.keys(jsonData[0])
    let dataArray = convertToArray(dataKeys, jsonData)
    dataArray.unshift(dataKeys)
    let range = sheet.getRange(1,1, dataArray.length, dataKeys.length)
    range.setValues(dataArray)
    }

    function convertToArray(dataKeys, jsonData) {
    Logger.log(dataKeys)
    return jsonData.map(entry => {
    Logger.log(entry)
    return dataKeys.map(key => entry[key])
    })
    }

    function fbRequestJsonData(url) {
    var response = UrlFetchApp.fetch(url)
    if (response.getResponseCode() != 200) {
    throw `ERROR: Failed to make request ${url}, response code:` + response.getResponseCode()
    }
    return JSON.parse(response.getContentText()).data
    }

    // https://developers.facebook.com/docs/marketing-api/connectionobjects/v11.0
    function getAccountIds(accessToken) {
    return fbRequestJsonData(`https://graph.facebook.com/v11.0/me/adaccounts?access_token=${accessToken}`).map(account =>{
    return account.id
    })
    }

    // https://developers.facebook.com/docs/marketing-api/insights/
    function getAdInsights(accountIds, fields, accessToken) {
    return accountIds.flatMap(id => {
    return fbRequestJsonData(`https://graph.facebook.com/v11.0/${id}/insights?access_token=${accessToken}&fields=${fields}`)
    })
    }