【问题标题】:Google API Calendar with Cron带有 Cron 的 Google API 日历
【发布时间】:2025-11-24 01:10:01
【问题描述】:

我正在尝试通过 cron 访问由我的应用程序创建的日历,我得到一个与应用程序创建的日历同名的日历,但 id 完全不同...这是我的代码:

public function cronTest()
{
    $this->g_client = new Google_Client();
    $this->g_client->setApplicationName($this->config->item("APPLICATION_NAME"));
    $service    = $this->getCronService("CalendarTest-46bde015a16.p12");
    $calendar   = $this->getCalendar($service);
}
private function getCronService($file)
{
    $key  = file_get_contents(CREDENTIALS_PATH.$file); 
    $cred = new Google_Auth_AssertionCredentials($this->config->item("google_service_id"), SCOPES, $key);
    $this->g_client->setAssertionCredentials($cred);
    if($this->g_client->getAuth()->isAccessTokenExpired())
         $this->g_client->getAuth()->refreshTokenWithAssertion($cred);
    return new Google_Service_Calendar($this->g_client);
}
private function getCalendar($service)
{
    $calendarList = $service->calendarList->listCalendarList();
    echo "getCalendar<br>";
    foreach ($calendarList->getItems() as $calendarListEntry)
    {
        echo $calendarListEntry->getSummary()." with id:".$calendarListEntry->getId()."<br>";
        echo "<br>";
        if($calendarListEntry->getSummary()=="Auto-Citas")
            echo "found";
            //return $calendarListEntry->getId();
    }
    die;
}

当我从命令行执行它时(模拟 cron):

wget www.domain.com/prototipo/alien/cronTest

我明白了:

Calendar  
Auto-Citas with id:h0gefmo7vjqlr4lp0r2n93vk9c@group.calendar.google.com  
found

但是,使用此应用程序创建的日历 ID 与此 ID 不匹配...
在尝试使用 ron 之前,我必须学习如何使用 API,这样我有时需要删除相同的日历。所以我所做的是再次删除我日历上的 Auto-Citas,并在我的应用程序上调用该函数以创建一个具有不同名称的新日历,然后我再次发出“模拟 cron”的请求(wget www .domain.com/prototipo/alien/cronTest),结果和以前一样:只有一个名为 Auto-Citas 的日历,但没有关于新日历。
功能是创建一个模块防旷工,在约会前两小时向用户发送电子邮件或短信(cita=appointment)
对于这项任务,我必须发挥更多作用......但它们对这个案例并不重要:

$events     = $this->getDates($service,$calendar,$min,$max);
$this->transformDates($events, $service, ",phone");

【问题讨论】:

    标签: php cron google-calendar-api google-api-php-client


    【解决方案1】:

    好的...我找到解决方案只是here(谷歌官方文档)。我需要使用 user_to_impersonate 的选项。

    $client_email = '1234567890-a1b2c3d4e5f6g7h8i@developer.gserviceaccount.com';
    $private_key = file_get_contents('MyProject.p12');
    $scopes = implode(' ', array(Google_Service_Calendar::CALENDAR));
    $user_to_impersonate = 'user@example.org';
    $credentials = new Google_Auth_AssertionCredentials(
        $client_email,
        $scopes,
        $private_key,
        'notasecret',                                 // Default P12 password
        'http://oauth.net/grant_type/jwt/1.0/bearer', // Default grant type
        $user_to_impersonate,
    );
    

    【讨论】: