我正在尝试通过PHP使用Google API来检索日历事件。我的环境
我使用以下代码作为测试代码(test2.php):
<html>
<head>
<title>PHP Test</title>
</head>
<body>
This is a line of text in test2.php
<?php
require_once 'C:\PHP\vendor\autoload.php';
$client = new Google_Client();
// $credentialsJson should contain the path to the json file downloaded from the API site
$credentialsJson = 'C:\Apache24\htdocs\credentials.json';
$credentials = $client->loadServiceAccountJson(
$credentialJson,
'https://www.googleapis.com/auth/calendar'
);
$client->setAssertionCredentials($credentials);
$service = new Google_Service_Calendar($client);
// $calendarId should contain the calendar id found on the settings page of the calendar
$calendarId = '*****myCalendarID*****';
$events = $service->events->listEvents($calendarId);
echo $events;
?>
</body>
</html>
我将test2.php文件放在C:\ Apache24 \ htdocs中。
当我浏览到:localhost / test2.php时,浏览器显示:
This is a line of text in test2.php
Fatal error: Uncaught Error: Call to undefined method Google_Client::loadServiceAccountJson() in C:\Apache24\htdocs\test2.php:14 Stack trace: #0 {main} thrown in C:\Apache24\htdocs\test2.php on line 14
为什么找不到方法“ loadServiceAccountJson”? 感谢您的关注。
答案 0 :(得分:0)
我不确定您要遵循的教程。这是我使用的代码。
require_once __DIR__ . '/vendor/autoload.php';
// Use the developers console and download your service account
// credentials in JSON format. Place the file in this directory or
// change the key file location if necessary.
putenv('GOOGLE_APPLICATION_CREDENTIALS='.__DIR__.'/service-account.json');
/**
* Gets the Google client refreshing auth if needed.
* Documentation: https://developers.google.com/identity/protocols/OAuth2ServiceAccount
* Initializes a client object.
* @return A google client object.
*/
function getGoogleClient() {
return getServiceAccountClient();
}
/**
* Builds the Google client object.
* Documentation: https://developers.google.com/api-client-library/php/auth/service-accounts
* Scopes will need to be changed depending upon the API's being accessed.
* array(Google_Service_Analytics::ANALYTICS_READONLY, Google_Service_Analytics::ANALYTICS)
* List of Google Scopes: https://developers.google.com/identity/protocols/googlescopes
* @return A google client object.
*/
function getServiceAccountClient() {
try {
// Create and configure a new client object.
$client = new Google_Client();
$client->useApplicationDefaultCredentials();
$client->addScope([YOUR SCOPES HERE]);
return $client;
} catch (Exception $e) {
print "An error occurred: " . $e->getMessage();
}
}
注意:如果您使用的不是服务帐户,则会从该服务帐户的Google日历帐户请求数据。如果您希望它可以访问您的个人日历,则必须像其他任何用户一样,获取服务帐户的电子邮件地址并与其共享日历。