Error when creating folder in google drive - php

I have search in th enet but i can't find the solutions. Please help. Below is the code.
<?php
require_once '../../vendor/autoload.php';
define('APPLICATION_NAME', 'Drive API PHP Quickstart');
define('CREDENTIALS_PATH', '~/.credentials/drive-php-quickstart.json');
define('CLIENT_SECRET_PATH', __DIR__ . '/client_secret.json');
define('SCOPES', implode(' ', array(
Google_Service_Drive::DRIVE_METADATA_READONLY)
));
$client = new Google_Client();
$client->setApplicationName(APPLICATION_NAME);
$client->setScopes(SCOPES);
$client->setScopes(array('https://www.googleapis.com/auth/drive', 'https://www.googleapis.com/auth/drive.apps.readonly', 'https://www.googleapis.com/auth/drive'));
$client->setAuthConfig(CLIENT_SECRET_PATH);
$client->setAccessType('offline');
$service = new Google_Service_Drive($client);
$fileMetadata = new Google_Service_Drive_DriveFile(array(
'name' => 'Test Folder',
'mimeType' => 'application/vnd.google-apps.folder'));
$file = $service->files->create($fileMetadata, array(
'fields' => 'id'));
printf("Folder ID: %s\n", $file->id);die();
?>
I can list all the files from the drive but I can't create a folder. What I'm missing? Below is the error. Can someone help me to solve this problem of mine. Thanks in advance.
PHP Fatal error: Uncaught Google_Service_Exception: {
"error": {
"errors": [
{
"domain": "global",
"reason": "required",
"message": "Login Required",
"locationType": "header",
"location": "Authorization"
}
],
"code": 401,
"message": "Login Required"
}
}

I hope this will assist you in solving your problem, I found your error here:
https://developers.google.com/drive/v3/web/handle-errors
To help you navigate to a solution, here is the snippet, hope this assists you in some way:
401: Invalid Credentials
Invalid authorization header. The access token you're using is either expired or invalid.
{
"error": {
"errors": [
{
"domain": "global",
"reason": "authError",
"message": "Invalid Credentials",
"locationType": "header",
"location": "Authorization",
}
],
"code": 401,
"message": "Invalid Credentials"
}
}
Suggested action: Refresh the access token using the long-lived refresh token. If this fails, direct the user through the OAuth flow, as described in Authorizing Your App with Google Drive.
If you want to know more about Authorizing your app with google drive, please refer to this site:
https://developers.google.com/drive/v3/web/about-auth
Hope you are able to find a solution with the resources provided.

Related

Insufficient Permission

befor i ask i want to introduce my first steps.
I used this for example: PHP Quickstart
Install google/apiclient via composer
Create a project in Google Developers Console
Add credentials to my project
Upload client_secret.json to my webserver
Run the script & enter the code
Credentials saved to /files/php-yt-oauth2.json
This channel's ID is UC_x5XG1OV2P6uZZ5FSM9Ttw. Its title is Google Developers, and it has 125874726 views.
Now i want to list all videos of one playlist:
function playlistItemsListByPlaylistId($service, $part, $params) {
$params = array_filter($params);
$response = $service->playlistItems->listPlaylistItems(
$part,
$params
);
print_r($response);
}
playlistItemsListByPlaylistId($service,
'snippet',
array('maxResults' => 1, 'playlistId' => 'ID'));
An get the following error:
[23-Dec-2017 14:29:59 Europe/Berlin] PHP Fatal error: Uncaught Google_Service_Exception: {
"error": {
"errors": [
{
"domain": "global",
"reason": "insufficientPermissions",
"message": "Insufficient Permission"
}
],
"code": 403,
"message": "Insufficient Permission"
}
}
in /html/sa/vendor/google/apiclient/src/Google/Http/REST.php:118
I dont know whats going wrong and i hope someone can help me with this issue.

PHP How to upload to Youtube user's channel

