Giter Site home page Giter Site logo

daroczig / fbrads Goto Github PK

View Code? Open in Web Editor NEW
150.0 30.0 57.0 423 KB

Analyze and manage Facebook ads from R using this client library to access their Marketing APIs

License: GNU Affero General Public License v3.0

R 100.00%
r facebook facebook-marketing-api facebook-ads facebook-api marketing adtech

fbrads's Introduction

fbRads

Caution

fbRads was started in 2015, even before the Facebook Marketing API was generally available, and has been actively maintained and used since then at many companies as the only third-party SDK (as per the Facebook Business SDK dev portal) -- up to my knowledge, serving dozens of Business Managers, hundreds of Ad Accounts, and managing ads spending over $100M over the past years.

After changing roles in 2022, I did not use Facebook Ads Manager for a few years, and assisted others maintaining the package with minor version updates. In early 2024, when trying to create a new Business Manager for an open-source community, I've learned that my account was restricted back in Aug 2023 and I cannot create/edit BMs and Ad Accounts anymore -- without further explanation. After being in touch with Meta Support for a month and many-many pointless emails, I was informed that the decision is final and I cannot do anything about it.

As per above, it's time for me to officially step down as the maintainer of the package, and move on, as I cannot even test the package functions anymore. So thus I am archiving the repo. If you want to take over maintenance, please fork the repo, and get in touch if I can help with the transition process.

This R package includes wrapper functions around the Facebook Marketing API to create, read, update and delete custom audiences, images, campaigns, adsets, ads and related content.

For more details, see the slides presented at useR! 2015, the Los Angeles R Users Group and at a Domino Webinar.

Creating a Facebook App & connect with OAuth token

To be able to use this package, you will have to create a Facebook App and authorize it to manage your Facebook ads. Basic steps to create an app with Development access level letting you manage up to 5 Facebook ad accounts:

  1. Click on "Add a New App" at https://developers.facebook.com/apps

  2. Fill in a unique Display Name (eg "app_testing_foobar_42"), and provide your e-mail address. Click on "Create App ID" & pass the captcha test.

  3. Select the "Implement Marketing API" scenario that will automatically add the "Marketing API" to the "Products" section of the sidebar, or click on the "+" butting in the "Products" section of the sidebar

  4. Optionally associate your app with a Business Manager in the "Settings" screen of the "Marketing API"

  5. In the sidebar, select "Tools" from the "Marketing API" and generate a token

  6. Store your token in a secure place, and you are all set to start using fbRads, eg list all the Ad Account ids you can access:

    accounts <- fbad_get_my_ad_accounts(token)
  7. Pick an Ad Account id from the returned list and initialize fbRads to use that Ad Account by default:

    account <- sample(accounts$account_id, 1)
    fbad_init(accountid = account, token = token)
  8. Then list all your ads along with the ad name and status on that Ad Account:

    fbad_list_ad(fields = c('name', 'effective_status'))
  9. Or eg filter for the active ads:

    fbad_list_ad(statuses = 'ACTIVE', fields = 'name')

Development version

The package is actively maintained, but not frequently pushed to CRAN, so to use the most recent version, install from GitHub. The master branch is supposed to include a relatively stable version at all the time:

devtools::install_github('daroczig/fbRads')

Using the package

This package makes your life more convenient when it comes to interacting with the Facebook Marketing API, but unfortunately, it cannot save you the time to get familiar with the actual API endpoints. To be able to interact with Facebook, you have to learn about how the API works etc -- see the documentation at https://developers.facebook.com/docs/marketing-apis


This package was originally developed at CARD.com, then maintained at System1. If you are interested in taking over the maintenance of this R package, please open a GH ticket.

fbrads's People

Contributors

arbenkqiku avatar baobaofzhang avatar bjeavons avatar bra-fsn avatar daroczig 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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

fbrads's Issues

Identify all accounts for business manager

For people who manage multiple accounts, is there a way to identify all the account IDs based on a business manager ID?

I've changed the scope of access to align with version 2.7 scopes for business_management as identified here

tkn <- oauth2.0_token(
  oauth_endpoints('facebook'), app, scope = 'business_management',
  type  = 'application/x-www-form-urlencoded', cache = FALSE)

There is more documentation on how to GET all the accounts that the business manager owns on this page at the heading Viewing business manager owned ad accounts

Maybe this could be an enhancement. I'm not too sure how to go about creating this as a function

fbad_get_search: using type='adTargetingCategory' to get ID for 'behaviors'

Hello,

I'm trying to us the fbad_get_search function to get the id of certain behaviors within Facebook API. I can do this easily for type='adinterest', but I cannot figure out the appropriate syntax nor could I find any examples that illustrate how to use the fbad_get_search function when the type='adTargetingCategory'.

I've tried the following but it returns a lexical error which seems like a json parsing issue:

fb <- fbad_get_search(q='Small business owners',type = 'adTargetingCategory',class='behaviors')

It returns this error:

Error: lexical error: invalid character inside string. mail (icloud, me, mac domains) ","audience_size":3796666,"re (right here) ------^

Is this possible currently within fbRads? I can see that it's possible when reviewing the Facebook Marketing API documentation, it's just not clear how that translates to the fbRads functions.

Thanks,

Curtis

Using fb_insights to get Delivery

Hi there,

I am using the fb_insights() to get colomuns of a report, however I am not able to get the Delivery of each ad (see attached).
Since I am using a breakdown parameter, it's not accurate to use fbad_read_ads() or fbad_list_ads(). Is this possible using fb_insights()?

list <- fb_insights(date_preset ='last_7_days', time_increment='1', level = 'ad' , breakdowns ='hourly_stats_aggregated_by_advertiser_time_zone', 
                        fields = toJSON(c('date_start','date_stop', 'campaign_name', 'adset_name','ad_name','clicks','reach','spend','impressions')))
    

