Search code examples
google-api-php-clientgoogle-api-clientgoogle-drive-android-apicreate-directory

Google Drive API Unable to Write Folder


I have pieced this together from Google documentation I am trying to write a test folder to the Google Drive APP but I am getting this error:

An error occurred: {
 "error": {
  "errors": [
   {
    "domain": "global",
    "reason": "insufficientPermissions",
    "message": "Insufficient Permission"
   }
  ],
  "code": 403,
  "message": "Insufficient Permission"
 }
}

Searching online it seems that this is due to the scopes? Which is why I've added so many below:

require_once 'vendor/autoload.php';

date_default_timezone_set('Europe/London');

define('APPLICATION_NAME', 'Pauls Google Drive');
define('CREDENTIALS_PATH', '~/.credentials/drive-php-quickstart.json');
define('CLIENT_SECRET_PATH', __DIR__ . '/client_secret_paul.json');
// If modifying these scopes, delete your previously saved credentials
// at ~/.credentials/drive-php-quickstart.json
define('SCOPES', implode(' ', array(
        Google_Service_Drive::DRIVE,
        Google_Service_Drive::DRIVE_FILE,
        Google_Service_Drive::DRIVE_APPDATA,
        Google_Service_Drive::DRIVE_READONLY,
        Google_Service_Drive::DRIVE_METADATA,
        Google_Service_Drive::DRIVE_METADATA_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);
}

function getFolderExistsCreate($service, $folderName, $folderDesc) {
    // List all user files (and folders) at Drive root
    $files = $service->files->listFiles();
    $found = false;
    // Go through each one to see if there is already a folder with the specified name
    foreach ($files['items'] as $item) {
        if ($item['title'] == $folderName) {
            $found = true;
            return $item['id'];
            break;
        }
    }
    // If not, create one
    if ($found == false) {
        $folder = new Google_Service_Drive_DriveFile();
        //Setup the folder to create
        $folder->setName($folderName);
        if(!empty($folderDesc))
            $folder->setDescription($folderDesc);
        $folder->setMimeType('application/vnd.google-apps.folder');
        //Create the Folder
        try {
            $createdFile = $service->files->create($folder, array(
                'mimeType' => 'application/vnd.google-apps.folder',
            ));
            // Return the created folder's id
            return $createdFile->id;
        } catch (Exception $e) {
            print "An error occurred: " . $e->getMessage();
        }
    }
}


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

getFolderExistsCreate( $service, 'Test', 'This is a test folder' );

getFolderExistsCreate is the method actually creating the folder, which is just over half way down the code. Please help!! :) I have been able to return a list of files from the drive without error, so I am happy that the credentials and connection are OK.


Solution

  • How about the following confirmations?

    1. Confirm that Drive API is enabled, again.
    2. You said that you added scopes. So please remove the file of ~/.credentials/drive-php-quickstart.json once. And then, run your script and create drive-php-quickstart.json again. By this, the added scopes is reflected to the access token and refresh token.

    If these were not useful for you, I'm sorry.