Need to make user's authorizations so server will upload videos to users channels.
Authentication part:
$client = new Google_Client();
$client->setAuthConfigFile(PROPPATH.'/inc/client_secret.json');
$client->setRedirectUri('https://back url');
$client->setScopes('https://www.googleapis.com/auth/youtube');
$client->setAccessType('offline');
$credentialsPath = PROPPATH.'/youtube_auth/user_'.get_current_user_id().'.json';
if (file_exists($credentialsPath)) {
$accessToken = file_get_contents($credentialsPath);
} else {
$authUrl = $client->createAuthUrl();
if(!isset($_GET['code'])) {
echo '<script>window.location = "'.$authUrl.'";</script>';
} else {
$authCode = $_GET['code'];
$accessToken = $client->authenticate($authCode);
file_put_contents($credentialsPath, $accessToken);
}
Authentication seems like works and saves some key.
2nd part, trying upload video:
$client = new Google_Client();
$client->setAuthConfigFile(PROPPATH.'/inc/client_secret.json');
$client->setScopes('https://www.googleapis.com/auth/youtube');
$youtube = new Google_Service_YouTube($client);
$client->setAccessToken(file_get_contents(PROPPATH.'/youtube_auth/user_2.json'));
$client->setAccessType('offline');
if ($client->getAccessToken()) {
$video = new Google_Service_YouTube_Video();
$chunkSizeBytes = 1 * 1024 * 1024;
$client->setDefer(true);
$insertRequest = $youtube->videos->insert("", $video);
$media = new Google_Http_MediaFileUpload(
$client,
$insertRequest,
'video/*',
null,
true,
$chunkSizeBytes
);
$media->setFileSize(filesize($videoPath));
...
And i'm getting error:
A service error occurred: { "error": { "errors": [ { "domain":
"global", "reason": "authError", "message": "Invalid Credentials",
"locationType": "header", "location": "Authorization" } ], "code":
401, "message": "Invalid Credentials" } }
What i'm missing?
401: Invalid Credentials
Invalid authorization header. The access token you're using is either
expired or invalid.
{
"error": {
"errors": [
{
"domain": "global",
"reason": "authError",
"message": "Invalid Credentials",
"locationType": "header",
"location": "Authorization",
}
],
"code": 401,
"message": "Invalid Credentials"
}
}
Suggested action: Refresh the access token using the long-lived
refresh token.

Google Speech Api PHP fails

I'm trying to use Google speech API in PHP to read text from audio, but it fails with the following: request must contain 'config' field.
This is the code:
<?php
require '../lib/vendor/autoload.php';
$client = new Google_Client();
$client->useApplicationDefaultCredentials();
$client->setAuthConfig(__DIR__.'/config.json');
$client->authorize();
$guzzleClient = new \GuzzleHttp\Client(array( 'curl' => array( CURLOPT_SSL_VERIFYPEER => false)));
$client->setHttpClient($guzzleClient);
$client->addScope('https://www.googleapis.com/auth/cloud-platform');
$speechService = new Google_Service_Speech($client);
$syncRecognize = new Google_Service_Speech_SyncRecognizeRequest();
$config = new Google_Service_Speech_RecognitionConfig();
$config->audioChannels = 1;
$config->encoding = 'LINEAR16';//'audio/wav';
$config->sampleRate = 8000;
$audio = new Google_Service_Speech_RecognitionAudio();
$audio->setContent(file_get_contents('c1.wav'));
$syncRecognize->setAudio($audio);
$syncRecognize->setConfig($config);
$response = $speechService->speech->syncrecognize($syncRecognize);
I receive the following:
Fatal error: Uncaught exception 'Google_Service_Exception' with message '{
"error": {
"code": 400,
"message": "Invalid recognition 'config': request must contain 'config' field.",
"errors": [
{
"message": "Invalid recognition 'config': request must contain 'config' field.",
"domain": "global",
"reason": "badRequest"
}
],
"status": "INVALID_ARGUMENT"
}
}
I can't find any documentation for PHP, so any help would be appreciated.
Try:
$audio->setContent(base64_encode(file_get_contents('c1.wav')));

Symfony Google Drive Api

I used Symfony and I need create file in google drive and add access to write for another user to this file. I read google api drive
intsall google/apiclient
and run qiuck star, I get name for my share file. But I not find how to create new file and how to share this file for some user, this is possible ?
I find how to create file and add to quick start
crate file
$fileMetadata = new Google_Service_Drive_DriveFile(array(
'name' => 'Project plan',
'mimeType' => 'application/vnd.google-apps.drive-sdk'));
$file = $service->files->create($fileMetadata, array(
'fields' => 'id'));
printf("File ID: %s\n", $file->id);
but have error
PHP Fatal error: Uncaught exception 'Google_Service_Exception' with message 'Error calling POST https://www.googleapis.com/drive/v3/files?fields=id: (403) Insufficient Permission' in /home/ivan/host/aog-code/vendor/google/apiclient/src/Google/Http/REST.php:110
{
"error": {
"errors": [
{
"domain": "global",
"reason": "insufficientPermissions",
"message": "Insufficient Permission"
}
],
"code": 403,
"message": "Insufficient Permission"
}
}
how to correct add file and add to permission for some user to this file ?

Youtube Data API v3 Failed to start the resumable upload

As of this morning I'm getting this error when trying to upload a Video with the service account and key, this worked at around 6pm yesterday.
I've tried it with both the resumable option set to true and false but to no avail.
This is my code
$client = new Google_Client();
$client->setClientId($OAUTH2_CLIENT_ID);
$key = file_get_contents($KEY_FILE);
$client->setAssertionCredentials(new Google_AssertionCredentials(
$SERVICE_ACCOUNT_NAME,
array('https://www.googleapis.com/auth/youtube'),
$key)
);
$client->setClientSecret($OAUTH2_CLIENT_SECRET);
$redirect = filter_var('http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'],
FILTER_SANITIZE_URL);
//$client->setRedirectUri($redirect);
$htmlBody = '';
// YouTube object used to make all API requests.
$youtube = new Google_YoutubeService($client);
I get back a valid bearer signature from here but when I initiate the upload I get the following error when setting the non resumable flag to false:
$media = new Google_MediaFileUpload('video/mp4', null, true, $chunkSizeBytes);
"error": {
"errors": [
{
"domain": "youtube.header",
"reason": "youtubeSignupRequired",
"message": "Unauthorized",
"locationType": "header",
"location": "Authorization"
}
],
"code": 401,
"message": "Unauthorized"
}
I hadn't set my access token which referenced the credentials. Make sure you set your access tokens!

Categories