2017-02-15 09_20- 18 adverts manager

Question: Targeting

Hi there,

I'm still loving this package. I'm new to R, and your package is the first one I'm using and it's definitely getting me much more involved.

I'm stumped and can't figure out targeting for new ad sets.

I've viewed your presentation, and it deals with custom audiences. How does one set other targeting though?

for example:

countries = AU
age_min = 28
age_max = 50

How do I correctly put this in R so that FB API picks it up? Nothing I'm doing seems to work.

 $ name             : chr "Test"
 $ optimization_goal: chr "LINK_CLICKS"
 $ billing_event    : chr "LINK_CLICKS"
 $ bid_amount       : num 100
 $ campaign_id      : chr "6041163821559"
 $ configured_status: chr "ACTIVE"
 $ daily_budget     : num 1000
 $ targeting        :Class 'json'  chr "[[\"countries\",\"AU\"]]"
ERROR [2016-03-13 20:27:34] Header: {"WWW-Authenticate":["OAuth \"Facebook Platform\" \"invalid_request\" \"(#100) Your audience targeting is incomplete. Select at least one location,\\n        or choose a Custom Audience.\""],"Access-Control-Allow-Origin":["*"],"Content-Type":["application/json; charset=UTF-8"],"X-FB-Trace-ID":["E1j8+00q6cu"],"X-FB-Rev":["2227162"],"Pragma":["no-cache"],"Cache-Control":["no-store"],"Facebook-API-Version":["v2.5"],"Expires":["Sat, 01 Jan 2000 00:00:00 GMT"],"Vary":["Accept-Encoding"],"X-FB-Debug":["zc2f3XyTCtgUNINPNAobwh13Sll8bwdjgJK32io4WOfas/NkWzej/IX6oC1EAMvv/Ddli/YXkDeLd4CP9eawew=="],"Date":["Sun, 13 Mar 2016 09:27:34 GMT"],"Transfer-Encoding":["chunked"],"Connection":["keep-alive"],"status":["400"],"statusMessage":["Bad Request"]}
ERROR [2016-03-13 20:27:34] Body: {"error":{"message":"(#100) Your audience targeting is incomplete. Select at least one location,\n        or choose a Custom Audience.","type":"OAuthException","code":100,"fbtrace_id":"E1j8+00q6cu"}}
Error in fbad_request(fbacc, path = paste0("act_", fbacc$account_id, ifelse(fb_api_version() <  : 
  (#100) Your audience targeting is incomplete. Select at least one location,
        or choose a Custom Audience.

Thanks for the help!

Problem Initializing Facebook Account with OAuth token (fbad_init)

I receive the following error (fid is my app ID and tok is my token). I replaced all private information such as ID with 'X's.
Is this due to version incompatibility (2.5 in fbRads while API is 2.9) or am I doing some mistake?
I double checked wheter I used an appropriate ID. Thus, the error message is confusing.

> fbacc<-fbad_init(fid,tok,version="2.9")
ERROR [2017-05-10 16:50:35] URL:  https://graph.facebook.com/v2.9/act_XXXXX/
ERROR [2017-05-10 16:50:35] Method:  GET
ERROR [2017-05-10 16:50:35] Params:  List of 1
 $ fields: chr "name,account_id,account_status,age,amount_spent,balance,capabilities,end_advertiser,funding_source,spend_cap,timezone_id,users"
ERROR [2017-05-10 16:50:35] Header: {"WWW-Authenticate":["OAuth \"Facebook Platform\" \"invalid_request\" \"Invalid parameter\""],"Access-Control-Allow-Origin":["*"],"Pragma":["no-cache"],"Cache-Control":["no-store"],"x-fb-rev":["XXXXX"],"Content-Type":["application/json; charset=UTF-8"],"x-fb-trace-id":["XXXXX"],"facebook-api-version":["v2.9"],"Expires":["Sat, 01 Jan 2000 00:00:00 GMT"],"Vary":["Accept-Encoding"],"X-FB-Debug":["XXXXXX+CQ=="],"Date":["Wed, 10 May 2017 14:50:35 GMT"],"Transfer-Encoding":["chunked"],"Connection":["keep-alive"],"status":["400"],"statusMessage":["Bad Request"]}
ERROR [2017-05-10 16:50:35] Body: {"error":{"message":"Invalid parameter","type":"OAuthException","code":100,"error_subcode":1487168,"is_transient":false,"error_user_title":"The account is invalid","error_user_msg":"The account is invalid","fbtrace_id":"XXXXX"}}

Error in fbad_request(path = paste0("act_", accountid, "/"), method = "GET",  : 
  Invalid parameter

I hope somebody can help me track down my problem.

Thank you.

Improvement: Facebook Pixel data collection

Hi,

I would like to suggest an improvement:

The ability to fetch data from fb_insights collected by the Facebook and Conversion Pixel.
This tool is amazing for report building also and without this feature it lacks some potential.

What do you think?

BR
Albert

Unknown error in fb_insights()

Ran the fb_insights() function without arguments and got this error:

> fb_insights()
 ERROR [2016-01-28 12:03:09] This is a temporary  FB error.
 INFO [2016-01-28 12:03:11] Retrying query for the 1  st/nd/rd time
 ERROR [2016-01-28 12:03:42] This is a temporary  FB error.
 INFO [2016-01-28 12:03:44] Retrying query for the 2  st/nd/rd time
 ERROR [2016-01-28 12:04:15] This is a temporary  FB error.
 INFO [2016-01-28 12:04:17] Retrying query for the 3  st/nd/rd time
 ERROR [2016-01-28 12:04:49] This is a temporary  FB error.
 Error in fb_insights() : An unknown error occurred

The account I got the token from works with API v.2.4. Might that be the problem?

UPDATE

The error was on my end. Closing this.

Error in Fbad_request

Hello,

I run a R studio script on a daily basis and as of yesterday I encountered an error while running the script. This is what I get:

Error in fbad_request(path = paste0("act_", accountid, "/"), method = "GET", :
This is a bug in the fbRads package. Please report on GitHub with a detailed output: SSL certificate problem: self signed certificate in certificate chain

Any ideas of what the issue might be?

Thanks in advance

Issues with fbad_create_creative

HI,
I just started using this package I and I really like it. I am having some issue with trying to associate page id with ad creative. The follow command does not work when I include object_id

creative <- fbad_create_creative(
name = "Career Networking. Solved.",
body = paste0('Professional networking made easy. User Xpertly to get inros to peeps you in your field'),
title = 'Career networking. Solved',
object_url = url,
image_hash = img,
object_id = list(1595692097387723)
)

Tried it as character and interger but did not work.

Error Thrown:
Error in fbad_request(fbacc, path = paste0("act_", fbacc$account_id, "/adcreatives"), :
This is a bug in the fbRads package. Please report on GitHub with a detailed output: STRING_ELT() can only be applied to a 'character vector', not a 'list'

tkn gives null variable

Hello

Does anybody else have an issue with this code line:
tkn <- tkn$credentials$access_token producing "null" instead of token because access_token variable has become part of the name of the list?
This is what I mean below


 tkn$credentials$access_token
NULL
> names(tkn$credentials)
[1] "{\"access_token\":\"SOME TOKEN",\"token_type\":\"bearer\"}"
> fromJSON(names(tkn$credentials))
$access_token
[1] "SOME TOKEN"

$token_type
[1] "bearer"

> new_tkn <- fromJSON(names(tkn$credentials))
> new_tkn$access_token
[1] "SOME TOKEN"

So, the only way to access the token is access the name of the list and convert it to a JSON format after which you can access the access_token
I've used fbRads code with the tkn$credentials$access_token part last year and it worked fine; however, this year the same line was not working for me. I looked over github intro page and the original code does not seem to have changed, so just curious whether this is an issue just with my computer.

Still Getting Bad Request (HTTP 400). Failed to get an access token Despite 2.6 Update

Hi,
I am using the following code which is the updated code for 2.6V..

app <-  oauth_app('facebook', 'XXXX', 'XXXXX')

Sys.setenv('HTTR_SERVER_PORT' = '1410/')
tkn <- oauth2.0_token(oauth_endpoints('facebook'), app, scope = 'ads_management',
    type  = 'application/x-www-form-urlencoded', cache = FALSE)

tkn <- tkn$credentials$access_token 

fbad_init(accountid = accountid, token = tkn, version = '2.6')

fbad_list_ad(fields = c('name', 'effective_status'))
fbad_list_ad(statuses = 'ACTIVE', fields = 'name')

However, I still get the same error:

Waiting for authentication in browser...
Press Esc/Ctrl + C to abort
Authentication complete.
Error in init_oauth2.0(self$endpoint, self$app, scope = self$params$scope, :
Bad Request (HTTP 400). Failed to get an access token.

Error: object 'tkn' not found

Any thoughts/ideas on why is this happening?

Thanks!

Glitch with the job_type() parameter in the fbInsights() fucntion

Taken from #7

When trying to run fbInsights(), the parameter fields= is converted to JSON, but when running the code this happens:

fbInsights(target = id, fields = toJSON(c(impressions, clicks)), job_type = "async") 

You get this error:

Error: Argument 'txt' must be a JSON string, URL or file.
Called from: base::stop(..., call. = FALSE)

If I enclose the job_type = "async" inside the toJSON() command, the function returns the correct result.

fbInsights(target = id, fields = toJSON(c(impressions, clicks), job_type = "async")) 

Authentication isssues

Hey, I've been trying to use the package to integrate some data and i'm having some trouble with auth.

When fbad_init("account", token), I get this error:

ERROR [2017-07-17 16:56:04] URL:  https://graph.facebook.com/v2.5/act_1873405082881571/
ERROR [2017-07-17 16:56:04] Method:  GET
ERROR [2017-07-17 16:56:04] Params:  List of 1
 $ fields: chr "name,account_id,account_status,age,amount_spent,balance,capabilities,end_advertiser,funding_source,spend_cap,timezone_id,users"
Error in fbad_request(path = paste0("act_", accountid, "/"), method = "GET",  : 
  This is a bug in the fbRads package. Please report on GitHub with a detailed output: SSL: CA certificate set, but certificate verification is disabled
Alรฉm disso: Warning message:
In curlSetOpt(..., .opts = .opts, curl = h, .encoding = .encoding) :
  Error setting the option for # 2 (status = 4) (enum = 10097) (value = 0x101aec890): A requested feature, protocol or option was not found built-in in this libcurl due to a build-time decision. <not set>

Can somebody help me to authenticate?

Remove line breaks from JSON returned by FB

Using fbad_read_creative yesterday I have got an error:
"Error: lexical error: invalid character inside string"
http://prntscr.com/eepyap

Our marketologs added several links in creative and after this we couldnt ger data using this function
As we can see here is used fromJSON.
Maibe we can set some configs for example to skip problems chars or set codding (utf-8)?

Deprecated version of Ads API

First of all thanks for fbRads. I am a newb when it comes to API's btw.

This is the code I'm using so far:
library(httr)
app <- oauth_app('facebook', '', '')
tkn <- oauth2.0_token(
oauth_endpoints('facebook'), app, scope = 'business_management',
type = 'application/x-www-form-urlencoded', cache = FALSE)
tkn <- tkn$credentials$access_token
save(tkn, file = "Token.RData")
library(fbRads)
fbad_init(****, tkn)

I got this error
Error in fbad_request(path = paste0("act_", accountid, "/"), method = "GET", :
(#2635) You are calling a deprecated version of the Ads API. Please update to the latest version: v2.8.

My app is up to date. How can I access the v2.8 version of the Ads API?

Thanks.

fbad_init: cannot coerce type 'environment' to vector of type 'character'

Went through the examples in the useR! slides, and got stuck when trying to initialize the Marketing API:

note: fid is specified and removed from the error message

fbacc <- fbad_init(fid, tkn)
ERROR [2015-12-23 11:56:17] URL:  https://graph.facebook.com/v2.4/act_XXXXXXXX/
  ERROR [2015-12-23 11:56:17] Method:  GET
ERROR [2015-12-23 11:56:17] Params:  List of 1
$ fields: chr        "name,account_id,account_status,age,amount_spent,balance,capabilities,end_advertiser,funding_source,spend_cap,timezone_id,users"
Error in fbad_request(path = paste0("act_", accountid, "/"), method = "GET",  : 
                        This is a bug in the fbRads package. Please report on GitHub with a detailed output:     cannot coerce type 'environment' to vector of type 'character'

fbad_init(fid, tkn): SSL: CA certificate set, but certificate verification is disabled

Hello,

I am getting this issue when running fbad_init(fid, tkn):

ERROR [2016-01-27 19:34:38] URL: https://graph.facebook.com/v2.4/act_xxx/
ERROR [2016-01-27 19:34:38] Method: GET
ERROR [2016-01-27 19:34:38] Params: List of 1
$ fields: chr "name,account_id,account_status,age,amount_spent,balance,capabilities,end_advertiser,funding_source,spend_cap,timezone_id,users"
Error in fbad_request(path = paste0("act_", accountid, "/"), method = "GET", :
This is a bug in the fbRads package. Please report on GitHub with a detailed output: SSL: CA certificate set, but certificate verification is disabled
Ademรกs: Warning message:
In curlSetOpt(..., .opts = .opts, curl = h, .encoding = .encoding) :
Error setting the option for # 2 (status = 4) (enum = 10097) (value = 0x11757ae30): A requested feature, protocol or option was not found built-in in this libcurl due to a build-time decision. SSL: CA certificate set, but certificate verification is disabled

Improvement: use getInsights() for longer periods of time

When I use getInsights(), there is a limit to the ammount of data I can pull from Marketing API, so I have to look at the date of the last output and start from that. Maybe, there should be an function parameter that allows you to make Marketing API further petitions in order to get the whole dataset you're looking to analyze.

invalid character inside string

> #l <- fbad_list_ad(fields = c('id','ad_review_feedback','adlabels', 'adset','adset_id','campaign', 'campaign_id', 'configured_status', 'conversion_s .... [TRUNCATED]

I get an error;

Error: lexical error: invalid character inside string.
           \"We <3 Choker-necks! Do you? Shop the hottest...\"","updat
                     (right here) ------^

I am trying to import my list of campaigns and above string is a campaign name.

Why do I get this error? Which character is the problem here?
The entire string is like this:

Ad Set: Post: "We <3 Choker-necks! Do you? Shop the hottest..."

Not able to get insight data for more than 7 days

I am using fb_insight() to get data at campaign level for last 30 days/lifetime, but its giving me below error.

ERROR [2016-05-23 17:10:25] This is a temporary "" FB error.
INFO [2016-05-23 17:10:28] Retrying query for the 1 st/nd/rd time

But when i run for last 7 days, it doesnt show any error and fetch data easily.
Below is my query -
fb_insights(fbacc, time_increment = 1 ,date_preset = 'last_7_days', level = 'campaign')

Can somebody tell even if it is possible with fbRads to get data for more number of days or not? If yes, help me understand if i am doing something wrong here.

Another issue i am facing is with the use of time_range function in fb_insight(). I know, it needs a different thread as this is different question but i am not able to set 'since' and 'until' values in time_range/time_ranges.

fbad_init trouble

R version: 3.3.3
Windows 10
Rstudio Desktop version

Error in fbad_request(path = paste0("act_", accountid, "/"), method = "GET", : This is a bug in the fbRads package. Please report on GitHub with a detailed output: cannot coerce type 'environment' to vector of type 'character'

Below is the code which generated the error.

library(httr)
library(fbRads)

app <- oauth_app('facebook', '123', '123abc')
tkn <- oauth2.0_token(
oauth_endpoints('facebook'), app, scope = 'business_management',
type = 'application/x-www-form-urlencoded', cache = FALSE)

saveRDS(tkn, "fb-oauth.rds")

fb_tkn <- readRDS("fb-oauth.rds")

fbad_init(accountid = "567", token = fb_tkn, version = "2.8")

Any help would be great. Thanks.

bug in fbrads package

ERROR [2017-02-06 04:04:12] URL:  https://graph.facebook.com/v2.7/act_784298674999592/
ERROR [2017-02-06 04:04:12] Method:  GET
ERROR [2017-02-06 04:04:12] Params:  List of 1
 $ fields: chr "name,account_id,account_status,age,amount_spent,balance,capabilities,end_advertiser,funding_source,spend_cap,timezone_id,users"
Error in fbad_request(path = paste0("act_", accountid, "/"), method = "GET",  : 
  This is a bug in the fbRads package. Please report on GitHub with a detailed output: Failed to connect to graph.facebook.com port 443: Connection timed out
Calls: tapply ... fbad_init -> fbad_get_adaccount_details -> fbad_request

I get this error. My requests have continuously been failing with a cron though works when executed manually. It has worked fine before for a very long time

SSL certificate problem: unable to get local issuer certificate

Hi,

Trying to run fbad_init() for the first time and I get the following error message that I'm trying to understand.

Error in fbad_request(path = paste0("act_", accountid, "/"), method = "GET",  :  This is a bug in the fbRads package. 
Please report on GitHub: SSL certificate problem: unable to get local issuer certificate

Steps I followed:

  • Created the Facebook App
  • Added the Ads account ID to the list of Authorized Ad Account IDs of the app
  • Authenticated via R and got an access token -- requested access scope ads_read

I noticed the version of the API the package attempts to hit is 2.3 (current is v2.4). This is hard-coded in fb_init.R. However, if I hit v2.3 of the API via url it says it's deprecated.

https://graph.facebook.com/v2.3/act_{my_id}/insights?level=account&access_token={my_token}

{
   "error": {
      "message": "(#2635) You are calling a deprecated version of the Ads API. Please update to the latest version.",
      "type": "OAuthException",
      "code": 2635
   }
}

But if I hit v2.4 I get a response with results. Same act_id, same access_token.

Could my original error be just a versioning issue?

Thanks!

> version

platform       x86_64-w64-mingw32          
arch           x86_64                      
os             mingw32                     
system         x86_64, mingw32             
status                                     
major          3                           
minor          1.2                         
year           2014                        
month          10                          
day            31                          
svn rev        66913                       
language       R                           
version.string R version 3.1.2 (2014-10-31)
nickname       Pumpkin Helmet 

Bad Request (HTTP 400). Failed to get an access token. Still.

Hi all,

I am still having a problem with access to my token! I already tried to fix this issue as you suggest in #28 and #77 but it still does not work for me. I used this code:
library(httr)
app <- oauth_app('facebook', 'your app id', 'your app secret')
Sys.setenv('HTTR_SERVER_PORT' = '1410/')
tkn <- oauth2.0_token(
oauth_endpoints('facebook'), app, scope = 'ads_management',
type = 'application/x-www-form-urlencoded', cache = FALSE)
tkn <- tkn$credentials$access_token

I've also tried to leave off the line Sys.setenv('HTTR_SERVER_PORT' = '1410/').
I also checked my OAuth Redirect URIs.
Is there any other possible solution?

Here my sessioninfo()
R version 3.3.1 (2016-06-21)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 7 x64 (build 7601) Service Pack 1

locale:
[1] LC_COLLATE=German_Germany.1252 LC_CTYPE=German_Germany.1252 LC_MONETARY=German_Germany.1252
[4] LC_NUMERIC=C LC_TIME=German_Germany.1252

attached base packages:
[1] stats graphics grDevices utils datasets methods base

other attached packages:
[1] Rfacebook_0.6.11 httpuv_1.3.3 rjson_0.2.15 httr_1.2.1.9000 devtools_1.12.0 RMySQL_0.10.9
[7] DBI_0.5-1

loaded via a namespace (and not attached):
[1] R6_2.2.0 tools_3.3.1 withr_1.0.2 curl_2.3 Rcpp_0.12.6 memoise_1.0.0 git2r_0.15.0
[8] digest_0.6.10

Many thanks!

fbad_create_ad has a problem with campaign_id argument

There is a problem with campaign_id in the function fbad_create_ad. In the version available on CRAN, you had campaign_id as an argument. But in the latest GitHub version, you don't. I think it might be because it's deprecated. Anyhow, not having campaign_id as an argument is causing problems. I get an error that says:

Error in missing(campaign_id) : 'missing' can only be used for arguments

I might try to do a fix and make a pull request.

Getting remote oauth token from facebook whilE IN R studio server

What is

The redirect_uri URL is not supported

error on facebook.

I have opted for out of band authentication and thus I have to point my browser to the url:

https://www.facebook.com/dialog/oauth?client_id=611685395673327&scope=ads_management&redirect_uri=urn%3Aietf%3Awg%3Aoauth%3A2.0%3Aoob&response_type=code

in order to get my authorization code.

Where did I go wrong?

What exactly do I need to pass into redirect_uri in the facebook application?

Since I am using R studio server, it is http://localhost:1410/ when one is working locally but it wont work with remote server.

A relevant post:https://support.rstudio.com/hc/en-us/articles/217952868-Generating-OAuth-tokens-from-a-server

Problem with Access Tokens

I followed your directions on the GitHub main page but I am still having issues with getting access tokens. I'm using v2.6 of the Facebook API. See below for my code and error messages. Do you think it's a problem with the new FB API version?

> app <- oauth_app('facebook', a, b)
> Sys.setenv('HTTR_SERVER_PORT' = '1410/')
> tkn <- oauth2.0_token(
+   oauth_endpoints('facebook'), app, scope = 'ads_management',
+   type  = 'application/x-www-form-urlencoded', cache = FALSE)
Waiting for authentication in browser...
Press Esc/Ctrl + C to abort
Authentication complete.
Error in init_oauth2.0(self$endpoint, self$app, scope = self$params$scope,  : 
  Bad Request (HTTP 400). Failed to get an access token.
> tkn <- tkn$credentials$access_token
Error: object 'tkn' not found

fbad_list

Hi there,

Apologies, as I'm a new in R. I can't get any fb list item to work. eg:

fbRads::fbad_list_ad(fbacc, id, statuses = "ACTIVE", fields = "id")
ERROR [2016-03-11 00:19:19] URL: https://graph.facebook.com/v2.5/
ERROR [2016-03-11 00:19:19] Method: GET
ERROR [2016-03-11 00:19:19] Params: List of 3
$ fields : chr "id"
$ limit : num 1000
$ effective_status:Class 'json' chr "["ACTIVE"]"
ERROR [2016-03-11 00:19:19] Header: {"WWW-Authenticate":["OAuth "Facebook Platform" "invalid_request" "Unsupported get request. Please read the Graph API documentation at https://developers.facebook.com/docs/graph-api""],"Access-Control-Allow-Origin":["*"],"Content-Type":["application/json; charset=UTF-8"],"X-FB-Trace-ID":["HlKEAU9mYcx"],"X-FB-Rev":["2223643"],"Pragma":["no-cache"],"Cache-Control":["no-store"],"Facebook-API-Version":["v2.5"],"Expires":["Sat, 01 Jan 2000 00:00:00 GMT"],"Vary":["Accept-Encoding"],"X-FB-Debug":["V/TZQWM169EvKsuhl2KHgIXhWCQMiQ4Vv/XRsJUa2/twEoA6aeoEk4JcMi3uW8Q/C1C/uOu/nnGAPOR9ZLn5aQ=="],"Date":["Thu, 10 Mar 2016 13:19:18 GMT"],"Transfer-Encoding":["chunked"],"Connection":["keep-alive"],"status":["400"],"statusMessage":["Bad Request"]}
ERROR [2016-03-11 00:19:19] Body: {"error":{"message":"Unsupported get request. Please read the Graph API documentation at https://developers.facebook.com/docs/graph-api","type":"GraphMethodException","code":100,"fbtrace_id":"HlKEAU9mYcx"}}
Error in fbad_request(fbacc, path = file.path(id, endpoint), params = params, :
Unsupported get request. Please read the Graph API documentation at https://developers.facebook.com/docs/graph-api

I'm thinking this is likely to do factors on my end such as being in developer mode for my FB app and accessing from a local machine? Not sure, but thought I'd double check here. Thanks!

Error: cannot coerce type 'closure' to vector of type 'character'

Hello there!

I'm building a Shiny app in R to display interactive Facebook Ads data. I'm pretty new at both R and Shiny, so please bear with me. I'd like to be able to use a Shiny reactive value in a fbRads call (the calls work fine with static values), but every time I try I get this error message:

Error in fb_insights(fields = "reach", level = "account", time_range = date_range_input) : 
  This is a bug in the fbRads package. Please report on GitHub with a detailed output: cannot coerce type 'closure' to vector of type 'character'

Here's the code that produces the error:

ui <- fluidPage(
titlePanel("Facebook Ads Reach Test App", windowTitle = "Facebook Ads Reach Test App"),
dateRangeInput("date_range", "Date range:", start = as.character(Sys.Date()-30), end = as.character(Sys.Date()-1), min = "2016-01-01", max = Sys.Date(), weekstart = 0, separator = " to "),
actionButton("update","Update"),
textOutput(outputId = "total_reach"),
plotOutput(outputId = "reach_over_time", width = "100%", height = "400px", click = NULL, dblclick = NULL, hover = NULL, hoverDelay = NULL, hoverDelayType = NULL, brush = NULL, clickId = NULL, hoverId = NULL, inline = FALSE), 
tableOutput(outputId = "top_reach"),
textOutput("dates"),
textOutput("dateText1"),
textOutput("dateText2")
)

server <- function(input, output) ({
  date_range_input <- eventReactive(input$update, {
    toJSON(data.frame(
      since=input$date_range[1],
      until=input$date_range[2]))
    print(date_range)
    })
  output$dateText1 <- renderText(date_range_input())
  output$dateText2 <- renderText(input$date_range)

output$reach_over_time <- renderPlot({
  reach_time <- fb_insights(level='adset', fields='adset_name,reach', filtering = c('impressions', 'GREATER THAN', '0'),time_range=date_range_input)
  for (i in c(1:length(reach_by_day))) {
    active_time = rbind(active_time, reach_by_day[[i]])
  }
  plot(active_time)
})

output$total_reach <- renderText({
  total_reach <- fb_insights(fields='reach', level='account',time_range=date_range_input)
  total_reach_data <- as.data.frame(total_reach)
  sum(total_reach_data$reach)
})

})

shinyApp(ui = ui, server = server)

Thanks for your time!

refreshing the token using fbrads

I had created this issue here : #17

The suggested fix was to copy the token from localhost initially and then use it on remote server which I did. But now that my token has expired, do I ought to do it every-time it expires? That isn't really a fix. Do we have a proper fix for this?

We need it guys :) How do we do without getting authentication to work properly.

Time out error

Hi, i'm getting this estrange output in my script

This is a bug in the fbRads package. Please report on GitHub with a detailed output: Failed to connect to graph.facebook.com port 443: Timed out

Deprecated User Instructions

The instructions on the main page says:

In the "Settings/Advanced" tab, add http://localhost:1410/ as the "Valid OAuth redirect URIs". Click "Save Changes".

But the Facebook app interface seems to have changed. Now you need to get Facebook Log under Products and set it up that way.

screen shot 2016-06-17 at 12 00 05 pm

how to use fb_insights function to import data from facebook using R

I am trying to use fbRads library to import data from facebook using R.

https://cran.r-project.org/web/packages/fbRads/fbRads.pdf

I have a valid fbaccount object returned by fb_init function and then I am trying to use exactly the same example mentioned here in the docs:

l <- fb_insights(fbacc, date_preset = 'today', level = 'ad')
library(rlist)
list.stack(list.select(l, date_start, date_stop, ad_id, total_actions,
total_unique_actions, total_action_value, impressions, unique_impressions,
social_impressions, unique_social_impressions, clicks, unique_clicks,
social_clicks, unique_social_clicks, spend, frequency, deeplink_clicks,
app_store_clicks, website_clicks, reach, social_reach, ctr, unique_ctr,
cpc, cpm, cpp, cost_per_total_action, cost_per_unique_click,
relevance_score = relevance_score$score))

In variable l, I get:

>print(l)
[[1]]
list()
and then

>list.stack(list.select(l, date_start, date_stop, ad_id, total_actions,
+                        total_unique_actions, total_action_value, impression .... [TRUNCATED] 
Error in eval(expr, envir, enclos) : object 'date_start' not found

What seems to be not working here? How do I fix this?

fbRads Reporting Bug

Hello again :)

I'm getting a bug notification when creating ads:

> creative <- fbad_create_creative(
+   fbacc,
+   name = 'This is the Name Field',
+   body = 'This is the body field of the ad',
+   title = 'This is the title field of the ad',
+   object_url = url,
+   link_url =url,
+   image_hash = img,
+   
+ )
ERROR [2016-03-14 10:00:33] URL:  https://graph.facebook.com/v2.5/*****/adcreatives
ERROR [2016-03-14 10:00:33] Method:  POST
ERROR [2016-03-14 10:00:33] Params:  List of 6
 $ title     : chr "This is the title field of the ad"
 $ body      : chr "This is the body field of the ad"
 $ name      : chr "This is the Name Field"
 $ image_hash:List of 3
  ..$ filename: chr "Image-File-Name.jpg"
  ..$ hash    : chr "614d6e68f9de48eca7a479c080fb8c74"
  ..$ url     : chr "https://fbcdn-creative-a.akamaihd.net/hads-ak-xfp1/t45.1600-4/12481040_6041201327159_1348364738_n.png"
 $ link_url  :function (description, open = "", blocking = TRUE, encoding = getOption("encoding"), method)  
 $ object_url:function (description, open = "", blocking = TRUE, encoding = getOption("encoding"), method)  
Error in fbad_request(fbacc, path = paste0("act_", fbacc$account_id, "/adcreatives"),  : 
  This is a bug in the fbRads package. Please report on GitHub with a detailed output: STRING_ELT() can only be applied to a 'character vector', not a 'list'

fbad_init Error: (#3) Application does not have the capability to make this API call

Hello!
Thanks to the contributors of this package! Looking forward to getting up and running. Early on I'm experiencing an minor issue with extracting the access code from tkn, but attempted a manual workaround for that (tkncopy). Later on, when trying to initiate via fbad_init, I'm getting a length error (included below). In summary, "(#3) Application does not have the capability to make this API call".

Appreciative of all advice - Thanks!

> library(httr)
> app <- oauth_app('facebook', 'my_id', 'my_secret')
> tkn <- oauth2.0_token(
+   oauth_endpoints('facebook'), app, scope = 'business_management',
+   type  = 'application/x-www-form-urlencoded', cache = FALSE)
Waiting for authentication in browser...
Press Esc/Ctrl + C to abort
Authentication complete.
> tkn$credentials$access_token
NULL
> tkn$credentials
$`{"access_token":"my_access_token","token_type":"bearer","expires_in":5098355}`
[1] ""
> tkncopy <- "my_token" #manually extracted token from credentials list
> library(devtools)
> install_github("cardcorp/fbRads")
Skipping install of 'fbRads' from a github remote, the SHA1 (fc6cc5a7) has not changed since last install.
  Use `force = TRUE` to force installation
> acctid <- "my_ad_account_id"
> fbacc <- fbad_init(accountid = acctid, token = tkncopy)
ERROR [2017-06-01 16:53:45] URL:  https://graph.facebook.com/v2.8/act_377523705722721/
ERROR [2017-06-01 16:53:45] Method:  GET
ERROR [2017-06-01 16:53:45] Params:  List of 1
 $ fields: chr "name,account_id,account_status,age,amount_spent,balance,end_advertiser,funding_source,spend_cap,timezone_id,users"
ERROR [2017-06-01 16:53:45] Header: {"WWW-Authenticate":["OAuth \"Facebook Platform\" \"invalid_request\" \"(#3) Application does not have the capability to make this API call.\""],"Access-Control-Allow-Origin":["*"],"Pragma":["no-cache"],"Cache-Control":["no-store"],"x-fb-rev":["3057537"],"Content-Type":["application/json; charset=UTF-8"],"x-fb-trace-id":["CKY+xp03Lm4"],"facebook-api-version":["v2.9"],"Expires":["Sat, 01 Jan 2000 00:00:00 GMT"],"X-FB-Debug":["RDKfEF5KzJzM1RDQUFIlU7+1hF+d2qRx0x7Hvww01BBMkoX4c8iruxRLN/zSvd4rT8QarSK2MvQ+pavDni9+Jw=="],"Date":["Thu, 01 Jun 2017 23:53:45 GMT"],"Connection":["keep-alive"],"Content-Length":["152"],"status":["400"],"statusMessage":["Bad Request"]}
ERROR [2017-06-01 16:53:45] Body: {"error":{"message":"(#3) Application does not have the capability to make this API call.","type":"OAuthException","code":3,"fbtrace_id":"CKY+xp03Lm4"}}
Error in fbad_request(path = paste0("act_", accountid, "/"), method = "GET",  : 
  (#3) Application does not have the capability to make this API call.

Error in fbad_request: cannot coerce type 'environment' to vector of type 'character'

I'm getting the following error, which let me know to report on GitHub below. I've tried the same command with v2.9 with the same result, do you have any suggestions here? Thanks!

> fbacc <- fbad_init(accountid = ###,
...                            token = tkn,
...                            version = '2.8')
ERROR [2017-05-09 08:24:55] URL:  https://graph.facebook.com/v2.8/act_###/
ERROR [2017-05-09 08:24:55] Method:  GET
ERROR [2017-05-09 08:24:55] Params:  List of 1
 $ fields: chr "name,account_id,account_status,age,amount_spent,balance,end_advertiser,funding_source,spend_cap,timezone_id,users"
Error in fbad_request(path = paste0("act_", accountid, "/"), method = "GET",  : 
  This is a bug in the fbRads package. Please report on GitHub with a detailed output: cannot coerce type 'environment' to vector of type 'character' 

error while using through Azure R notebook

I would to use the package in a Microsoft Azure R Notebook, however after

mystats<-fb_insights(date_preset='last_7_days', level='campaign',
                     fields= toJSON(c('campaign_name', 'reach','impressions','clicks','spend')), time_increment=1)

it returns...

ERROR [2017-04-20 13:21:22] URL:  https://graph.facebook.com/v2.8/act_554605768056065/
ERROR [2017-04-20 13:21:22] Method:  GET
ERROR [2017-04-20 13:21:22] Params:  List of 1
 $ fields: chr "name,account_id,account_status,age,amount_spent,balance,end_advertiser,funding_source,spend_cap,timezone_id,users"
Error in fbad_request(path = paste0("act_", accountid, "/"), method = "GET", : This is a bug in the fbRads package. Please report on GitHub with a detailed output: Received HTTP code 403 from proxy after CONNECT
Traceback:

1. fbad_init(accountid = accountid, token = tkn.at, version = "2.8")
2. fbad_get_adaccount_details(accountid, token, version)
3. fbad_request(path = paste0("act_", accountid, "/"), method = "GET", 
 .     params = list(access_token = token, fields = scope), version = version)
4. stop(paste(ifelse(inherits(curlres, "error"), "This is a bug in the fbRads package. Please report on GitHub with a detailed output:", 
 .     "FB query failed:"), res$message))

Name of facebook campaigns not updated

So, the campaigns were created as a copy of the campaign (since it's easier to do it that way) on the dashboard and then the names were updated.

The campaign names from API look like:

fb_campaign_name-COPY and I never get the updated names. How do we resolve this please?Is that the expected behavior? Is there a workaround for this?

fbRads Facebook API 2.6

Hi,

I'v loaded fbRads_0.2. I get the following error:

Error in fbad_request(path = paste0("act_", accountid, "/"), method = "GET", : (#2635) You are calling a deprecated version of the Ads API. Please update to the latest version: v2.6.

Is there a new version I can use with API v2.6? Or how can I select to use API v2.5?

Thanks

FB insights list.stack not working

Hi,
When I try to get data from fb_insights specified in the package manual:

:l <- fb_insights(fbacc, date_preset = 'today', level = 'ad')
library(rlist)
list.stack(list.select(l, date_start, date_stop, ad_id, total_actions,
total_unique_actions, total_action_value, impressions, unique_impressions,
social_impressions, unique_social_impressions, clicks, unique_clicks,
social_clicks, unique_social_clicks, spend, frequency, deeplink_clicks,
app_store_clicks, website_clicks, reach, social_reach, ctr, unique_ctr,
cpc, cpm, cpp, cost_per_total_action, cost_per_unique_click,
relevance_score = relevance_score$score))

I get an Error in eval(expr, envir, enclos) : object 'total_actions' not found. That is still an issue even after changding the date_preset to a week or last 30 days. The only metrics that this works for are a) impressions and b) spend .

The only way I can get these metrics is if I query
fb_insights(fbacc, date_preset = 'last_7_days', level = 'ad', fields = 'actions')
But the problem is I can query only one field. For example, I cannot query ad_id and actions together .

Any solutions to this problem?

Thanks!

Error in fb_insights: An unknown error occurred

My code used to work just fine and now it's failing at fb_insights call.

ERROR [2016-09-22 10:19:19] This is a temporary FB error. INFO [2016-09-22 10:19:21] Retrying query for the 1 st/nd/rd time ERROR [2016-09-22 10:19:33] This is a temporary FB error. INFO [2016-09-22 10:19:35] Retrying query for the 2 st/nd/rd time ERROR [2016-09-22 10:19:41] This is a temporary FB error. INFO [2016-09-22 10:19:43] Retrying query for the 3 st/nd/rd time ERROR [2016-09-22 10:19:50] This is a temporary FB error. Error in fb_insights(level = "ad", time_range = sprintf("{'since':%s,'until':%s}", : An unknown error occurred

I have tried a couple of times and it continues to fail somehow. How do I avoid this? If it's a temporary error, how do I check the response header for status and ask it to make the call again if it still fails?

My call looks like this : 1:

FBInsights <- fb_insights(level = 'ad', time_range="{'since':\"2016-09-21\",'until':\"2016-09-21\"}", time_increment= 1);

Edit: I tried it for like 7th time and then it worked so I absolutely need to be able to check the response header and recall it if it fails

Time Ranges with fb_insights

Sorry if this is just me being daft, however I am having trouble with the time_range variable for the insights method.

fb_insights(time_range = "{'since'=>'2016-05-30','until'=>'2016-07-31'}", level = 'ad', fields = "['date_start','date_stop','account_name','campaign_name','ad_name','impressions','spend','clicks','ctr','reach','frequency','cost_per_unique_click','objective','ad_id','account_id']")

I can get it to work with the date_preset, however I get an error message with the time_range

Error in fb_insights(time_range = "{'since'=>'2016-05-30','until'=>'2016-07-31'}", :
(#100) param time_range must be non-empty.

Any help on how to structure the time_range would be super.

Error in fbad_update_ad

Hi,

When I use fbad_update_ad(fbacc, id,list("name"="Jeff")) to change my ad's name, it will occur error:

Error in fbad_request(fbacc, path = id, params = list(...), method = "POST") :
This is a bug in the fbRads package. Please report on GitHub with a detailed output: STRING_ELT() can only be applied to a 'character vector', not a 'list"

How could I fix it?

Facebook Lead Ads

Facebook developed a new ad format. It creates leads from fb users, can the package read those leads?

How to specify the date range for fb_insights?

For all ad-accounts using fb_insights API at ad level,

I get
date_start = 2016-07-26
and
date_end = 2016-08-24

Today is 2016-08-24 so I suppose that is its default date range.

Why is it? How do I get the historical data?
Also, I will append it for every day eventually so would need to fetch it day by day.

So,

  1. I need to get lifetime data to start with
  2. I need to get data incrementally up until last date

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.