繁体   English   中英

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

[英]Can I use my php app to add events in Google Calendar?

是否可以在 Google 日历中添加/编辑/删除事件? 因为我所做的只是阅读我的事件。 我正在启用我可以找到的有关日历 API 的所有“范围”,但仍然收到关于“请求的身份验证范围不足/权限被拒绝”的错误 403。

我已经做了很多尝试来解决这个问题,每次我都达到同样的目的。 我正在使用 OAuth 2.0 客户端 ID 凭据,还有一个问题是我应该将哪个 URL 用于授权重定向 URI。

<?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%s\n", $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: %s\n', $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>";
    }
}

?>

请求的身份验证范围不足

意味着当前经过身份验证的用户没有授予您足够的权限来执行您正在尝试执行的操作。

由于您尚未发布代码,因此很难提供帮助,但我可以猜测您有一些具有一个范围的代码。 您授权用户并意识到您需要更高级别的权限,因此您更改了代码中的范围。

但是您没有再次请求用户同意,用户必须再次看到同意屏幕并显示新的权限范围,您才能拥有此新权限。

要么找出您在代码中存储用户凭据的位置。 或转到用户 google 帐户并找到第三方权限并删除对您帐户的访问权限。

然后使用新范围再次运行您的代码,并确保同意屏幕显示此新权限。 然后它应该工作。

我能够通过使用您的相同代码并进行少量编辑来创建事件。 我修改了只读范围以允许读/写访问而不是只读。 这是最终结果:

<?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%s\n", $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: %s\n', $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>";
    }
}

?>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM