簡體   English   中英

PHP 致命錯誤:在嘗試運行 Google 的示例腳本時,vendor/google/apiclient/src/Client.php:982 中不存在文件“credentials.json”

[英]PHP fatal error: file "credentials.json" does not exist in vendor/google/apiclient/src/Client.php:982 when trying to run Google's example script

我一直在嘗試使用 Google 的 Apps Script API。 我一直在嘗試使用 Google 的 Apps Script API。 以下是我到目前為止采取的步驟:

  1. 運行作曲家並安裝所需的 package google/apiclient:^2.0
  2. 開通試用 Google Cloud 帳戶
  3. 在賬戶中啟用 API
  4. 下載並安裝了 gloud cli
  5. 執行“gcloud install”並選擇項目
  6. 執行“gcloud auth application-default login”並登錄我的谷歌雲賬戶

當我運行示例腳本時,標題中出現了致命錯誤。

這是谷歌的代碼

require __DIR__ . '/vendor/autoload.php';

if (php_sapi_name() != 'cli') {
    throw new Exception('This application must be run on the command line.');
}

use Google\Client;
use Google\Service\Script;

/**
 * Returns an authorized API client.
 * @return Client the authorized client object
 */
function getClient()
{
    $client = new Client();
    $client->setApplicationName('Google Apps Script API PHP Quickstart');
    $client->setScopes("https://www.googleapis.com/auth/script.projects");
    $client->setAuthConfig('credentials.json');
    $client->setAccessType('offline');
    $client->setPrompt('select_account consent');

    // Load previously authorized token from a file, if it exists.
    // The file token.json stores the user's access and refresh tokens, and is
    // created automatically when the authorization flow completes for the first
    // time.
    $tokenPath = 'token.json';
    if (file_exists($tokenPath)) {
        $accessToken = json_decode(file_get_contents($tokenPath), true);
        $client->setAccessToken($accessToken);
    }

    // If there is no previous token or it's expired.
    if ($client->isAccessTokenExpired()) {
        // Refresh the token if possible, else fetch a new one.
        if ($client->getRefreshToken()) {
            $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
        } else {
            // Request authorization from the user.
            $authUrl = $client->createAuthUrl();
            printf("Open the following link in your browser:\n%s\n", $authUrl);
            print 'Enter verification code: ';
            $authCode = trim(fgets(STDIN));

            // Exchange authorization code for an access token.
            $accessToken = $client->fetchAccessTokenWithAuthCode($authCode);
            $client->setAccessToken($accessToken);

            // Check to see if there was an error.
            if (array_key_exists('error', $accessToken)) {
                throw new Exception(join(', ', $accessToken));
            }
        }
        // Save the token to a file.
        if (!file_exists(dirname($tokenPath))) {
            mkdir(dirname($tokenPath), 0700, true);
        }
        file_put_contents($tokenPath, json_encode($client->getAccessToken()));
    }
    return $client;
}


/**
 * Shows basic usage of the Apps Script API.
 *
 * Call the Apps Script API to create a new script project, upload files to the
 * project, and log the script's URL to the user.
 */
$client = getClient();
$service = new Script($client);

// Create a management request object.
try{

    $request = new Script\CreateProjectRequest();
    $request->setTitle('My Script');
    $response = $service->projects->create($request);

    $scriptId = $response->getScriptId();

    $code = <<<EOT
function helloWorld() {
  console.log('Hello, world!');
}
EOT;
    $file1 = new Script\ScriptFile();
    $file1->setName('hello');
    $file1->setType('SERVER_JS');
    $file1->setSource($code);

    $manifest = <<<EOT
{
  "timeZone": "America/New_York",
  "exceptionLogging": "CLOUD"
}
EOT;
    $file2 = new Script\ScriptFile();
    $file2->setName('appsscript');
    $file2->setType('JSON');
    $file2->setSource($manifest);

    $request = new Script\Content();
    $request->setScriptId($scriptId);
    $request->setFiles([$file1, $file2]);

    $response = $service->projects->updateContent($scriptId, $request);
    echo "https://script.google.com/d/" . $response->getScriptId() . "/edit\n";
}
catch(Exception $e) {
    // TODO(developer) - handle error appropriately
    echo 'Message: ' .$e->getMessage();
}

PHP的堆棧跟蹤:

Stack trace:
#0 apps-script/quickstart.php(21): Google\Client->setAuthConfig()
#1 apps-script/quickstart.php(72): getClient()
#2 {main}
  thrown in apps-script/vendor/google/apiclient/src/Client.php on line 982

我在計算機上進行了搜索,但找不到名為“credentials.json”的文件。

有沒有我沒有采取的步驟? 唯一的區別是我的 apiclient 版本更新。

您需要從您的 Google 帳戶創建文件,然后將其復制到您的項目中。 可以在這里找到要采取的步驟。 可用的方法有:

所需的憑據取決於應用程序的數據類型、平台和訪問方法。 以下是可用的憑證類型:

  • API 密鑰 – 使用此憑據在您的應用程序中匿名訪問公開可用的數據。

  • OAuth 客戶端 ID – 使用此憑據作為最終用戶進行身份驗證並訪問他們的數據。 要求您的應用請求並獲得用戶的同意。

  • 服務帳號 - 使用此憑據作為機器人服務帳號進行身份驗證,或通過域范圍的委派代表 Google Workspace 或 Cloud Identity 用戶訪問資源。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM