-
-
Save alinademi/74ad04325fb791154fed936c1dd243c8 to your computer and use it in GitHub Desktop.
Interacting with Google API's using their PHP libraries is a nightmare. Skip the headache by authorizing a Guzzle client and make raw HTTP requests instead!
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$key_file_path = __DIR__ . '/service-account-credentials.json'; | |
$google_client = new \Google_Client(); | |
$google_client->setAuthConfig( $key_file_path ); | |
// Set the scopes of whatever you need access to | |
// See https://developers.google.com/identity/protocols/oauth2/scopes | |
$google_client->setScopes( array( 'https://www.googleapis.com/auth/analytics.readonly' ) ); | |
$http_client = $client->authorize(); | |
// Now you have a Guzzle http client authorized to make requests to Google | |
$body_args = array( | |
'reportRequests' => array( | |
'viewId' => 'xxxxxx', | |
'dateRanges' => array( | |
array( | |
'startDate' => '7DaysAgo', | |
'endDate' => 'today', | |
), | |
), | |
'metrics' => array( | |
array( | |
'expression' => 'ga:sessions', | |
), | |
), | |
), | |
); | |
$args = array( | |
'body' => json_encode( $body_args ), | |
); | |
$response = $ga->request( 'POST', 'https://analyticsreporting.googleapis.com/v4/reports:batchGet', $args ); | |
$raw_json = (string) $response->getBody(); | |
$json = json_decode( $raw_json ); | |
// Admire your glorious reward! | |
var_dump( $json ); | |
// More Documention!!! | |
// Google Analytics reports.batchGet - https://developers.google.com/analytics/devguides/reporting/core/v4/rest/v4/reports/batchGet | |
// Guzzle Request Options - https://docs.guzzlephp.org/en/stable/request-options.html |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment