問題描述
我正在運行以下 PHP 代碼,使用此處找到的客戶端庫:https://code.google.com/p/google-api-php-client/.我沒有收到任何此代碼的錯誤,但是當我調用 getAccessToken()
時,它返回 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.
我已允許在我的個人日歷上訪問此服務帳戶,并已通過 API 控制臺授予對項目的完全訪問權限.
I have allowed access to this service account on my personal calendar, and have granted full access to the project via the API Console.
有什么想法嗎?
require_once 'google-api-php-client/src/Google_Client.php';
const CLIENT_ID = 'blahblahblah';
const SERVICE_ACCOUNT_NAME = 'blahblahblah@developer.gserviceaccount.com';
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());
推薦答案
出于某種原因,這似乎有效:
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 = 'blahblahblah@developer.gserviceaccount.com';
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!
這篇關于使用服務帳戶,getAccessToken() 返回 null的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!