使用 PHP Cron 和 Google API 访问

Using PHP Cron and Google API access

我需要使用 CRON 通过 php 更新我的 Google 个工作表之一。但在 2018 年这样做的正确方法是什么? 我应该在 Google Cloud API 中 select 调用 Web 应用程序还是没有 UI 的平台(但只能访问应用程序生成的数据)? 我应该创建凭据作为服务帐户吗?使用服务帐户访问权限时如何刷新令牌?

通常这将是我的私人功能,仅供我使用。我的任务应该由cron来实现,但是我完全脱离了这个话题,我以前从未使用过Google API。我读过很多文档,但其中大部分是关于带有用户提示的标准 oauth2 访问(甚至不时)。在这种情况下,也许有人可以推荐一些好的做法?

PS。我正在使用 googleapis/google-api-php-client

您需要做的第一件事是决定您要访问谁的数据。

  • 这是您的帐户还是您的 sheet 作为开发者可以访问的东西。
  • 这是另一个用户帐户所拥有的 sheet。

如果这是第一个选项,那么您应该利用服务帐户。 google api php 客户端库将为您处理刷新访问,您无需担心。只需获取服务帐户电子邮件地址并与服务帐户用户共享您希望它访问的 sheet。

如果这是第二个选项并且您需要访问用户帐户。那么您可能需要使用基于浏览器的浏览器。一旦您可以保存刷新令牌,用户将需要对您的应用程序进行身份验证,然后 php 客户端库将在需要时通过获取新的访问令牌来帮助您。您将需要注意此解决方案,因为刷新令牌应该长期存在并且不会过期,但根据我的经验,它们可能会不时过期,您将需要再次向用户请求授权。

require_once __DIR__ . '/vendor/autoload.php';
// Use the developers console and download your service account
// credentials in JSON format. Place the file in this directory or
// change the key file location if necessary.
putenv('GOOGLE_APPLICATION_CREDENTIALS='.__DIR__.'/service-account.json');
/**
 * Gets the Google client refreshing auth if needed.
 * Documentation: https://developers.google.com/identity/protocols/OAuth2ServiceAccount
 * Initializes a client object.
 * @return A google client object.
 */
function getGoogleClient() {
    return getServiceAccountClient();
}
/**
 * Builds the Google client object.
 * Documentation: https://developers.google.com/api-client-library/php/auth/service-accounts
 * Scopes will need to be changed depending upon the API's being accessed. 
 * array(Google_Service_Analytics::ANALYTICS_READONLY, Google_Service_Analytics::ANALYTICS)
 * List of Google Scopes: https://developers.google.com/identity/protocols/googlescopes
 * @return A google client object.
 */
function getServiceAccountClient() {
    try {   
        // Create and configure a new client object.        
        $client = new Google_Client();
        $client->useApplicationDefaultCredentials();
        $client->addScope([YOUR SCOPES HERE]);
        return $client;
    } catch (Exception $e) {
        print "An error occurred: " . $e->getMessage();
    }
}

ServiceAccount.php

中窃取的代码