Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/hadoop/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 从本地服务器请求谷歌分析数据_Php_Google Analytics Api - Fatal编程技术网

Php 从本地服务器请求谷歌分析数据

Php 从本地服务器请求谷歌分析数据,php,google-analytics-api,Php,Google Analytics Api,我想编写一个PHP脚本,从GA导入web统计数据。该脚本可以通过web前端(用于触发导入)访问,并驻留在本地服务器(127.0.0.1)上 我从文档中了解到,有两种用于验证和使用核心API的选项: API密钥-仅授予访问统计信息的权限 OAuth2-完全授权 如果我正确理解了OAuth2的机制,那么在我的场景中这不是一个选项,因为我无法指定回调URL。我想到了黑客解决方案——比如建立一个直接从浏览器连接到GA的web配置文件身份验证,然后通过JavaScript获取数据并将其提供给导入脚本——

我想编写一个PHP脚本,从GA导入web统计数据。该脚本可以通过web前端(用于触发导入)访问,并驻留在本地服务器(127.0.0.1)上

我从文档中了解到,有两种用于验证和使用核心API的选项:

  • API密钥-仅授予访问统计信息的权限
  • OAuth2-完全授权
  • 如果我正确理解了OAuth2的机制,那么在我的场景中这不是一个选项,因为我无法指定回调URL。我想到了黑客解决方案——比如建立一个直接从浏览器连接到GA的web配置文件身份验证,然后通过JavaScript获取数据并将其提供给导入脚本——但我更愿意避免使用此类解决方案。另外,因为触发导入过程的浏览器交互将来可能会被cron作业替代

    API密钥似乎正是我想要的,但是来自浏览器的GET请求失败

    获取请求:

    https://www.googleapis.com/analytics/v3/data/ga
      ?ids=ga:[profile ID]
      &start-date=2013-01-01&end-date=2013-01-05
      &metrics=ga:visits
      &key=[the API key]
    
    {
      error: {
      errors: [
        {
          domain: "global",
          reason: "required",
          message: "Login Required",
          locationType: "header",
          location: "Authorization"
        }
      ],
      code: 401,
      message: "Login Required"
      }
    }
    
    响应:

    https://www.googleapis.com/analytics/v3/data/ga
      ?ids=ga:[profile ID]
      &start-date=2013-01-01&end-date=2013-01-05
      &metrics=ga:visits
      &key=[the API key]
    
    {
      error: {
      errors: [
        {
          domain: "global",
          reason: "required",
          message: "Login Required",
          locationType: "header",
          location: "Authorization"
        }
      ],
      code: 401,
      message: "Login Required"
      }
    }
    
    不过,URL应该很好。除了关键参数外,它与生成的参数相同,该参数也在工作(在这种情况下使用AOuth2)。API密钥是新的

    然后再次生成一个新的API密钥让我面临下一个不便,那就是该密钥显然只在一天内有效


    所以最后我的问题是:


    是否可以在上述场景中获取数据,而无需手动验证或每天生成API密钥?

    我认为要实现这一点,您需要使用OAuth,但只需稍加修改即可从服务器上运行它。Google将此身份验证方法称为“”

    如该页所述,您可以使用PHP客户端库来完成身份验证。客户端库位于

    关于如何使用此客户端库的示例位于同一项目的。注意,您必须对代码进行一些修改,正如注释所说的那样,将令牌存储在db中并定期刷新它

    <?php
    require_once 'google-api-php-client/src/Google_Client.php';
    require_once 'google-api-php-client/src/contrib/Google_PlusService.php';
    
    // Set your cached access token. Remember to replace $_SESSION with a
    // real database or memcached.
    session_start();
    
    $client = new Google_Client();
    $client->setApplicationName('Google+ PHP Starter Application');
    // Visit https://code.google.com/apis/console?api=plus to generate your
    // client id, client secret, and to register your redirect uri.
    $client->setClientId('insert_your_oauth2_client_id');
    $client->setClientSecret('insert_your_oauth2_client_secret');
    $client->setRedirectUri('insert_your_oauth2_redirect_uri');
    $client->setDeveloperKey('insert_your_simple_api_key');
    $plus = new Google_PlusService($client);
    
    if (isset($_GET['code'])) {
      $client->authenticate();
      $_SESSION['token'] = $client->getAccessToken();
      $redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
      header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
    }
    
    if (isset($_SESSION['token'])) {
      $client->setAccessToken($_SESSION['token']);
    }
    
    if ($client->getAccessToken()) {
      $activities = $plus->activities->listActivities('me', 'public');
      print 'Your Activities: <pre>' . print_r($activities, true) . '</pre>';
    
      // We're not done yet. Remember to update the cached access token.
      // Remember to replace $_SESSION with a real database or memcached.
      $_SESSION['token'] = $client->getAccessToken();
    } else {
      $authUrl = $client->createAuthUrl();
      print "<a href='$authUrl'>Connect Me!</a>";
    }
    

    我也有类似的设置。您没有意识到的是,您可以指定一个
    http://localhost
    http://127.0.0.1
    或任何其他内容作为源和回调URL。您需要在本地服务器上设置一些web界面,为具有GA访问权限的用户启动OAuth设置。请注意,这是一次。回调处理程序必须如下所示:

    注意:这里使用的库与前面的答案相同,详细代码在包装器中

    try {
        $token = GAPI::readToken(); //read from persistent storage
    } catch (Exception $e) {
        $token = FALSE;
    }
    
    if($token == FALSE) {
        $logger->crit("Token not set before running cron!");
        echo "Error: Token not set before running cron!";
        exit;
    }
    
    $client = GAPI::init(); //instance of Google_Client
    $client->setAccessToken($token); 
    
    一旦您保存了已保存的令牌,您必须在向GA请求获取分析数据之前在客户端设置它。比如:

    $client = new Google_Client();
    $client->setApplicationName(self::APP_NAME);
    
    $client->setClientId(self::CLIENT_ID);
    $client->setClientSecret(self::CLIENT_SECRET);
    $client->setRedirectUri(self::REDIRECT_URI);
    $client->setDeveloperKey(self::DEVELOPER_KEY);
    
    //to specify that the token is stored offline
    $client->setAccessType('offline');
    
    //all results will be objects
    $client->setUseObjects(true);
    
    //tell that this app will RO from Analytics
    $client->setScopes('https://www.googleapis.com/auth/analytics.readonly');
    
    return $client;
    
    GAPI::init()
    的实现如下:

    $client = new Google_Client();
    $client->setApplicationName('test');
    
    $client->setAssertionCredentials(
        new Google_AssertionCredentials(
            EMAIL,
            array('https://www.googleapis.com/auth/analytics.readonly'),
            file_get_contents(PRIVATE_KEY_FILEPATH)
        )
    );
    $client->setClientId(CLIENT_ID);
    $client->setAccessType('offline_access');
    
    $analytics = new Google_AnalyticsService($client);
    

    My mysql表包含诸如
    id、title、send\u to\u email、frequency、dimensions、metrics、filters、profile\u id等列,这些列完全定义了从GA生成的每个报告。您可以使用、和您已经知道的

    如前所述,使用此库: 但是,不要使用oauth,而是从api控制台创建一个服务帐户(只需选择服务器应用程序)。这将为您提供一个客户端id、一封标识服务帐户的电子邮件以及保存私钥的*.p12文件

    然后,您必须将服务帐户(电子邮件)作为管理员用户添加到您的分析中,以获取所需的数据

    要使用该服务,请执行以下操作:

    $analytics->data_ga->get(PROFILE_ID, $date_from, $date_to, $metrics, $optParams)
    
    要获取一些数据:


    有关详细信息,请查看api文档。另外,请注意,有一个查询上限(除非您付费)

    请仔细查看可用的查询。有两个应该适合你。Web服务器和服务帐户。使用该方法,您仍然必须通过oAuth,但您只需执行一次。然后,您将获得一个刷新令牌,可以在需要时使用该令牌生成更多访问令牌,而无需再次通过oAuth流。[Service Accounts](好的,也许是这样。但是我仍然对一个完整的答案感兴趣,这个答案也涉及到其他提到的问题。我没有问题中提到的“insert_your_oauth2_redirect_uri”。要接受这个答案,你必须解释如何处理这个问题(没有重定向uri)或者我对这个URI的含义理解有误的方式和原因。另外,我更喜欢一个不复制粘贴的Google示例代码,而是一个如何获取一些有意义的东西的工作示例,比如一些URL(如foo/)的访问次数。在你的设置中,请求的URI不只是你的计算机地址吗e用户身份验证后,我认为它不会验证URL。由于没有验证,您可以指定。这是一个很好的观点。似乎我误解了此URL.np的含义。很高兴提供帮助。@Birla在他的回答中做了一些非常类似的事情。我不想复制他的代码,但如果您发现h,可以随意将他的回答标记为答案答案是否更容易理解(他说的和我上面的评论一样。)阻止我使用这种方法的是灵活性的丧失。如果我必须迁移到另一个GA帐户,我需要获得新的服务凭据,或者如果我必须从两个不同的帐户获取数据,我将不得不使用欺骗。最后这只是一个选择,因为我已经使用了这两个帐户!我对这个答案给予了奖励,因为(至少表面上)它似乎比其他答案更直接地解决了我的问题。我还没有找到更多的时间来处理这个项目。一旦我确定如何在我的情况下完成这项工作,我将标记答案或自己写一个。