【发布时间】:2017-09-21 06:46:56
【问题描述】:
我正在使用 php 库 google-api-php-client-2.2.0
我正在尝试通过 crontab 执行 php 脚本,每小时自动更新 google drive 电子表格的值
这是我如何让我的客户使用 google drive 服务
function getClient() {
$client = new Google_Client();
$client->setApplicationName(APPLICATION_NAME);
$client->setScopes(SCOPES);
$client->setAuthConfig(CLIENT_SECRET_PATH);
$client->setAccessType('offline');
$client->setIncludeGrantedScopes(true);
// Load previously authorized credentials from a file.
$credentialsPath = expandHomeDirectory(CREDENTIALS_PATH);
if (file_exists($credentialsPath)) {
$accessToken = json_decode(file_get_contents($credentialsPath), true);
$client->setAccessToken($accessToken);
if ($client->isAccessTokenExpired()) {
$client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
file_put_contents($credentialsPath, json_encode($client->getAccessToken()));
$accessToken = json_decode(file_get_contents($credentialsPath), true);
$client->setAccessToken($accessToken);
}
}
return $client;
}
下面是搜索正确的谷歌驱动器文件并在找到后更新它的代码
define('APPLICATION_NAME', 'Drive API PHP Quickstart');
define('CREDENTIALS_PATH', __DIR__ . '/drive-php-quickstart.json');
define('CLIENT_SECRET_PATH', __DIR__ . '/client_secret.json');
define('SCOPES', implode(' ', array(Google_Service_Drive::DRIVE)));
$client = getClient();
$service = new Google_Service_Drive($client);
$optParams = array(
'pageSize' => 10,
'fields' => 'nextPageToken, files(id, name)'
);
$results = $service->files->listFiles($optParams);
$data = get_results_as_string($all); // this is data to be updated with
if (count($results->getFiles()) == 0) {
print "No files found.\n";
}else{
foreach ($results->getFiles() as $file) {
if ($file->getName() == $GOOGLE_SPREADSHEET_NAME){
$fileId = $file->getId();
$emptyFile = new Google_Service_Drive_DriveFile();
$service->files->update($fileId, $emptyFile, array(
'data' => $data,
'mimeType' => 'text/csv',
'uploadType' => 'media',
'fields' => 'id')
);
}
}
}
我希望当我从 CLIENT_SECRET_PATH 文件中获取的访问令牌到期时 - 我将从我在同一文件中的刷新令牌中获取(因为我对此进行了适当的检查)新的访问令牌。 我用获取的内容覆盖文件,并进一步进行更新和例程。
但是,这大约可以工作 12 小时(我每小时运行一次),然后停止工作。 如果您能对此提供帮助,不胜感激
【问题讨论】:
-
Define 停止工作你的错误信息到底是什么。您选择不使用服务帐户的任何原因?使用sheets api不是更容易吗?
标签: php google-sheets google-api google-drive-api google-api-php-client