googleapis / google-api-php-client

A PHP client library for accessing Google APIs
http://googleapis.github.io/google-api-php-client/
Apache License 2.0
9.35k stars 3.53k forks source link

Google API Client Auth Exception #795

Closed sivabalan02 closed 8 years ago

sivabalan02 commented 8 years ago

Hi all, I am using google api on my yii2 project which gives an error as follows:

Google_Auth_Exception

Error refreshing the OAuth2 token, message: '{ "error" : "invalid_grant" }'

in the file vendor/google/apiclient/src/Google/Auth/OAuth2.php

I gave the service account email as my google's developer email address

Please someone help me get out of this

This is my code:

<?php 
use google\apiclient\src\Google;
$this->title = "Google Analytics";
require_once $_SERVER['DOCUMENT_ROOT'] . '/vendor/autoload.php';
//require_once $_SERVER['DOCUMENT_ROOT'] . '/vendor/google/apiclient/src/Google/  autoload.php';
//echo BASE_URL . "/backend/web/themes/default/MatchBox-15a5a6b9c872.p12";
//echo $_SERVER['DOCUMENT_ROOT'] . 'backend/modules/admin/views/default/MatchBox-15a5a6b9c872.p12';
//die;
    function getService()
    {
        // Creates and returns the Analytics service object.

        // Load the Google API PHP Client Library.
        //require_once 'google-api-php-client/src/Google/autoload.php';

        // Use the developers console and replace the values with your
        // service account email, and relative location of your key file.
        $service_account_email = 'sivakumar750@gmail.com';
        $key_file_location = BASE_URL . "/backend/web/themes/default/MatchBox-15a5a6b9c872.p12";

        // Create and configure a new client object.
        $client = new Google_Client();
        $client->setApplicationName("HelloAnalytics");
        $analytics = new Google_Service_Analytics($client);

        // Read the generated client_secrets.p12 key.
        $key = file_get_contents($key_file_location);
        $cred = new Google_Auth_AssertionCredentials($service_account_email, array(Google_Service_Analytics::ANALYTICS_READONLY), $key);
        $client->setAssertionCredentials($cred);

        if($client->getAuth()->isAccessTokenExpired()) 
            $client->getAuth()->refreshTokenWithAssertion($cred);

        return $analytics;
    }

    function getFirstprofileId(&$analytics) 
    {
        // Get the user's first view (profile) ID.

        // Get the list of accounts for the authorized user.
        $accounts = $analytics->management_accounts->listManagementAccounts();

        if (count($accounts->getItems()) > 0) 
        {
            $items = $accounts->getItems();
            $firstAccountId = $items[0]->getId();

            // Get the list of properties for the authorized user.
            $properties = $analytics->management_webproperties
            ->listManagementWebproperties($firstAccountId);

            if (count($properties->getItems()) > 0) 
            {
                $items = $properties->getItems();
                $firstPropertyId = $items[0]->getId();

                // Get the list of views (profiles) for the authorized user.
                $profiles = $analytics->management_profiles
                ->listManagementProfiles($firstAccountId, $firstPropertyId);

                if (count($profiles->getItems()) > 0) 
                {
                    $items = $profiles->getItems();

                    // Return the first view (profile) ID.
                    return $items[0]->getId();
                } 
                else 
                    throw new Exception('No views (profiles) found for this user.');
            } 
            else 
                throw new Exception('No properties found for this user.');
        } 
        else 
            throw new Exception('No accounts found for this user.');
    }

    function getResults(&$analytics, $profileId) 
    {
        // Calls the Core Reporting API and queries for the number of sessions
        // for the last seven days.
        return $analytics->data_ga->get(
        'ga:' . $profileId,
        '7daysAgo',
        'today',
        'ga:sessions');
    }

    function printResults(&$results) 
    {
        // Parses the response from the Core Reporting API and prints
        // the profile name and total sessions.
        if (count($results->getRows()) > 0) 
        {
            // Get the profile name.
            $profileName = $results->getProfileInfo()->getProfileName();

            // Get the entry for the first entry in the first row.
            $rows = $results->getRows();
            $sessions = $rows[0][0];

            // Print the results.
            print "First view (profile) found: $profileName\n";
            print "Total sessions: $sessions\n";
        }
        else 
            print "No results found.\n";
    }

    $analytics = getService();
    $profile = getFirstProfileId($analytics);
    $results = getResults($analytics, $profile);
    printResults($results);
?>
bshaffer commented 8 years ago

Can you paste your code so we can see what you might be doing wrong? From the information you've provided, there really isn't any way we can help.

sivabalan02 commented 8 years ago

Hai bshaffer, sorry for late reply. I updated the issue with the code itself

bshaffer commented 8 years ago

@sivabalan02 I am not sure where the problem is... however, this flow has been deprecated in favor of the v2.0 version of this library, which you can learn more about here.

I suggest trying to pull down the latest version and using the new method of assertion credentials. Note you'll need to use a json credentials file instead of the p12 you're currently using.

daftspunk commented 8 years ago

@sivabalan02 After extensive testing, it looks like newly generated P12 files are no longer usable in v1 at all. Tested Google_Service_Analytics::ANALYTICS_READONLY scope only. Even the JSON files using v1 don't seem to play nicely.

Here is the code and documentation changes we used for the upgrade from 1.0 to 2.0, it might help you.

bshaffer commented 8 years ago

@daftspunk Interesting. What is the error you are receiving, and does it seem to be an issue with the PHP Library or with the Google APIs?

daftspunk commented 8 years ago

All old P12 files that were set up prior to the Google Developer Tools UI changes are working fine with the v1 library. Any new accounts with P12 files receive the invalid_grant error even using the identical PHP code base. It leads me to believe it is an issue with the API.

When attempting to use the JSON file for auth, v1 was looking for a key called "client_secret" in the JSON file which is missing from those newly generated by the Dev Tools. Among other missing keys, it outputs error Invalid client secret JSON file. I do not have an old [working] JSON file from the previous Dev Tools to compare with.

bshaffer commented 8 years ago

Ahh, interesting. I know the p12 method is deprecated, so it is very likely those specific APIs have been intentionally phased out for all but legacy credentials.