【问题标题】:using service account to access google calendar but answer variables are empty使用服务帐户访问谷歌日历但答案变量为空
【发布时间】:2020-05-25 16:23:57
【问题描述】:

我创建了一个服务帐户来访问某个谷歌日历。此服务帐户用户还获得了日历设置中的权限,如本博客所述:“allow my user to add meeting in my calendar with Google Calendar API with PHP without auth”。

正如我在 Google Cloud Platform 中的 APIs + Services -> Credentials 中的 Service Account 部分看到的那样,创建的服务帐户每次都用于所有服务(过去 30 天),当我触发这个 php 脚本时,但是在浏览器窗口 我没有收到任何错误,表明身份验证会出现问题,但是:未捕获的错误:调用 php-script 的 null in line 上的成员函数 getSummary()... Google Cloud Platform 中的脚本和设置如上述帖子中所述。

知道可能是什么问题吗?自 2019 年发布此帖子以来,谷歌日历 api 有什么变化吗?

require '../google-api-php-client/vendor/autoload.php';
ini_set('display_errors', 1);

$client = new Google_Client();
$client->addScope("https://www.googleapis.com/auth/calendar");

$client->setAuthConfig(dirname(__FILE__).'/credentials/credentials.json');

$service = new Google_Service_Calendar($client);

$calendarList = $service->calendarList->listCalendarList();

while(true) {

  foreach ($calendarList->getItems() as $calendarListEntry) {
    echo $calendarListEntry->getSummary();
    echo "\n------------------------------\n\n";

    // get events 
    $events = $service->events->listEvents($calendarListEntry->id);

    foreach ($events->getItems() as $event) {
        echo "- " . $event->getSummary() . "\n";
        echo "- " . $event->getStart()->getDateTime() . "\n\n";
    }

  }

  $pageToken = $calendarList->getNextPageToken();

  if ($pageToken) {
    $optParams = array('pageToken' => $pageToken);
    $calendarList = $service->calendarList->listCalendarList($optParams);
  } else {

    echo "break";
   break;
  }

}
    echo "calendar summary: " . $calendarListEntry->getSummary();
    echo "\ncalendar id: " . $calendarListEntry->getId();
    echo "\n------------------------------\n\n";

显然 $calendarList 和 $calendarListEntry 是空的......

【问题讨论】:

  • 您正在尝试调用未定义类的方法。如果您发布您的代码,我们可能会为您提供更好的帮助。请记住删除您的身份验证详细信息。
  • 您可以在定义服务帐户的地方分享您的代码吗?
  • 不是在 credentials.json 中声明的服务帐户,它包含在 ->setAuthConfig() 中吗?定义服务帐号是否还需要其他东西?
  • 是的,但是在使用服务帐户时,您需要为身份验证流程使用不同的库,而不是普通用户。在this question 上查看答案。

标签: php service google-calendar-api service-accounts


【解决方案1】:

function getSummary() 无法呈现任何结果(为 null 或为空)的原因是因为新的服务帐户用户有一个空的 calendarList。将任何其他日历中的权限授予服务帐户用户不会自动将此日历插入到服务帐户用户的日历列表中。

所以你首先必须为服务帐户插入/创建一个calenderList:

$calendarListEntry = new Google_Service_Calendar_CalendarListEntry();
$calendarListEntry->setId("calendar_address_you_want_to_add");
$createdCalendarListEntry = $service->calendarList->insert($calendarListEntry);
echo $createdCalendarListEntry->getSummary();

现在使用第一个脚本时,您将获得 calendarEvents(只要日历中发布任何即将发生的事件)getSummary() 函数和 getId() 函数的结果。

【讨论】:

    猜你喜欢
    • 2017-12-24
    • 2019-06-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-30
    • 1970-01-01
    • 2018-02-10
    相关资源
    最近更新 更多