即使客户端 ID 和密钥有效,创建文件请求也会导致“请求的身份验证凭据无效”

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

我正在尝试使用 Laravel 应用程序在我的驱动器中创建一个文件夹。我的 Google 云端硬盘凭据是正确的,但我不断收到此错误:

{ "error": { "code": 401, "message": "请求无效 身份验证凭据。需要 OAuth 2 访问令牌、登录 cookie 或其他有效的身份验证凭证。看 https://developers.google.com/identity/sign-in/web/devconsole-project。”, “错误”:[ {“消息”:“无效凭据”,“域”:“全局”, “原因”:“authError”,“位置”:“授权”,“locationType”: “标题”}],“状态”:“未经身份验证”}}

这是控制器:

try {

        $client = new Client();
         $client->setApplicationName('MyAppTest');
         $client->setClientId(env('GOOGLE_APP_ID'));
         $client->setClientSecret(env('GOOGLE_APP_SECRET'));
         $client->setAccessToken(env('GOOGLE_OAUTH_ACCESS_TOKEN'));
       // $client->useApplicationDefaultCredentials();
        $client->addScope(Drive::DRIVE);
        $driveService = new Drive($client);
        $fileMetadata = new Drive\DriveFile(array(
            'name' => 'Invoices',
            'mimeType' => 'application/vnd.google-apps.folder'));
        $file = $driveService->files->create($fileMetadata, array(
            'fields' => 'id'));
        printf("Folder ID: %s\n", $file->id);
        return $file->id;

    }catch(Exception $e) {
       echo "Error Message: ".$e;
    }
php laravel google-drive-api google-oauth google-api-php-client
1个回答
0
投票

您不请求用户访问,您所做的只是创建客户端,然后向 api 发出请求。除非您请求用户同意,否则调用不会被授权。

function getClient()
{
    $client = new Client();
    $client->setApplicationName('Google Drive API PHP Quickstart');
    $client->setScopes('https://www.googleapis.com/auth/drive.readonly');
    $client->setAuthConfig('C:\Development\FreeLance\GoogleSamples\Credentials\credentials.json');
    $client->setAccessType('offline');
    $client->setRedirectUri("http://127.0.0.1");
    $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->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
            $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;
}


// Get the API client and construct the service object.
try {
    $client = getClient();
}
catch(Exception $e) {

    unlink("token.json");
    $client = getClient();
    }

$service = new Drive($client);

// Print the next 10 events on the user's calendar.
try{


    $optParams = array(
        'pageSize' => 10,
        'fields' => 'files(id,name,mimeType)',
        'q' => 'mimeType = "application/vnd.google-apps.folder" and "root" in parents',
        'orderBy' => 'name'
    );
    $results = $service->files->listFiles($optParams);
    $files = $results->getFiles();

    if (empty($files)) {
        print "No files found.\n";
    } else {
        print "Files:\n";
        foreach ($files as $file) {
            $id = $file->id;

            printf("%s - (%s) - (%s)\n", $file->getId(), $file->getName(), $file->getMimeType());
        }
    }
}
catch(Exception $e) {
    // TODO(developer) - handle error appropriately
    echo 'Message: ' .$e->getMessage();
}
© www.soinside.com 2019 - 2024. All rights reserved.