2017-06-16 426 views
0

我正在使用Google PHP客戶端訪問電子表格數據。Google Api Php客戶端 - Spreadsheets權限錯誤

我得到這個致命的錯誤:

Fatal error: Uncaught exception 'Google_Service_Exception' with message '{ "error": { "code": 403, "message": "The caller does not have permission", "errors": [ { "message": "The caller does not have permission", "domain": "global", "reason": "forbidden" } ], "status": "PERMISSION_DENIED" } }

我的代碼:

$client = new Google_Client(); 
    $client->setApplicationName("Google spreadsheets"); 
    $client->setDeveloperKey("xxxxx"); 
    $client->setScopes(array('https://www.googleapis.com/auth/drive',  
    'https://www.googleapis.com/auth/spreadsheets.readonly',  
    'https://www.googleapis.com/auth/drive.file')); 

    $service = new Google_Service_Sheets($client); 

    $range = 'Class Data!A2:E'; 
    $response = $service->spreadsheets_values->get($sheetid, $range); 
    $values = $response->getValues(); 

    if (count($values) == 0) { 
     print "No data found.\n"; 
    } else { 
    print "Name, Major:\n"; 
    foreach ($values as $row) { 
    // Print columns A and E, which correspond to indices 0 and 4. 
    printf("%s, %s\n", $row[0], $row[4]); 
    } 
    } 

如何解決這一問題?

回答

0

獲取服務帳戶的電子郵件地址,並像使用其他用戶一樣共享工作表。然後它將訪問表格

0

該錯誤表示您無權訪問該工作表。我建議你按照Google Sheets php quick start tutorial,這將告訴你如何獲得驗證工作。

<?php 
require_once __DIR__ . '/vendor/autoload.php'; 


define('APPLICATION_NAME', 'Google Sheets API PHP Quickstart'); 
define('CREDENTIALS_PATH', '~/.credentials/sheets.googleapis.com-php-quickstart.json'); 
define('CLIENT_SECRET_PATH', __DIR__ . '/client_secret.json'); 
// If modifying these scopes, delete your previously saved credentials 
// at ~/.credentials/sheets.googleapis.com-php-quickstart.json 
define('SCOPES', implode(' ', array(
    Google_Service_Sheets::SPREADSHEETS_READONLY) 
)); 

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

/** 
* Returns an authorized API client. 
* @return Google_Client the authorized client object 
*/ 
function getClient() { 
    $client = new Google_Client(); 
    $client->setApplicationName(APPLICATION_NAME); 
    $client->setScopes(SCOPES); 
    $client->setAuthConfig(CLIENT_SECRET_PATH); 
    $client->setAccessType('offline'); 

    // Load previously authorized credentials from a file. 
    $credentialsPath = expandHomeDirectory(CREDENTIALS_PATH); 
    if (file_exists($credentialsPath)) { 
    $accessToken = json_decode(file_get_contents($credentialsPath), true); 
    } 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); 

    // Store the credentials to disk. 
    if(!file_exists(dirname($credentialsPath))) { 
     mkdir(dirname($credentialsPath), 0700, true); 
    } 
    file_put_contents($credentialsPath, json_encode($accessToken)); 
    printf("Credentials saved to %s\n", $credentialsPath); 
    } 
    $client->setAccessToken($accessToken); 

    // Refresh the token if it's expired. 
    if ($client->isAccessTokenExpired()) { 
    $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken()); 
    file_put_contents($credentialsPath, json_encode($client->getAccessToken())); 
    } 
    return $client; 
} 

/** 
* Expands the home directory alias '~' to the full path. 
* @param string $path the path to expand. 
* @return string the expanded path. 
*/ 
function expandHomeDirectory($path) { 
    $homeDirectory = getenv('HOME'); 
    if (empty($homeDirectory)) { 
    $homeDirectory = getenv('HOMEDRIVE') . getenv('HOMEPATH'); 
    } 
    return str_replace('~', realpath($homeDirectory), $path); 
} 

// Get the API client and construct the service object. 
$client = getClient(); 
$service = new Google_Service_Sheets($client); 

// Prints the names and majors of students in a sample spreadsheet: 
// https://docs.google.com/spreadsheets/d/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms/edit 
$spreadsheetId = '1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms'; 
$range = 'Class Data!A2:E'; 
$response = $service->spreadsheets_values->get($spreadsheetId, $range); 
$values = $response->getValues(); 

if (count($values) == 0) { 
    print "No data found.\n"; 
} else { 
    print "Name, Major:\n"; 
    foreach ($values as $row) { 
    // Print columns A and E, which correspond to indices 0 and 4. 
    printf("%s, %s\n", $row[0], $row[4]); 
    } 
} 
+0

該電子表格歸我所有,意味着可以訪問工作表的api項目所有者。此外,我想訪問沒有oAuth認證。 –

+0

Google Developer Console上的項目不允許您訪問使用數據,即使是擁有它的開發人員也是如此。您仍然需要訪問私人用戶數據的權限。您應該考慮使用服務帳戶。您可以預先授予允許其訪問表單的服務帳戶。查看https://developers.google.com/api-client-library/php/auth/service-accounts – DaImTo

+0

我創建了一個服務帳戶並使用下載的json文件。我不確定我們在控制檯中授權服務帳戶的位置。在鏈接中,它談到了gsuite授權。你能指導嗎? –