我需要使用CRON通过php更新我的一张Google表格。但是在2018年这样做的正确方法是什么?我应该选择Google Cloud API调用Web应用程序还是没有UI的平台(但只能访问应用程序生成的数据)?我应该创建作为服务帐户的凭据吗?使用服务帐户访问时刷新令牌怎么样?
一般来说,这将是我的私人功能,仅限我。我的任务应该由cron实现,但我完全不在这个主题之内,我以前从未使用过Google API。我已经阅读了很多文档,但其中大部分是关于标准的oauth2访问和用户提示(甚至不时)。也许有人可以在这种情况下推荐一些好的做法?
PS。我正在使用googleapis / google-api-php-client
您需要做的第一件事是决定您要访问哪些数据。
如果这是第一个选项,那么您应该利用服务帐户。谷歌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撕掉