使用带有R的openpaths.cc API

Jem*_*s42 5 api r oauth httr

我试图从openpaths.cc中提取我的位置数据以将其与R一起使用.API使用OAuth并在此处进行了说明,但是,它仅提供了Python中的示例.

在查看了如何处理R中的OAuth(我几乎不熟悉)之后,我找到了ROAuth,因此我使用了提供的用法示例作为基础.

根据API的文档,所有请求的端点是https://openpaths.cc/api/1的,我有我的访问密钥和访问秘密,所以我天真地插入他们在cKey,cSecret,reqURL,accessURL,authURL,和testURL,但只得到了"错误的请求"从结果credentials$handshake()线.

reqURL <- "https://openpaths.cc/api/1"
accessURL <- "https://openpaths.cc/api/1"
authURL <- "https://openpaths.cc/api/1"
cKey <- "key"
cSecret <- "secret"
testURL <- "https://openpaths.cc/api/1"
credentials <- OAuthFactory$new(consumerKey=cKey,
                                consumerSecret=cSecret,
                                requestURL=reqURL,
                                accessURL=accessURL,
                                authURL=authURL,
                                needsVerifier=TRUE)
credentials$handshake()
## the GET isn’t strictly necessary as that’s the default
credentials$OAuthRequest(testURL, "GET")
Run Code Online (Sandbox Code Playgroud)

虽然我觉得我不知道自己在做什么,但我至少证实了ROAuth能够使用HMAC-SHA1方法,这是openpath所要求的.

编辑:我安装了ROAuth版本0.9.3

EDIT2:在了解了httr后,我认为这可能是适合该任务的库,但是我仍然无法产生任何可用的结果,因为令牌创建oauth1.0_token只会导致Bad request再次出现.我认为我的主要问题是缺少openpaths.cc的API文档.使用所有这些工具,我仍然不知道如何正确使用它们.

Kar*_* W. 0

据我所知。我收到“400 Not Authorized”消息,可能是因为我的 openpaths 帐户未连接到 foursquare,也可能是代码有问题。请尝试一下!

所需包:

library(RCurl)
library(digest)
library(base64)
Run Code Online (Sandbox Code Playgroud)

一些函数借用/改编自ROAuth

## Get a random sequence of characters.
## Nonce - number used only once.
genNonce <- function(len = 15L + sample(1:16, 1L)) {
  els <- c(letters, LETTERS, 0:9, "_")
  paste(sample(els, len, replace = TRUE), collapse = "")
}

## this function is derived from utils::URLencode
## Characters not in the unreserved character set ([RFC3986] section 2.3) MUST be encoded
##   unreserved = ALPHA, DIGIT, '-', '.', '_', '~'
## cf. http://oauth.net/core/1.0/#encoding_parameters
encodeURI <- function(URI, ...) {
  if (!is.character(URI)) {
    URI
  } else {
    OK <- "[^-A-Za-z0-9_.~]"
    x <- strsplit(URI, "")[[1L]]
    z <- grep(OK, x)
    if (length(z)) {
      y <- sapply(x[z], function(x) paste("%", toupper(as.character(charToRaw(x))),
                                          sep = "", collapse = ""))
      x[z] <- y
    }
      paste(x, collapse = "")
  }
}

## we escape the values of the parameters in a special way that escapes
## the resulting % prefix in the escaped characters, e.g. %20 becomes
## %2520 as %25 is the escape for %
## cf. http://tools.ietf.org/html/rfc5849#section-3.4.1.3.2
normalizeParams <- function(params, escapeFun) {
  names(params) <- sapply(names(params), escapeFun, post.amp = TRUE)
  params <- sapply(params, escapeFun, post.amp = TRUE)
  ## If two or more parameters share the same name, they are sorted by their value.
  params <- params[order(names(params), params)]
  return(paste(names(params), params, sep = "=", collapse = "&"))
}

## From Ozaki Toru's code at https://gist.github.com/586468
signWithHMAC <- function(key, data) {
  blockSize <- 64
  hashlength <- 20
  innerpad   <- rawToBits(as.raw(rep(0x36, blockSize)))
  outerpad   <- rawToBits(as.raw(rep(0x5C, blockSize)))
  zero       <- rep(0 ,64)

  HexdigestToDigest <- function(digest) {
    as.raw(strtoi(substring(digest, (1:hashlength)*2-1,
                            (1:hashlength)*2), base=16))
  }

  mac <- function(pad, text) {
    HexdigestToDigest(digest(append(packBits(xor(key, pad)), text),
                             algo='sha1', serialize=FALSE))
  }

  if(nchar(key) >= 64) {
    keyDigested <- digest(key, algo="sha1", serialize=FALSE)
    key <- intToUtf8(strtoi(HexdigestToDigest(keyDigested), base=16))
  }
  key <- rawToBits(as.raw(append(utf8ToInt(key), zero)[1:blockSize]))

  base64(mac(outerpad, mac(innerpad, charToRaw(data))))[1]
}

## Sign an request made up of the URL, the parameters as a named character
## vector the consumer key and secret and the token and token secret.
signRequest  <- function(uri, consumerKey, consumerSecret, params=character(), 
                         oauthKey = "", oauthSecret = "", httpMethod = "GET",
                         nonce = genNonce(),
                         timestamp = Sys.time()) {
  httpMethod <- toupper(httpMethod)

  params["oauth_nonce"] <- nonce
  params["oauth_timestamp"] <- as.integer(timestamp)
  params["oauth_consumer_key"] <- consumerKey
  params["oauth_signature_method"] <- 'HMAC-SHA1'
  params["oauth_version"] <- '1.0'
  if(oauthKey != "") params["oauth_token"] <- oauthKey
  odat <- paste(
      encodeURI(httpMethod), encodeURI(uri), 
      encodeURI(normalizeParams(params, encodeURI), post.amp = TRUE),
      sep = "&"
  )
  okey <- encodeURI(consumerSecret)
  if(oauthSecret != "") okey <- paste(okey, encodeURI(oauthSecret), sep = "&")

  params["oauth_signature"] <- signWithHMAC(okey, odat)
  return(params)
}
Run Code Online (Sandbox Code Playgroud)

现在这个函数尝试复制 openpaths 网站上的示例:

openpaths <- function(
    access_key=getOption("openpaths.access_key"), 
    secret_key=getOption("openpaths.secret_key"), 
    curl=getCurlHandle()) {

    uri <- 'https://openpaths.cc/api/1'
    params <- signRequest(uri, consumerKey=access_key, consumerSecret=secret_key)
    oa_header <- paste(names(params), params, sep="=", collapse=",")
    ret <- getURL(
        uri,
        curl=curl,
        .opts=list(
            header=TRUE,
            verbose=TRUE,
            httpheader=c(Authorization=paste("OAuth ", oa_header, sep="")),
            ssl.verifypeer = TRUE, 
            ssl.verifyhost = TRUE, 
            cainfo = system.file("CurlSSL", "cacert.pem", package = "RCurl")
        )
    )
    return(ret)
}
Run Code Online (Sandbox Code Playgroud)