使用服务帐户密钥和php进行Google工作表更新

问题描述 投票:0回答:1

使用php api更新谷歌表格我使用https://console.developers.google.com/apis创建了一个servide accout键,并将该文件保存在根文件夹中,我使用composer下载了apiclient结构。并与服务帐户中提供的客户端客户端电子邮件共享工作表nad授予其完全访问权限。以下是用于更新的代码:

<?php

require 'vendor/autoload.php';

$service_account_file = 'credentials.json';

$spreadsheet_id = '13zWB1_uY5CdPGLuSXRWAgD0lE7QVrbTDW_9V5lqdNAY';


$spreadsheet_range = 'Sheet1';

putenv('GOOGLE_APPLICATION_CREDENTIALS=' . $service_account_file);
$client = new Google_Client();
$client->useApplicationDefaultCredentials();
$client->addScope(Google_Service_Sheets::SPREADSHEETS);
$service = new Google_Service_Sheets($client);

$options = array('valueInputOption' => 'RAW');
$values = [
["Name", "Roll No", "Contact"],
["AAA", "001", "12345"],
["BBB", "002", "6789"]
];
$body   = new Google_Service_Sheets_ValueRange(['values' => $values]);

$result = $service->spreadsheets_values->update($spreadsheet_id, $spreadsheet_range, $body, $options);
?>

问题是它在我的localhost中正常工作。但是当我将文件夹上传到000webhost并从那里运行时,它给出了以下错误:

捕获异常:无法加载默认凭据。浏览https://developers.google.com/accounts/docs/application-default-credentials获取更多信息

我需要使用gcloud吗?据我所知,我不需要gcloud来使用Google API。如果我需要使用gcloud如何使用gcloud从我的000webhost网站(https://www.000webhost.com)工作。

php google-cloud-platform google-sheets-api google-api-php-client
1个回答
2
投票

您正在使用凭证文件的相对路径名。您需要使用完整路径。代码中的行:

$service_account_file = 'credentials.json';

应改为:

$service_account_file = '/mysecrets/credentials.json';

将目录mysecrets更改为您想要的任何内容。如果这是一个Web服务器,请不要在服务器的html目录中找到该文件。

您也可以手动指定文件:

$client->setAuthConfig($service_account_file);

并删除这些行:

putenv('GOOGLE_APPLICATION_CREDENTIALS=' . $service_account_file); 
$client->useApplicationDefaultCredentials();
© www.soinside.com 2019 - 2024. All rights reserved.