Google Analytics API v3 authorization to allow access to my data

前端 未结 3 809
既然无缘
既然无缘 2021-02-13 14:14

I am developing an app that allows users to see my own Google Analytics Data using Google API v3. Everything I researched seems to indicate that users need to login into their G

相关标签:
3条回答
  • 2021-02-13 15:14

    You can use a refresh token for offline access. Once you get the refresh token, you can save it to a file or database and use that to access the data without an authorization redirect.

    See Using a Refresh Token in the docs.

    Also see: How can we access specific Google Analytics account data using API?

    0 讨论(0)
  • 2021-02-13 15:16

    I believe what you want to do is set up a Service Account: https://developers.google.com/analytics/devguides/config/mgmt/v3/mgmtAuthorization

    "Useful for automated/offline/scheduled access to Google Analytics data for your own account. For example, to build a live dashboard of your own Google Analytics data and share it with other users.

    There are a few steps you need to follow to configure service accounts to work with Google Analytics:

    1. Register a project in the APIs Console.
    2. In the Google APIs Console, under the API Access pane, create a client ID with the Application Type set to Service Account.
    3. Sign-in to Google Analytics and navigate to the Admin section.
    4. Select the account for which you want the application to have access to.
    5. Add the email address, from the Client ID created in the APIs Console from step #2, as a user of the selected Google Analytics account.
    6. Follow the instructions for Service Accounts to access Google Analytics data: https://developers.google.com/accounts/docs/OAuth2ServiceAccount"
    0 讨论(0)
  • 2021-02-13 15:18

    Here is a full Google Analytics reporting example implementation with service account including setup notes. Just wrote it after reading your question, I had the same problem.

    <?php
    // Service account code from http://stackoverflow.com/questions/18258593/using-a-service-account-getaccesstoken-is-returning-null
    // Analytics code from https://code.google.com/p/google-api-php-client/source/browse/trunk/examples/analytics/simple.php?r=474
    
    require_once 'google-api-php-client/src/Google_Client.php';
    require_once 'google-api-php-client/src/contrib/Google_AnalyticsService.php';
    
    // Set your client id, service account name (AKA "EMAIL ADDRESS"), and the path to your private key.
    // For more information about obtaining these keys, visit:
    // https://developers.google.com/console/help/#service_accounts
    const CLIENT_ID = 'CLIENT ID';
    const SERVICE_ACCOUNT_NAME = 'SERVICE ACCOUNT NAME (IS "EMAIL ADDRESS")';
    const KEY_FILE = 'KEY FILE';
    const SCOPE = 'https://www.googleapis.com/auth/analytics.readonly';
    
    // OPEN GOOGLE ANALYTICS AND GRANT ACCESS TO YOUR PROFILE, THEN PASTE IN YOUR SERVICE_ACCOUNT_NAME
    
    $key = file_get_contents(KEY_FILE);
    $auth = new Google_Auth_AssertionCredentials(
        SERVICE_ACCOUNT_NAME,
        array(SCOPE),
        $key
    );
    
    $client = new Google_Client();
    $client->setScopes(array(SCOPE));
    $client->setAssertionCredentials($auth);
    $client->getAuth()->refreshTokenWithAssertion();
    $accessToken = $client->getAccessToken();
    $client->setClientId(CLIENT_ID);
    $service = new Google_Service_Analytics($client);
    
    ?>
    <!DOCTYPE html>
    <html>
      <head>
        <title>Google Experiments Dashboard</title>
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <link href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet" media="screen">
      </head>
      <body class="container">
        <h1>Your experiments</h1>
        <table class="table"><tr><th><th>Experiment<th>Page<th>Started<th>Status
    <?php
    $progressClasses = array('progress-bar progress-bar-success','progress-bar progress-bar-info','progress-bar progress-bar-warning', 'progress-bar progress-bar-danger');
    $profiles = $service->management_profiles->listManagementProfiles("~all", "~all");
    
    foreach ($profiles['items'] as $profile) {
      $experiments = $service->management_experiments->listManagementExperiments($profile['accountId'], $profile['webPropertyId'], $profile['id']);
    
      foreach ($experiments['items'] as $experiment) {
        echo "<tr>";
        if ($experiment['status'] == 'RUNNING')
          echo '<td><a class="btn btn-xs btn-success"><i class="glyphicon glyphicon-ok"></i></a>';
        else
          echo '<td><a class="btn btn-xs btn-danger"><i class="glyphicon glyphicon-remove"></i></a>';
        $expHref = "https://www.google.com/analytics/web/?pli=1#siteopt-experiment/siteopt-detail/a{$profile['accountId']}w{$experiment['internalWebPropertyId']}p{$experiment['profileId']}/%3F_r.drilldown%3Danalytics.gwoExperimentId%3A{$experiment['id']}/";
        echo "<td><a href='$expHref' target='_blank'>{$experiment['name']}</a>";
        echo "<td>{$experiment['variations'][0]['url']}";
        echo "<td>".date('Y-m-d',strtotime($experiment['startTime']));
        echo "<td>";
    
        echo '<div class="progress" style="width:400px">';
        foreach ($experiment['variations'] as $i => $variation) {
          echo '<a href="'.$variation['url'].'" target="_blank"><div class="'.$progressClasses[$i].'" role="progressbar" style="width: '.(100*$variation['weight']).'%">'.$variation['name'].'</div></a>';
        }
        echo '</div>';        
      }
    }
    ?>
    

    Code with more documentation at https://gist.github.com/fulldecent/6728257

    0 讨论(0)
提交回复
热议问题