我可以使用我的php应用程序在谷歌日历添加事件吗?



是否可以在谷歌日历中添加/编辑/删除事件?因为我所完成的只是阅读我的事件。我启用了所有的作用域我可以找到关于日历API,但我仍然得到一个错误403关于"请求没有足够的身份验证范围/PERMISSION denied"。

我已经做了很多尝试来解决这个问题,每次我都遇到同样的问题。我正在使用OAuth 2.0客户端id凭证,我还有一个问题是我应该为授权重定向uri使用哪个url。

<?php
require __DIR__ . '/vendor/autoload.php';
/*
if (php_sapi_name() != 'cli') {
throw new Exception('This application must be run on the command line.');
}
*/
/**
* Returns an authorized API client.
* @return Google_Client the authorized client object
*/
function getClient()
{
$client = new Google_Client();
$client->setApplicationName('Google Calendar API PHP Quickstart');
$client->setScopes(Google_Service_Calendar::CALENDAR_READONLY);
$client->setAuthConfig('credentials.json');
$client->setAccessType('offline');
$client->setPrompt('select_account consent');
// Load previously authorized token from a file, if it exists.
// The file token.json stores the user's access and refresh tokens, and is
// created automatically when the authorization flow completes for the first
// time.
$tokenPath = 'token.json';
if (file_exists($tokenPath)) {
$accessToken = json_decode(file_get_contents($tokenPath), true);
$client->setAccessToken($accessToken);
}
// If there is no previous token or it's expired.
if ($client->isAccessTokenExpired()) {
// Refresh the token if possible, else fetch a new one.
if ($client->getRefreshToken()) {
$client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
} else {
// Request authorization from the user.
$authUrl = $client->createAuthUrl();
printf("Open the following link in your browser:n%sn", $authUrl);
print 'Enter verification code: ';
$authCode = trim(fgets(STDIN));
// Exchange authorization code for an access token.
$accessToken = $client->fetchAccessTokenWithAuthCode($authCode);
$client->setAccessToken($accessToken);
// Check to see if there was an error.
if (array_key_exists('error', $accessToken)) {
throw new Exception(join(', ', $accessToken));
}
}
// Save the token to a file.
if (!file_exists(dirname($tokenPath))) {
mkdir(dirname($tokenPath), 0700, true);
}
file_put_contents($tokenPath, json_encode($client->getAccessToken()));
}
return $client;
}

// Get the API client and construct the service object.
$client = getClient();
$service = new Google_Service_Calendar($client);
$calendarId = 'primary';
$optParams = array(
'maxResults' => 10,
'orderBy' => 'startTime',
'singleEvents' => true,
'timeMin' => date('c'),
);
$results = $service->events->listEvents($calendarId, $optParams);
$events = $results->getItems();
#--------------------------------------------------------------------------------------------
// Refer to the PHP quickstart on how to setup the environment:
// https://developers.google.com/calendar/quickstart/php
// Change the scope to Google_Service_Calendar::CALENDAR and delete any stored
// credentials.
$event = new Google_Service_Calendar_Event(array(
'summary' => 'Google I/O 2015',
'location' => '800 Howard St., San Francisco, CA 94103',
'description' => 'A chance to hear more about Google's developer products.',
'start' => array(
'dateTime' => '2015-05-28T09:00:00-07:00',
'timeZone' => 'America/Los_Angeles',
),
'end' => array(
'dateTime' => '2015-05-28T17:00:00-07:00',
'timeZone' => 'America/Los_Angeles',
),
'recurrence' => array(
'RRULE:FREQ=DAILY;COUNT=2'
),
'attendees' => array(
array('email' => 'lpage@example.com'),
array('email' => 'sbrin@example.com'),
),
'reminders' => array(
'useDefault' => FALSE,
'overrides' => array(
array('method' => 'email', 'minutes' => 24 * 60),
array('method' => 'popup', 'minutes' => 10),
),
),
));
$calendarId = 'primary';
$event = $service->events->insert($calendarId, $event);
printf('Event created: %sn', $event->htmlLink);
#--------------------------------------------------------------------------------------------------------
if (empty($events)) {
print "No upcoming events found.n";
} else {
print "Upcoming events:n";
foreach ($events as $event) {
$start = $event->start->dateTime;
if (empty($start)) {
$start = $event->start->date;
}
printf("%s (%s)n", $event->getSummary(), $start);
echo "<br>";
}
}
?>

