Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save xus/966d230535ad1e802daac64feda2ed04 to your computer and use it in GitHub Desktop.
Save xus/966d230535ad1e802daac64feda2ed04 to your computer and use it in GitHub Desktop.
Oauth example for PHP and the Google Analytics reporting api v4 with pagination.
For service account auth include:
require_once __DIR__ . '/ServiceAccount.php';
For Oauth2 include:
require_once __DIR__ . '/Oauth2Authentication.php';
Note: To reset the auth for oauth to just unset the sessions
unset($_SESSION['access_token']);
unset($_SESSION['refresh_token']);
<?php
// Copyright 2017 DAIMTO ([Linda Lawton](https://twitter.com/LindaLawtonDK)) : [www.daimto.com](http://www.daimto.com/)
//
// 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.
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by DAIMTO-Google-apis-Sample-generator 1.0.0
// Template File Name: Oauth2Authentication.tt
// Build date: 08/30/2017 13:16:22
// PHP generator version: 1.0.0
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
// About
//
// Unofficial sample for the Drive v3 API for PHP.
// This sample is designed to be used with the Google PHP client library. (https://github.com/google/google-api-php-client)
//
// API Description: Manages files in Drive including uploading, downloading, searching, detecting changes, and updating sharing permissions.
// API Documentation Link https://developers.google.com/drive/
//
// Discovery Doc https://www.googleapis.com/discovery/v1/apis/Drive/v3/rest
//
//------------------------------------------------------------------------------
// Installation
//
// The preferred method is via https://getcomposer.org. Follow the installation instructions https://getcomposer.org/doc/00-intro.md
// if you do not already have composer installed.
//
// Once composer is installed, execute the following command in your project root to install this library:
//
// composer require google/apiclient:^2.0
//
//------------------------------------------------------------------------------
// Load the Google API PHP Client Library.
require_once __DIR__ . '/vendor/autoload.php';
/**
* Gets the Google client refreshing auth if needed.
* Documentation: https://developers.google.com/identity/protocols/OAuth2
* Initializes a client object.
* @return A google client object.
*/
function getGoogleClient() {
$client = getOauth2Client();
// Refresh the token if it's expired.
if ($client->isAccessTokenExpired()) {
$client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
file_put_contents($credentialsPath, json_encode($client->getAccessToken()));
}
return $client;
}
/**
* Builds the Google client object.
* Documentation: https://developers.google.com/identity/protocols/OAuth2
* Scopes will need to be changed depending upon the API's being accessed.
* @return A google client object.
*/
function buildClient(){
$client = new Google_Client();
$client->setAccessType("offline"); // offline access. Will result in a refresh token
$client->setIncludeGrantedScopes(true); // incremental auth
$client->setAuthConfig(__DIR__ . '/client_secrets.json');
$client->addScope(array(Google_Service_Analytics::ANALYTICS_READONLY, Google_Service_Analytics::ANALYTICS));
$client->setRedirectUri(getRedirectUri());
//$client->setRedirectUri((isset($_SERVER['HTTPS']) ? "https" : "http") . '://' . $_SERVER['HTTP_HOST'] . $folder. '/oauth2callback.php');
return $client;
}
/**
* Builds the redirect uri.
* Documentation: https://developers.google.com/api-client-library/python/auth/installed-app#choosingredirecturi
* Hostname and current server path are needed to redirect to oauth2callback.php
* @return A redirect uri.
*/
function getRedirectUri(){
//Building Redirect URI
$url = $_SERVER['REQUEST_URI']; //returns the current URL
if(strrpos($url, '?') > 0)
$url = substr($url, 0, strrpos($url, '?') ); // Removing any parameters.
$folder = substr($url, 0, strrpos($url, '/') ); // Removeing current file.
return (isset($_SERVER['HTTPS']) ? "https" : "http") . '://' . $_SERVER['HTTP_HOST'] . $folder. '/oauth2callback.php';
}
/**
* Authenticating to Google using Oauth2
* Documentation: https://developers.google.com/identity/protocols/OAuth2
* Returns a Google client with refresh token and access tokens set.
* If not authencated then we will redirect to request authencation.
* @return A google client object.
*/
function getOauth2Client() {
try {
$client = buildClient();
// Set the refresh token on the client.
if (isset($_SESSION['refresh_token']) && $_SESSION['refresh_token']) {
$client->refreshToken($_SESSION['refresh_token']);
}
// If the user has already authorized this app then get an access token
// else redirect to ask the user to authorize access to Google Analytics.
if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
// Set the access token on the client.
$client->setAccessToken($_SESSION['access_token']);
// Refresh the access token if it's expired.
if ($client->isAccessTokenExpired()) {
$client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
$client->setAccessToken($client->getAccessToken());
$_SESSION['access_token'] = $client->getAccessToken();
}
return $client;
} else {
// We do not have access request access.
header('Location: ' . filter_var( $client->getRedirectUri(), FILTER_SANITIZE_URL));
}
} catch (Exception $e) {
print "An error occurred: " . $e->getMessage();
}
}
?>
<?php
// Copyright 2017 DAIMTO ([Linda Lawton](https://twitter.com/LindaLawtonDK)) : [www.daimto.com](http://www.daimto.com/)
//
// 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.
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by DAIMTO-Google-apis-Sample-generator 1.0.0
// Template File Name: ServiceAccount.tt
// Build date: 08/30/2017 13:16:24
// PHP generator version: 1.0.0
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
// About
//
// Unofficial sample for the Drive v3 API for PHP.
// This sample is designed to be used with the Google PHP client library. (https://github.com/google/google-api-php-client)
//
// API Description: Manages files in Drive including uploading, downloading, searching, detecting changes, and updating sharing permissions.
// API Documentation Link https://developers.google.com/drive/
//
// Discovery Doc https://www.googleapis.com/discovery/v1/apis/Drive/v3/rest
//
//------------------------------------------------------------------------------
// Installation
//
// The preferred method is via https://getcomposer.org. Follow the installation instructions https://getcomposer.org/doc/00-intro.md
// if you do not already have composer installed.
//
// Once composer is installed, execute the following command in your project root to install this library:
//
// composer require google/apiclient:^2.0
//
//------------------------------------------------------------------------------
// Load the Google API PHP Client Library.
require_once __DIR__ . '/vendor/autoload.php';
require_once __DIR__ . '/Oauth2Authentication.php';
// Start a session to persist credentials.
session_start();
// Handle authorization flow from the server.
if (! isset($_GET['code'])) {
$client = buildClient();
$auth_url = $client->createAuthUrl();
header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL));
} else {
$client = buildClient();
$client->authenticate($_GET['code']); // Exchange the authencation code for a refresh token and access token.
// Add access token and refresh token to seession.
$_SESSION['access_token'] = $client->getAccessToken();
$_SESSION['refresh_token'] = $client->getRefreshToken();
//Redirect back to main script
$redirect_uri = str_replace("oauth2callback.php",$_SESSION['mainScript'],$client->getRedirectUri());
header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}
?>
<?php
// Copyright 2017 DAIMTO ([Linda Lawton](https://twitter.com/LindaLawtonDK)) : [www.daimto.com](http://www.daimto.com/)
//
// 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.
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by DAIMTO-Google-apis-Sample-generator 1.0.0
// Template File Name: methodTemplate.tt
// Build date: 08/30/2017 13:16:07
// PHP generator version: 1.0.0
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
// About
//
// Unofficial sample for the Analyticsreporting v4 API for PHP.
// This sample is designed to be used with the Google PHP client library. (https://github.com/google/google-api-php-client)
//
// API Description: Accesses Analytics report data.
// API Documentation Link https://developers.google.com/analytics/devguides/reporting/core/v4/
//
// Discovery Doc https://www.googleapis.com/discovery/v1/apis/Analyticsreporting/v4/rest
//
//------------------------------------------------------------------------------
// Installation
//
// The preferred method is via https://getcomposer.org. Follow the installation instructions https://getcomposer.org/doc/00-intro.md
// if you do not already have composer installed.
//
// Once composer is installed, execute the following command in your project root to install this library:
//
// composer require google/apiclient:^2.0
//
//------------------------------------------------------------------------------
// Load the Google API PHP Client Library.
require_once __DIR__ . '/vendor/autoload.php';
//require_once __DIR__ . '/ServiceAccount.php';
require_once __DIR__ . '/Oauth2Authentication.php';
session_start();
//unset($_SESSION['access_token']);
//unset($_SESSION['refresh_token']);
$_SESSION['mainScript'] = basename($_SERVER['PHP_SELF']); // Oauth2callback.php will return here.
$client = getGoogleClient();
$service = new Google_Service_AnalyticsReporting($client);
// Create the DateRange object.
$dateRange = new Google_Service_AnalyticsReporting_DateRange();
$dateRange->setStartDate("2016-01-01");
$dateRange->setEndDate("2017-06-30");
// Create the Metrics objects.
$sessions = new Google_Service_AnalyticsReporting_Metric();
$sessions->setExpression("ga:sessions");
$sessions->setAlias("ga:sessions");
$users = new Google_Service_AnalyticsReporting_Metric();
$users->setExpression("ga:users");
$users->setAlias("ga:users");
$metrics = array($sessions,$users);
// Create the Dimensions objects.
$date = new Google_Service_AnalyticsReporting_Dimension();
$date->setName("ga:date");
$pagePath = new Google_Service_AnalyticsReporting_Dimension();
$pagePath->setName("ga:pagePath");
$dimensions = array($date,$pagePath);
// Create the ReportRequest object.
$request = new Google_Service_AnalyticsReporting_ReportRequest();
$request->setViewId("81692014");
$request->setPageSize("10000");
$request->setDateRanges($dateRange);
$request->setDimensions($dimensions);
$request->setMetrics($metrics);
// Create the report
$body = new Google_Service_AnalyticsReporting_GetReportsRequest();
$body->setReportRequests(array( $request));
$data = BatchGet($service, $body);
showData($data->reports[0]);
// Loop though first give pages of data.
$cnt = 0;
while ($data->reports[0]->nextPageToken > 0 && $cnt < 5) {
// There are more rows for this report. we apply the next page token to the page token of the orignal body.
$body->reportRequests[0]->setPageToken($data->reports[0]->nextPageToken);
$data = BatchGet($service, $body);
showData($data->reports[0]);
$cnt++;
}
function showData($data) {
?> <pre><table><?php
?><tr><?php // Header start row
for($i = 0; $i < sizeof($data->columnHeader->dimensions);$i++) {
?> <td> <?php print_r($data->columnHeader->dimensions[$i]); ?> </td> <?php
}
for($i = 0; $i < sizeof($data->columnHeader->metricHeader->metricHeaderEntries);$i++) {
?> <td> <?php print_r($data->columnHeader->metricHeader->metricHeaderEntries[$i]->name); ?> </td> <?php
}
?><tr><?php // Header row end
// Display data
for($i = 0; $i < sizeof($data->data->rows);$i++) {
?><tr><?php // Data row start
// Dimensions
for($d = 0; $d < sizeof($data->columnHeader->dimensions);$d++) {
?> <td> <?php print_r($data->data->rows[$i]->dimensions[$d]); ?> </td> <?php
}
// Metrics
for($m = 0; $m < sizeof($data->columnHeader->metricHeader->metricHeaderEntries);$m++) {
?> <td> <?php print_r($data->data->rows[$i]->metrics[0]->values[$m]); ?> </td> <?php
}
?><tr><?php // Header row end
}
?></table></pre><?php
}
function showText($data)
{
?> <pre> <?php print_r($data); ?> </pre> <?php
}
/**
* Returns the Analytics data.
* Documentation https://developers.google.com/analyticsreporting/v4/reference/reports/batchGet
* Generation Note: This does not always build corectly. Google needs to standardise things I need to figuer out which ones are wrong.
* @service Authenticated Analyticsreporting service.</param>
* @body A valid Analyticsreporting v4 body.</param>
* @return GetReportsResponseResponse</returns>
*/
function BatchGet($service, $body)
{
try
{
// Initial validation.
if ($service == null)
throw new Exception("service");
if ($body == null)
throw new Exception("body");
// Make the request.
return $service->reports->batchGet($body);
}
catch (Exception $ex)
{
throw new Exception("Request Reports.BatchGet failed.", $ex->getMessage());
}
}
?>
<?php
// Copyright 2017 DAIMTO ([Linda Lawton](https://twitter.com/LindaLawtonDK)) : [www.daimto.com](http://www.daimto.com/)
//
// 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.
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by DAIMTO-Google-apis-Sample-generator 1.0.0
// Template File Name: ServiceAccount.tt
// Build date: 08/30/2017 13:16:26
// PHP generator version: 1.0.0
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
// About
//
// Unofficial sample for the Analyticsreporting v4 API for PHP.
// This sample is designed to be used with the Google PHP client library. (https://github.com/google/google-api-php-client)
//
// API Description: Accesses Analytics report data.
// API Documentation Link https://developers.google.com/analytics/devguides/reporting/core/v4/
//
// Discovery Doc https://www.googleapis.com/discovery/v1/apis/Analyticsreporting/v4/rest
//
//------------------------------------------------------------------------------
// Installation
//
// The preferred method is via https://getcomposer.org. Follow the installation instructions https://getcomposer.org/doc/00-intro.md
// if you do not already have composer installed.
//
// Once composer is installed, execute the following command in your project root to install this library:
//
// composer require google/apiclient:^2.0
//
//------------------------------------------------------------------------------
// Load the Google API PHP Client Library.
require_once __DIR__ . '/vendor/autoload.php';
// Use the developers console and download your service account
// credentials in JSON format. Place them in this directory or
// change the key file location if necessary.
putenv('GOOGLE_APPLICATION_CREDENTIALS='.__DIR__.'/service-account.json');
$service = getAuthenticateServiceAccount();
/**
* Authenticating to Google using a Service account
* Documentation: https://developers.google.com/api-client-library/php/auth/service-accounts
* Initializes an Analyticsreporting.v4 service object.
*
* @return An authorized Analyticsreporting.v4 service object.
*/
function getAuthenticateServiceAccount() {
try {
// Create and configure a new client object.
$client = new Google_Client();
$client->useApplicationDefaultCredentials();
$client->addScope(Google_Service_Analytics::ANALYTICS);
return new Google_Service_AnalyticsReporting($client);
} catch (Exception $e) {
print "An error occurred: " . $e->getMessage();
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment