Run Batch Process with Oauth2.0_token - r

I am trying to connect to the Instagram API using R and want my code to run as a batch process on an Ubuntu server. Currently, I am using oauth2.0_token and running into an error when it needs to connect to the browser for authentication.
When I try to connect to the API on the server, I get this message
Waiting for authentication in browser...
Press Esc/Ctrl + C to abort
What would be a way to get around this? Or is there a better way to connect to the Instagram API?
Here is an example of the code I am currently using that is producing the error
app_name <- 'Testing'
client_id <- 'XXXXXXX'
client_secret <- 'XXXXXXX'
scope = 'basic'
instagram <- oauth_endpoint(
authorize = "https://api.instagram.com/oauth/authorize",
access = "https://api.instagram.com/oauth/access_token")
myapp <- oauth_app(app_name, client_id, client_secret)
ig_oauth <- ?oauth2.0_token(instagram, myapp,scope="basic",
type = "application/x-www-form-urlencoded",cache=FALSE)

Related

Error in Oauth2.0 authentication in R using HTTR (failed to connect: connection refused)

I am trying to create a simple app (in R) using GroupMe's API, which utilizes OAuth2.0. The documentation can be found here. However, I'm getting stuck on the first step of authentication/token generation for a user. See below for my code and the response I get:
access_key = ****
client_id = ****
gendpoint <- oauth_endpoint(
authorize = glue("https://oauth.groupme.com/oauth/login_dialog?client_id={client_id}"),
access = glue("http://localhost:1410/?access_token={access_key}")
)
gapp <- oauth_app(
"pingme",
key = client_id,
secret = access_key
)
t <- oauth2.0_token(
endpoint = gendpoint,
app = gapp
)
The above code is sufficient to bring in the login page, which presumably allows me to enter my credentials to obtain a token. However, when I enter my credentials, I get the following error message in R:
Authentication complete.
Error in curl::curl_fetch_memory(url, handle = handle) :
Failed to connect to localhost port 1410: Connection refused
So it looks like my authentication/login credentials worked, but somewhere an error prevented me from actually generating the token.
Could someone help me with this? This is my first time using the OAuth2.0 framework so I'm very confused. Thanks in advance!

Error when signing into R Studio on Google Cloud VM: Unable to connect to service

I want to run Rstudio on a VM through Google Cloud Platform. Everything seems to work except when I sign in to RStudio I receive an 'RStudio Initialization Error': "Unable to connect to service". My username and password are correct as if they're wrong it tells me so.
I created the instance using RStudio on my laptop. I've tried adding a rule in Google Cloud Platform to allow all access to the IP address but that did not work.
#My Code
library(googleComputeEngineR)
#Setup ------------
project <- "r-bench"
zone <- "europe-west1-b"
account_key <- "gcs-key.json"
Sys.setenv(GCE_AUTH_FILE = account_key,
GCE_DEFAULT_PROJECT_ID = project,
GCE_DEFAULT_ZONE = zone)
gce_auth()
#Set our default global project
gce_global_project(project)
gce_global_zone(zone)
default_project <- gce_get_project("r-bench")
default_project$name
#Deploy instance
vm <- gce_vm(template = "rstudio",
name = "rstudio-demo",
username = "rstudio",
password = "xxxxxxxx",
predefined_type = "n1-standard-1")
I expect to sign in and use RStudio as normal. Instead, I receive the error I mentioned previously.
If I am not mistaken using rstudio is a reserved name and as a username is not allowed.

Quickbooks Online API Oauth2.0 using httr

