6

I am running the following PHP code, using the client libraries found here: https://code.google.com/p/google-api-php-client/. I do not get any errors for any of this code, but when I call getAccessToken(), it returns null.

I have allowed access to this service account on my personal calendar, and have granted full access to the project via the API Console.

Any ideas?

require_once 'google-api-php-client/src/Google_Client.php'; const CLIENT_ID = 'blahblahblah'; const SERVICE_ACCOUNT_NAME = '[email protected]'; const KEY_FILE = 'path/to/privatekey.p12'; $google_client = new Google_Client(); // created only to initialized static dependencies $client = new Google_OAuth2(); // you really just need Google_OAuth2 $key = file_get_contents(KEY_FILE); $client->setAssertionCredentials( new Google_AssertionCredentials( SERVICE_ACCOUNT_NAME, array('https://www.googleapis.com/auth/calendar'), $key ) ); var_dump($client->getAccessToken()); 

1 Answer 1

3

For some reason, this seemed to work:

require_once 'google-api-php-client/src/Google_Client.php'; const CLIENT_ID = 'blahblahblah'; const SERVICE_ACCOUNT_NAME = '[email protected]'; const KEY_FILE = 'path/to/privatekey.p12'; const CALENDAR_SCOPE = "https://www.googleapis.com/auth/calendar"; $key = file_get_contents(KEY_FILE); $auth = new Google_AssertionCredentials( SERVICE_ACCOUNT_NAME, array(CALENDAR_SCOPE), $key ); $client = new Google_Client(); $client->setScopes(array(CALENDAR_SCOPE)); $client->setAssertionCredentials($auth); $client->getAuth()->refreshTokenWithAssertion(); $accessToken = $client->getAccessToken(); $client->setClientId(CLIENT_ID); 

If someone can explain why this worked, please edit this answer or comment!

Sign up to request clarification or add additional context in comments.

2 Comments

Not sure either. I am using your code with credit at gist.github.com/fulldecent/6728257 and FYI the line setScopes is not necessary
getAccessToken() returns the current access token, which does not exist until you call refreshTokenWithAssertion() (to initialize it) or setAccessToken() (if you recovered a previous access token you'd want to use).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.