【问题标题】:Using PHP Cron and Google API access使用 PHP Cron 和 Google API 访问
【发布时间】:2018-09-18 10:54:29
【问题描述】:

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

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

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

【问题讨论】:

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


    【解决方案1】:

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

    • 这是您的帐户或工作表,您作为开发者可以访问吗?
    • 这是另一个用户帐户拥有的工作表吗?

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

    如果这是第二个选项并且您需要访问用户帐户。那么您可能需要使用基于浏览器的浏览器。一旦您可以保存刷新令牌,用户将需要对您的应用程序进行身份验证,然后 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 窃取的代码

    【讨论】:

    • 感谢您的回复。好吧,我只需要这个用于我的帐户,用于我的私人数据。我考虑了一个服务帐户,但可能需要 G Suite?我在 cloud.google.com 和 json 文件中为此类访问创建了一个服务帐户 xxx@xxx.iam.gserviceaccount.com,但是如何设置通过此服务帐户访问我的消费者帐户的权限。
    • 您不需要 gsuite 即可通过服务帐户使用 google sheet api。获取该电子邮件地址并转到谷歌驱动器,与该电子邮件地址共享文件。 (右上角的蓝色按钮)服务帐户将有权访问您的工作表。你可以在浏览器uri中找到文件id
    • 是的,非常感谢!我只需要与服务帐户共享我的文件。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-17
    • 1970-01-01
    • 2013-03-19
    • 2012-09-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多