2016-12-01 63 views
2

我想通過PHP在谷歌驅動器上傳文件。我在開發者控制檯中創建了一個項目,啓用了Drive API並添加了OAuth 2.0客戶端ID。 這是我的代碼。權限不足谷歌驅動器api oauth2在PHP

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

    session_start(); 

    $client = new Google_Client(); 
    $client->setAuthConfigFile('client_secret.json'); 
    $client->addScope(Google_Service_Drive::DRIVE_METADATA_READONLY); 
    $client->setScopes(array('https://www.googleapis.com/auth/drive')); 

    if (isset($_SESSION['access_token']) && $_SESSION['access_token']) { 
     $client->setAccessToken($_SESSION['access_token']); 
     $drive_service = new Google_Service_Drive($client); 
     $files_list = $drive_service->files->listFiles(array())->getFiles(); 
     echo "<pre>"; 
     print_r($files_list); 
    } else { 
     $redirect_uri = 'http://localhost/oauth2callback.php'; 
     header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL)); 
    } 
    $filename = "abc.txt"; 
    $file = new Google_Service_Drive_DriveFile(); 
    $file->setName($filename); 
    $result = $drive_service->files->create($file, array(
    'data' => file_get_contents("abc.txt"), 
    'mimeType' => 'application/octet-stream', 
    'uploadType' => 'media' 
)); 

輸出是:

Fatal error: Uncaught exception 'Google_Service_Exception' with message '{ 
"error": { 
    "errors": [ 
    { 
    "domain": "global", 
    "reason": "insufficientPermissions", 
    "message": "Insufficient Permission" 
    } 
    ], 
    "code": 403, 
    "message": "Insufficient Permission" 
} 
} 
' in D:\xampp\htdocs\vendor\google\apiclient\src\Google\Http\REST.php:118 

回答

0

的錯誤意味着The user does not have sufficient permissions for the {fileId}的用戶沒有對文件的寫訪問,並且應用程序試圖修改該文件。

授予您的服務帳戶訪問文件的權限。使用Permissions:insert來插入文件的權限。

import com.google.api.services.drive.Drive; 
import com.google.api.services.drive.model.Permission; 

import java.io.IOException; 
// ... 

public class MyClass { 

    // ... 

    /** 
    * Insert a new permission. 
    * 
    * @param service Drive API service instance. 
    * @param fileId ID of the file to insert permission for. 
    * @param value User or group e-mail address, domain name or {@code null} 
        "default" type. 
    * @param type The value "user", "group", "domain" or "default". 
    * @param role The value "owner", "writer" or "reader". 
    * @return The inserted permission if successful, {@code null} otherwise. 
    */ 
    private static Permission insertPermission(Drive service, String fileId, 
     String value, String type, String role) { 
    Permission newPermission = new Permission(); 

    newPermission.setValue(value); 
    newPermission.setType(type); 
    newPermission.setRole(role); 
    try { 
     return service.permissions().insert(fileId, newPermission).execute(); 
    } catch (IOException e) { 
     System.out.println("An error occurred: " + e); 
    } 
    return null; 
    } 

    // ... 

}