Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
379 views
in Technique[技术] by (71.8m points)

php - Using a Service Account, getAccessToken() is returning null

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());
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...