php 服务应用程序和 Google Analytics API V3:服务器到服务器 OAuth2 身份验证?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9863509/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 07:48:32  来源:igfitidea点击:

Service Applications and Google Analytics API V3: Server-to-server OAuth2 authentication?

phpgoogle-apioauth-2.0google-analytics-apijwt

提问by moon prism power

I'm trying to make a server application to routinely pull Google Analytics data from my own GA account. Note, it is a personal, server-side application accessing my own data, i.e. there is no end-user accessing this application.

我正在尝试制作一个服务器应用程序,以定期从我自己的 GA 帐户中提取 Google Analytics 数据。请注意,它是访问我自己数据的个人服务器端应用程序,即没有最终用户访问此应用程序。

As such, I registered my application in the Google API Consoleas a Service Application, which gave me a Client IDand a Private Key. It is my understanding that Service Applications do NOT use Application Secretand Redirect URLas there is no end-user in this server-to-server authentication flow. Indeed, the Google API Console gave me no Secret and did not prompt me for a Redirect URL.

因此,我在Google API Console中将我的应用程序注册为Service Application,它给了我一个Client ID和一个Private Key。我的理解是服务应用程序不使用应用程序机密重定向 URL,因为在此服务器到服务器身份验证流程中没有最终用户。事实上,Google API 控制台没有给我任何秘密,也没有提示我输入重定向 URL。

Unfortunately, I can not figure out how to authenticate my Service Application within Google's PHP Client API. There is extensive documentation on authenticating web applications withan end-user.

不幸的是,我无法弄清楚如何在Google 的 PHP Client API 中验证我的服务应用程序。有关于验证的Web应用程序广泛的文件最终用户。

Google's documentation suggests it is possible to authenticate server-to-server by signing a JWT request with the private key. I just can't figure out how to do within the PHP client API (although I've browsed the source and there's definitely a scriptthat signs a request with the private key.)

Google 的文档表明可以通过使用私钥签署 JWT 请求来验证服务器到服务器的身份。我只是不知道如何在 PHP 客户端 API 中执行(尽管我已经浏览了源代码,并且肯定有一个使用私钥对请求进行签名的脚本。)

Am I missing something here? How can I perform authentication for a Service Application with my private key and the Google PHP client API?

我在这里错过了什么吗?如何使用我的私钥和 Google PHP 客户端 API 对服务应用程序执行身份验证?

Edited for clarity

为清晰起见进行了编辑

回答by moon prism power

UPDATE July 21st, 2012

2012 年 7 月 21 日更新

Google Analytics API V3 now supports OAuth2 tokens returned by a .p12-signed JWT request. That is, we can now use the Analytics API w/ service accounts.

Google Analytics API V3 现在支持由 .p12 签名的 JWT 请求返回的 OAuth2 令牌。也就是说,我们现在可以使用带有服务帐户的 Analytics API

Currently pulling 4 years of day-by-day metrics, just for the hell of it.

目前正在提取 4 年的每日指标,只是为了它。

Here's a quick 'n' dirty step-by-step:

