我试图通过R访问QuickBooks在线API。这是我到目前为止所做的:
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))
当通过QBOtoken运行上面的代码时,我会通过整个Oauth2.0“舞蹈”并得到回复:
Waiting for authentication in browser...
Press Esc/Ctrl + C to abort
Authentication complete.
但是,当我执行GET命令时,它返回:
Error in self$credentials$access_token :
$ operator is invalid for atomic vectors
生成的.httr-oauth
文件包含284行,每行32个字符。这是正常的吗?
我通过Postman连接到API,它生成一个访问令牌,允许我在我的代码中执行类似GET请求的查询。 Intuit Developer上还有一个Oauth 2.0游乐场。不知何故,在R中,我没有获得访问令牌和刷新令牌。
另一个问题是,我目前正在尝试连接到开发环境。对于QuickBooks Online,重定向URL可以是开发环境中的localhost,但如果我想连接到制作公司(我的公司)数据,我将需要https重定向URL。这可以通过R吗?
此项目的最终目标是让脚本在每晚自动运行,连接到API,并将数据ETL到关系数据库中以进行报告/分析。任何帮助将不胜感激!
答案 0 :(得分:0)
我确实得到了这个“功能”,但这绝不是好的代码。其中的某些方法(例如将令牌存储在csv中)不是最佳实践,而只是用于测试代码的创可贴。
我在结构中创建了一个tokens.csv文件:
"RefreshToken","AccessToken"
"<RefreshToken>","<AccessToken>"
下面是我的脚本,该脚本从QBO api沙箱中检索了客户数据。
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
希望这能使球正确滚动。让我知道您是否有任何反馈!