我希望你能帮助我 .
我正在尝试使用 Oauth2 身份验证连接到Google(日历)API .
为此我遵循了以下步骤:
-
通过Google Developers控制台注册应用
-
使用composer安装客户端库(google-api-php-client)
-
在供应商文件夹中放置以下脚本:
require_once 'autoload.php';
require('google/apiclient-services/src/Google/Service/Oauth2.php');
session_start();
// ******************************************************** //
// Get these values from https://console.developers.google.com
// Be sure to enable the Analytics API
// ******************************************************** //
$client_id = 'myclientid';
$client_secret = 'myclientsecret';
$redirect_uri = 'https://domain.nl/dev/vendor/google/apiclient-services/src/Google/Service/Oauth2.php'; //identical as in Google console
$client = new Google_Client();
$client->setApplicationName("Client_Library_Examples");
$client->setClientId($client_id);
$client->setClientSecret($client_secret);
$client->setRedirectUri($redirect_uri);
$client->setAccessType('offline'); // Gets us our refreshtoken
$client->setScopes(array('https://www.googleapis.com/auth/calendar.readonly'));
//For loging out.
if (isset($_GET['logout'])) {
unset($_SESSION['token']);
}
// Step 2: The user accepted your access now you need to exchange it.
if (isset($_GET['code'])) {
$client->authenticate($_GET['code']);
$_SESSION['token'] = $client->getAccessToken();
$redirect = 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
}
// Step 1: The user has not authenticated we give them a link to login
if (!isset($_SESSION['token'])) {
$authUrl = $client->createAuthUrl();
print "Connect Me!";
}
// Step 3: We have access we can now create our service
if (isset($_SESSION['token'])) {
$client->setAccessToken($_SESSION['token']);
print "LogOut ";
$service = new Google_Service_Calendar($client);
$calendarList = $service->calendarList->listCalendarList();;
while(true) {
foreach ($calendarList->getItems() as $calendarListEntry) {
echo $calendarListEntry->getSummary()." \n";
// get events
$events = $service->events->listEvents($calendarListEntry->id);
foreach ($events->getItems() as $event) {
echo "-----".$event->getSummary()." ";
}
}
$pageToken = $calendarList->getNextPageToken();
if ($pageToken) {
$optParams = array('pageToken' => $pageToken);
$calendarList = $service->calendarList->listCalendarList($optParams);
} else {
break;
}
}
}
不幸的是,我在点击Authentication的"accept"按钮后立即收到错误:
Fatal error: Class 'Google_Service' not found in /home/user/domains/domain.nl/private_html/dev/vendor/google/apiclient-services/src/Google/Service/Oauth2.php on line 32
Google research到目前为止没有帮助 .
可能的解决方案:
- 正确设置自动加载路径 . 校验 .
require_once 'autoload.php';
-
运行支持的PHP版本 . 检查(尝试5.6 7.1) .
-
检查composer.json中的库与实际自动加载的库之间是否存在不同之处 . 校验 .
感谢您的帮助!
1 回答
更新:这已得到修复 . 我使用Oauth2.php作为我的redirect_url而不是返回我的脚本 . 初学者错了:)