是否有一种使用curl运行经过身份验证的Google Analytics查询的简单方法?

时间:2015-08-23 19:14:17

标签: curl google-analytics google-api

我想在命令行上使用curl运行Google AnalyticsAPI查询,我对可用的身份验证方法感到困惑。我希望我只需要一个客户端ID和秘密来传递curl请求,但所有OAuth身份验证的东西看起来都坚持通过服务器或浏览器进行往返。

最简单的“永久”方式是什么,一劳永逸地被撤销,验证命令行脚本以查询Google Analytics,然后呢?每次我想运行脚本时,我都不想打开浏览器。

1 个答案:

答案 0 :(得分:0)

到目前为止,这就是我所得到的:

{-# LANGUAGE OverloadedStrings #-}

import Data.Yaml
import Control.Monad
import Data.ByteString.Char8 (pack, unpack)
import Data.Monoid
import Network.Google.OAuth2
import Network.HTTP.Conduit
import Network.HTTP.Types (hAuthorization)
import qualified Data.ByteString.Char8 as B8
import qualified Data.ByteString.Lazy.Char8 as L8

data OAuth2Credentials = OAuth2Credentials {
    getClientID :: String,
    getClientSecret :: String
} deriving (Show, Eq)

instance FromJSON OAuth2Credentials where
    parseJSON (Object value) = OAuth2Credentials <$>
        value .:  "clientID" <*>
        value .:  "clientSecret"
    parseJSON _ = mzero

parseOAuth2Credentials :: String -> Maybe OAuth2Credentials
parseOAuth2Credentials source = Data.Yaml.decode $ pack source

main :: IO ()
main = do
    source <- readFile "analytics-credentials.yml"
    let creds = parseOAuth2Credentials source
    case creds of
        Just creds -> do
            let client = OAuth2Client (getClientID creds) (getClientSecret creds)
            token <- getAccessToken client authScope (Just tokenCacheFile)
            request <- parseUrl analyticsQueryURL
            response <- withManager $ httpLbs $ authorize token request
            L8.putStrLn $ responseBody response
        Nothing -> return ()
    where
        authorize token request = request { requestHeaders = [(hAuthorization, B8.pack $ "Bearer " <> token)] }
        analyticsQueryURL = "…"
        authScope = ["https://www.google.com/analytics/feeds/"]
        tokenCacheFile = "analytics-token.yml"

不完全卷曲并且不完全简单,但在最初的基于浏览器的令牌生成之后,访问令牌被缓存在文件中,后续请求不需要任何人工交互。