这是一个快速的“n”步骤:

  1. Go to the Google API Consoleand create a new app

  2. In the Servicestab, flip the Google Analyticsswitch

  3. In the API Accesstab, click Create an OAuth2.0 Client ID

    • enter your name, upload a logo, and click Next

    • select the Service accountoption and press Create client ID

    • download your private key

  4. Now you're back on the API Accesspage. You'll see a section called Service accountwith a Client IDand Email address

    • Copy the email address (something like ####@developer.gserviceaccount.com)

    • Visit your GA Adminand add this email as a user to your properties

    • This is a must; you'll get cryptic errors otherwise.

  5. Get the latest Google PHP Client APIvia Github

    git submodule add https://github.com/google/google-api-php-client.git google-api-php-client-read-only
    
  6. Rock 'n' roll (thanks all for tips on updated class names):

    // api dependencies
    require_once(PATH_TO_API . 'Google/Client.php');
    require_once(PATH_TO_API . 'Google/Service/Analytics.php');
    
    // create client object and set app name
    $client = new Google_Client();
    $client->setApplicationName(APP_NAME); // name of your app
    
    // set assertion credentials
    $client->setAssertionCredentials(
      new Google_Auth_AssertionCredentials(
    
        APP_EMAIL, // email you added to GA
    
        array('https://www.googleapis.com/auth/analytics.readonly'),
    
        file_get_contents(PATH_TO_PRIVATE_KEY_FILE)  // keyfile you downloaded
    
    ));
    
    // other settings
    $client->setClientId(CLIENT_ID);           // from API console
    $client->setAccessType('offline_access');  // this may be unnecessary?
    
    // create service and get data
    $service = new Google_Service_Analytics($client);
    $service->data_ga->get($ids, $startDate, $endDate, $metrics, $optParams);
    
  1. 转到Google API 控制台并创建一个新应用

  2. 在“服务”选项卡中,翻转Google Analytics(分析)开关

  3. API 访问选项卡中,单击创建 OAuth2.0 客户端 ID

    • 输入您的姓名,上传徽标,然后单击下一步

    • 选择服务帐户选项,然后按创建客户端 ID

    • 下载你的私钥

  4. 现在您又回到了API 访问页面。您将看到一个名为服务帐户的部分,其中包含客户 ID电子邮件地址

    • 复制电子邮件地址(类似于####@developer.gserviceaccount.com

    • 访问您的GA管理添加电子邮件作为用户你的属性

    • 这是必须的;否则你会得到神秘的错误。

  5. 通过 Github获取最新的Google PHP Client API

    git submodule add https://github.com/google/google-api-php-client.git google-api-php-client-read-only
    
  6. 摇滚乐(感谢大家提供有关更新类名称的提示):

    // api dependencies
    require_once(PATH_TO_API . 'Google/Client.php');
    require_once(PATH_TO_API . 'Google/Service/Analytics.php');
    
    // create client object and set app name
    $client = new Google_Client();
    $client->setApplicationName(APP_NAME); // name of your app
    
    // set assertion credentials
    $client->setAssertionCredentials(
      new Google_Auth_AssertionCredentials(
    
        APP_EMAIL, // email you added to GA
    
        array('https://www.googleapis.com/auth/analytics.readonly'),
    
        file_get_contents(PATH_TO_PRIVATE_KEY_FILE)  // keyfile you downloaded
    
    ));
    
    // other settings
    $client->setClientId(CLIENT_ID);           // from API console
    $client->setAccessType('offline_access');  // this may be unnecessary?
    
    // create service and get data
    $service = new Google_Service_Analytics($client);
    $service->data_ga->get($ids, $startDate, $endDate, $metrics, $optParams);
    

 

 

original workaround below

下面的原始解决方法



It seems that, despite ambiguous documentation, most Google APIs do not support service accounts yet, including Google Analytics. They cannot digest OAuth2 tokens returned by a .p12 signed JWT request. So, as of right now, you cannot use Google Analytics API V3 with a service account.

Workaround:

  1. In the Google API console, create a clientapplication.

  2. Follow the steps in the Google PHP Client APIexamples to generate a client_auth_urlusing your client_id, client_secret, and redirect_uri

  3. Login to Googleusing cURL. (Be sure to use a cookie file!)

  4. Open the client_auth_urlin cURL and complete the form. Make sure you set curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0);and curl_setopt($ch, CURLOPT_HEADER, 1);as the authorization_codewill be in the Location:header of the response.

  5. Using your client_id, client_secret, redirect_uri, and the activation code from Step 4, post a request to the Google's OAuth2 Token machine. Make sure you include grant_type = "authorization_code"in your post fields.

  6. Hurray, you now have a refresh_tokenthat never expires, and a working access_token! Post a request to the Google's OAuth2 Token machinewith your client_id, client_secret, redirect_uri, and refresh_tokenwhen your access_tokenexpires and you'll get a new one.

似乎,尽管文档含糊不清,但大多数 Google API 尚不支持服务帐户,包括 Google Analytics。它们无法消化由 .p12 签名的 JWT 请求返回的 OAuth2 令牌。因此,截至目前,您无法通过服务帐户使用 Google Analytics API V3

解决方法:

  1. Google API 控制台 中,创建一个客户端应用程序。

  2. 请按照下列步骤谷歌PHP客户端API的例子来生成client_auth_url使用client_idclient_secretredirect_uri

  3. 使用 cURL登录Google。(一定要使用cookie文件!)

  4. 打开client_auth_urlin cURL 并完成表单。请确保您设置curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0);curl_setopt($ch, CURLOPT_HEADER, 1);authorization_code将在Location:响应的头。

  5. 使用您的client_idclient_secretredirect_uri和步骤 4 中的激活码,向Google 的 OAuth2 令牌机器发布请求。确保您包含grant_type = "authorization_code"在您的帖子字段中。

  6. 万岁,您现在拥有一个refresh_token永不过期的access_token!使用您的, ,向Google 的 OAuth2 Token 机器发布请求,当您的过期时,您将获得一个新的。client_idclient_secretredirect_urirefresh_tokenaccess_token

回答by Chirag Shah

The Google API PHP Client now supports service accounts on trunk.

Google API PHP 客户端现在支持主干上的服务帐户。

The implementation hasn't been released yet, so you'll need to checkoutthe latest version of the PHP client.

该实现尚未发布,因此您需要检查最新版本的 PHP 客户端。

I've prepared a sample application that demonstrates how you can use service accounts to hit the Google Prediction API. To view the example, take a peek at examples/prediction/serviceAccount.php or visit: http://code.google.com/p/google-api-php-client/source/browse/trunk/examples/prediction/serviceAccount.php

我准备了一个示例应用程序,用于演示如何使用服务帐户访问 Google Prediction API。要查看示例,请查看 examples/prediction/serviceAccount.php 或访问:http: //code.google.com/p/google-api-php-client/source/browse/trunk/examples/prediction/serviceAccount .php

回答by jk.

If you are using Google's PHP client APIthen go to the Google API Consoleand click on API Accesson the left.

如果您使用的是Google 的 PHP 客户端 API,请转到Google API 控制台并单击API Access左侧的。

Then Create a Client ID. That will give you the secretand it is where you set your redirect URL. It won't give you a redirect URL - that is the URL the app sends the user back to after authenticating.

然后Create a Client ID。这会给你secret,它是你设置你的redirect URL. 它不会为您提供重定向 URL - 这是应用程序在身份验证后将用户发送回的 URL。

There are other authentication methodsyou can look at.

还有其他身份验证方法,你可以看看。

回答by Martin Lojek

you can use very usefull php library GAPI(Google Analytics API PHP Interface) to access Google Analytics without OAuth. It's easy to use.

您可以使用非常有用的 php 库GAPI(Google Analytics API PHP 接口)在没有 OAuth 的情况下访问 Google Analytics。它很容易使用。