我能够通过使用相同的代码进行小编辑来创建事件。我修改了只读作用域,允许读/写访问,而不是只读。这是最终的结果:

<?php
require __DIR__ . '/vendor/autoload.php';
/*
if (php_sapi_name() != 'cli') {
throw new Exception('This application must be run on the command line.');
}
*/
/**
* Returns an authorized API client.
* @return Google_Client the authorized client object
*/
function getClient()
{
$client = new Google_Client();
$client->setApplicationName('Google Calendar API PHP Quickstart');
$client->setScopes(Google_Service_Calendar::CALENDAR);
$client->setAuthConfig('credentials.json');
$client->setAccessType('offline');
$client->setPrompt('select_account consent');
// Load previously authorized token from a file, if it exists.
// The file token.json stores the user's access and refresh tokens, and is
// created automatically when the authorization flow completes for the first
// time.
$tokenPath = 'token.json';
if (file_exists($tokenPath))
{
$accessToken = json_decode(file_get_contents($tokenPath) , true);
$client->setAccessToken($accessToken);
}
// If there is no previous token or it's expired.
if ($client->isAccessTokenExpired())
{
// Refresh the token if possible, else fetch a new one.
if ($client->getRefreshToken())
{
$client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
}
else
{
// Request authorization from the user.
$authUrl = $client->createAuthUrl();
printf("Open the following link in your browser:n%sn", $authUrl);
print 'Enter verification code: ';
$authCode = trim(fgets(STDIN));
// Exchange authorization code for an access token.
$accessToken = $client->fetchAccessTokenWithAuthCode($authCode);
$client->setAccessToken($accessToken);
// Check to see if there was an error.
if (array_key_exists('error', $accessToken))
{
throw new Exception(join(', ', $accessToken));
}
}
// Save the token to a file.
if (!file_exists(dirname($tokenPath)))
{
mkdir(dirname($tokenPath) , 0700, true);
}
file_put_contents($tokenPath, json_encode($client->getAccessToken()));
}
return $client;
}
// Get the API client and construct the service object.
$client = getClient();
$service = new Google_Service_Calendar($client);
$calendarId = 'primary';
$optParams = array(
'maxResults' => 10,
'orderBy' => 'startTime',
'singleEvents' => true,
'timeMin' => date('c') ,
);
$results = $service
->events
->listEvents($calendarId, $optParams);
$events = $results->getItems();
#--------------------------------------------------------------------------------------------
// Refer to the PHP quickstart on how to setup the environment:
// https://developers.google.com/calendar/quickstart/php
// Change the scope to Google_Service_Calendar::CALENDAR and delete any stored
// credentials.
$event = new Google_Service_Calendar_Event(array(
'summary' => 'Google I/O 2015',
'location' => '800 Howard St., San Francisco, CA 94103',
'description' => 'A chance to hear more about Google's developer products.',
'start' => array(
'dateTime' => '2015-05-28T09:00:00-07:00',
'timeZone' => 'America/Los_Angeles',
) ,
'end' => array(
'dateTime' => '2015-05-28T17:00:00-07:00',
'timeZone' => 'America/Los_Angeles',
) ,
'recurrence' => array(
'RRULE:FREQ=DAILY;COUNT=2'
) ,
'attendees' => array(
array(
'email' => 'lpage@example.com'
) ,
array(
'email' => 'sbrin@example.com'
) ,
) ,
'reminders' => array(
'useDefault' => false,
'overrides' => array(
array(
'method' => 'email',
'minutes' => 24 * 60
) ,
array(
'method' => 'popup',
'minutes' => 10
) ,
) ,
) ,
));
$calendarId = 'primary';
$event = $service
->events
->insert($calendarId, $event);
printf('Event created: %sn', $event->htmlLink);
#--------------------------------------------------------------------------------------------------------
if (empty($events))
{
print "No upcoming events found.n";
}
else
{
print "Upcoming events:n";
foreach ($events as $event)
{
$start = $event
->start->dateTime;
if (empty($start))
{
$start = $event
->start->date;
}
printf("%s (%s)n", $event->getSummary() , $start);
echo "<br>";
}
}
?>

最新更新