ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

无法使用PHP连接到OAuth 2.0

2019-07-08 18:27:38  阅读:230  来源: 互联网

标签:php google-oauth google-analytics-api google-api-php-client


我有一个网站,我希望向所有访问者显示我的Google Analytics帐户中的一些数据(来自不同国家/地区的独特网页浏览量).就我而言,可以使用OAuth 2.0和Google AnalyticsAPI执行此操作.我希望身份验证能够实现自动化,以便访问我网站的任何人都可以查看此数据,而不仅仅是可以登录我的Google Analytics帐户的用户.

我做了什么

>使用Google Developers Console制作项目.
>将Analytics API更改为ON.
>创建了一个服务帐户.
>为服务器和浏览器应用程序生成的API密钥(不知道确切地使用哪个和哪里使用).
>下载用于PHP的Google API客户端库.
>上传了我创建服务帐户时下载的.p12密钥,将其上传到我的网站并链接到google-api-php-client-master / examples / service-account.php.
>在google-api-php-client-master / examples / service-account.php中声明了我的服务帐户客户端ID.

目前的代码

<?php
/*
 * Copyright 2013 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
session_start();
include_once "templates/base.php";

/************************************************
  Make an API request authenticated with a service
  account.
 ************************************************/
set_include_path("../src/" . PATH_SEPARATOR . get_include_path());
require_once 'Google/Client.php';
require_once 'Google/Service/Books.php';

/************************************************
  ATTENTION: Fill in these values! You can get
  them by creating a new Service Account in the
  API console. Be sure to store the key file
  somewhere you can get to it - though in real
  operations you'd want to make sure it wasn't
  accessible from the webserver!
  The name is the email address value provided
  as part of the service account (not your
  address!)
  Make sure the Books API is enabled on this
  account as well, or the call will fail.
 ************************************************/
$client_id = 'SECRET-NUMBERS.apps.googleusercontent.com';
$service_account_name = '';
$key_file_location = 'SOMENUMBERS-privatekey.p12';

echo pageHeader("Service Account Access");
if ($client_id == 'SECRET-NUMBERS.apps.googleusercontent.com'
    || !strlen($service_account_name)
    || !strlen($key_file_location)) {
  echo missingServiceAccountDetailsWarning();
}

$client = new Google_Client();
$client->setApplicationName("Client_Library_Examples");
$service = new Google_Service_Books($client);

/************************************************
  If we have an access token, we can carry on.
  Otherwise, we'll get one with the help of an
  assertion credential. In other examples the list
  of scopes was managed by the Client, but here
  we have to list them manually. We also supply
  the service account
 ************************************************/
if (isset($_SESSION['service_token'])) {
  $client->setAccessToken($_SESSION['service_token']);
}
$key = file_get_contents($key_file_location);
$cred = new Google_Auth_AssertionCredentials(
    $service_account_name,
    array('https://www.googleapis.com/auth/analytics.readonly'),
    $key
);
$client->setAssertionCredentials($cred);
if($client->getAuth()->isAccessTokenExpired()) {
  $client->getAuth()->refreshTokenWithAssertion($cred);
}
$_SESSION['service_token'] = $client->getAccessToken();

/************************************************
  We're just going to make the same call as in the
  simple query as an example.
 ************************************************/
$optParams = array('filter' => 'free-ebooks');
$results = $service->volumes->listVolumes('Henry David Thoreau', $optParams);
echo "<h3>Results Of Call:</h3>";
foreach ($results as $item) {
  echo $item['volumeInfo']['title'], "<br /> \n";
}

echo pageFooter(__FILE__);

问题

>在google-api-php-client-master / examples / service-account.php中有这段代码,我不太明白:

$service_account_name =”;

我应该在这里宣布什么?

>当我完成上述所有操作并在我的网站上加载google-api-php-client-master / examples / service-account.php页面时,我收到以下两个错误:

Warning: You need to set Client ID, Email address and the location of the Key from the Google API console

Fatal error: Uncaught exception ‘Google_Auth_Exception’ with message ‘Error refreshing the OAuth2 token, message: ‘{ “error” : “invalid_grant” }” in /home/texterx1/public_html/google-api-php-client-master/src/Google/Auth/OAuth2.php:327 Stack trace: #0 /home/texterx1/public_html/google-api-php-client-master/src/Google/Auth/OAuth2.php(289): Google_Auth_OAuth2->refreshTokenRequest(Array) #1 /home/texterx1/public_html/google-api-php-client-master/examples/service-account.php(75): Google_Auth_OAuth2->refreshTokenWithAssertion(Object(Google_Auth_AssertionCredentials)) #2 {main} thrown in /home/texterx1/public_html/google-api-php-client-master/src/Google/Auth/OAuth2.php on line 327

我做错了什么?

解决方法:

好的,您需要做的第一件事是在开发者控制台上获取与应用程序一起创建的应用程序的电子邮件地址.

1046123799103-nk421gjc2v8mlr2qnmmqaak04ntb1dbp@developer.gserviceaccount.com

登录您的GA,转到您希望服务帐户访问的帐户的管理部分.您需要在帐户级别为该电子邮件帐户提供访问权限,只需向他们提供阅读和分析即可.

<?php
session_start();
require_once 'Google/Client.php';
require_once 'Google/Service/Analytics.php';
// Values from APIs console for your app    
$client_id = 'Client ID';
$service_account_name = 'Email address';
$key_file_location = 'The file you downloaded';

$client = new Google_Client();
$client->setApplicationName("Client_Library_Examples");
if (isset($_SESSION['service_token'])) {
        $client->setAccessToken($_SESSION['service_token']);
    }
    $key = file_get_contents($key_file_location);

    $cred = new Google_Auth_AssertionCredentials(
        $service_account_name,
        array('https://www.googleapis.com/auth/analytics.readonly'),
        $key
        );
    $client->setAssertionCredentials($cred);
    if($client->getAuth()->isAccessTokenExpired()) {
        $client->getAuth()->refreshTokenWithAssertion($cred);
    }
    $_SESSION['service_token'] = $client->getAccessToken();
    $service = new Google_Service_Analytics($client);  
    $accounts = $service->management_accountSummaries->listManagementAccountSummaries();

   foreach ($accounts->getItems() as $item) {
    echo "Account: ",$item['name'], "  " , $item['id'], "<br /> \n";

    foreach($item->getWebProperties() as $wp) {
    echo '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;WebProperty: ' ,$wp['name'], "  " , $wp['id'], "<br /> \n";    

    $views = $wp->getProfiles();
    if (!is_null($views)) {
    foreach($wp->getProfiles() as $view) {
        //  echo '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;View: ' ,$view['name'], "  " , $view['id'], "<br /> \n";    
    }
                }
            }
        }

标签:php,google-oauth,google-analytics-api,google-api-php-client
来源: https://codeday.me/bug/20190708/1404962.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有