I am trying to access the QuickBooks online API via R. Here is what I have so far:
library(httr)
library(httpuv)
endPoint <- oauth_endpoint(request = NULL,
authorize = "https://appcenter.intuit.com/connect/oauth2",
access = "https://oauth.platform.intuit.com/oauth2/v1/tokens/bearer")
App <- oauth_app("Untitled",
key = "xxxx",
secret = "xxxxx",
redirect_uri = "http://localhost:1410/")
QBOtoken <- oauth2.0_token(endpoint = endPoint,
app = App,
scope = "com.intuit.quickbooks.accounting",
type = "code",
cache = T)
GET("https://sandbox-quickbooks.api.intuit.com/v3/company/193514718345164/query?query=Select * from Payment", config(token = QBOtoken))
When run the code above through QBOtoken, I go through the whole Oauth2.0 "dance" and get the response:
Waiting for authentication in browser...
Press Esc/Ctrl + C to abort
Authentication complete.
However, when I execute the GET command, it returns:
Error in self$credentials$access_token :
$ operator is invalid for atomic vectors
The .httr-oauth file that is generated is filled with 284 rows of 32 characters. Is that normal?
I have connected to the API via Postman and it generates an access token allowing me to execute queries like the GET request in my code. There is also an Oauth 2.0 playground on Intuit Developer. Somehow, in R, I am not getting the access token and refresh token.
Another concern, is that I am currently trying to connect to a development environment. For QuickBooks Online, the redirect URL can be the localhost in the development environment, but if I want to connect to the production company(my company) data I will need a https redirect URL. Will this be possible through R?
My ultimate goal for this project is for the script to automatically run on a nightly basis, connect to the API, and ETL the data into a Relational Database for reporting/analytics purposes. Any help would be greatly appreciated!
I did get this "functional," but it is by no means good code. Some of this, like storing tokens in a csv, is not best practice, just a band-aid to test the code.
I created a tokens.csv file in the structure:
"RefreshToken","AccessToken"
"<RefreshToken>","<AccessToken>"
Below is my script that retrieved customer data from the QBO api sandbox.
library(httr)
library(httpuv)
library(curl)
library(jsonlite)
library(base64enc)
#Client ID and Client Secret were retrieved from the online explorer
clientID <- "<ClientID>"
clientSecret <- "<ClientSecret>"
scope <- "com.intuit.quickbooks.accounting"
tokens <- read.csv("tokens.csv")
RefreshToken <- as.character(tokens$RefreshToken[1])
AccessToken <- as.character(tokens$AccessToken[1])
authorize <- base64enc::base64encode(charToRaw(paste0(clientID,":",clientSecret)))
oauth_refresh <- httr::POST("https://oauth.platform.intuit.com/oauth2/v1/tokens/bearer",
add_headers('Content-Type'= "application/x-www-form-urlencoded",
'Accept'= 'application/json',
'Authorization'= paste0('Basic ',authorize)
),
body = list('grant_type'='refresh_token',
'refresh_token'=RefreshToken),
encode = "form")
oaJSON <- fromJSON(content(oauth_refresh, as = "text"))
RefreshToken <- oaJSON[["refresh_token"]][1]
AccessToken <- oaJSON[["access_token"]][1]
tokens <- as.data.frame(list('RefreshToken'=RefreshToken,'AccessToken'=AccessToken))
write.csv(tokens,file = "tokens.csv", row.names = F)
datas <- httr::GET("https://sandbox-quickbooks.api.intuit.com/v3/company/<ID>/query?query=SELECT%20%2a%20FROM%20Customer",
accept_json(),
add_headers('Authorization'= paste0("Bearer ",AccessToken))
)
#datas$status_code
j_son <- content(datas, as = "text")
customers <- fromJSON(j_son)
customer_df <- customers$QueryResponse$Customer
Hopefully this gets the ball rolling correctly for you. Let me know if you have any feedback!

Configuring listener_endpoint in httr when using Rstudio server

I;'m struggling to connect to Google Analytics with httr oauth2.0 function
oauth2.0_token(oauth_endpoints("google")
, oauth_app("google", client.id, client.secret)
, scope = "https://www.googleapis.com/auth/analytics.readonly")
It works perfectly in my local Rstudio, but it breaks in AWS-based Rstudio Server. The error appears when I agree to pass data in browser and Google redirects me to the page
http://localhost:1410/?state=codehere
When launching authentication in local Rstudio, browser responds with a message - Authentication complete. Please close this page and return to R, incase of Rstudio server it's just This webpage is not available
I suspect I need to change listener_endpoint configuration, but how? Should I put my Rstudio server address instead of default 127.0.0.1? Or is it flaw of httr+Rtudio server and I should not bother?
Your redirect URI is part of the problem. Httr's oauth2.0_token() function identify the correct one. When you set up your project, Google Analytics created two redirect URIs, one that can be used on your RStudio IDE (local) and one that can be used in the RStudio web-based environment for out-of-of band authentication: "urn:ietf:wg:oauth:2.0:oob"
Once you've authenticated, the following code should work.
library(httr)
ga_id <- YourProjectID
client_id <- YourClientID
redirect_uri <- 'urn:ietf:wg:oauth:2.0:oob'
scope <- YourScope
client_secret <- YourSecret
response_type <-'code'
auth1 <- oauth2.0_token(
endpoint = oauth_endpoints("google"),
app = oauth_app(
"google",
key = client_id,
secret = client_secret
),
scope,
use_oob = TRUE,
cache = TRUE
)
-- Ann
You could use out-of-band authentication -
options(httr_oob_default = TRUE)

Get oauth_callback for Deployed R Shiny Application

I have a Shiny application that uses the Instagram API, and needs an access token. When running locally, I am able to use
full_url <-oauth_callback()
full_url <- gsub("(.*localhost:[0-9]{1,5}/).*", x=full_url, replacement="\\1")
print(full_url)
to get the callback url to register with Instagram. How would I go about getting this url when my application is deployed?
Additionally, and this might be related, when the app is deployed I get an error that:
Error : oauth_listener() needs an interactive environment
I never explicitly use oauth_listener(), so I'm not sure how to counteract this. All of my oauth related code is as follows:
instagram <- oauth_endpoint(
authorize="https://api.instagram.com/oauth/authorize",
access="https://api.instagram.com/oauth/access_token",)
my_app <- oauth_app(app_name, client_id, client_secret)
ig_oauth <- oauth2.0_token(instagram, my_app, scope="basic", type="application/x-www-form-urlencoded", cache=FALSE)

Resources