Youtube Data API v3 Failed to start the resumable upload - php

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!

Related

Upload to youtube via google api v3 (php) with refresh and access token

I wish to develop one restful app where users will upload video to youtube via some admin interface. Since users will only upload on behalf of my name and in one channel I want to make authentication only once and then use refresh token to get access token.
So what I did is the following
I have visited https://developers.google.com and select and authorize all Youtube data API v3 API's with my email
Exchange authorization code for tokens (so now I have Authorization code, refresh and access token)
Code implementation (stuck here, can't imagine huh?)
$client = new Google_Client();
$client->setApplicationName('myApp');
$client->setClientId('<client-id>');
$client->setClientSecret('<client-secret>');
$client->setDeveloperKey('<dev-key>'); // <- do I really need that
$client->setScopes('https://www.googleapis.com/auth/youtube.force-ssl https://www.googleapis.com/auth/youtube.upload https://www.googleapis.com/auth/youtubepartner https://www.googleapis.com/auth/youtube https://www.googleapis.com/auth/youtubepartner-channel-audit https://www.googleapis.com/auth/youtube.readonly');
$client->refreshToken('<my-refresh-token>');
$client->setAuthConfig('client_secrets.json'); // <- is that the same as setting clientId and ClientSecret???
$client->setAccessType('offline');
$client->setApprovalPrompt('force');
$accessToken = $client->getAccessToken();
if (is_null($accessToken) || $client->isAccessTokenExpired()) {
// How to refresh token with REFRESH token?
dd($_GET);
}
// Define service object for making API requests.
$service = new Google_Service_YouTube($client);
// Define the $video object, which will be uploaded as the request body.
$video = new Google_Service_YouTube_Video();
// Add 'snippet' object to the $video object.
$videoSnippet = new Google_Service_YouTube_VideoSnippet();
$videoSnippet->setCategoryId('1');
$videoSnippet->setChannelId('<my-channel-id>');
$videoSnippet->setDescription('Description of uploaded video.');
$videoSnippet->setTags(['tag', 'tag2', 'tag3']);
$videoSnippet->setTitle('Test video upload.');
$video->setSnippet($videoSnippet);
// Add 'status' object to the $video object.
$videoStatus = new Google_Service_YouTube_VideoStatus();
$videoStatus->setEmbeddable(true);
$videoStatus->setLicense('youtube');
$videoStatus->setPrivacyStatus('private');
$video->setStatus($videoStatus);
$queryParams = [
'stabilize' => false
];
// TODO: For this request to work, you must replace "YOUR_FILE"
// with a pointer to the actual file you are uploading.
// The maximum file size for this operation is 64GB.
$response = $service->videos->insert(
'snippet,status',
$video,
$queryParams,
array(
'data' => file_get_contents($fullFilePath),
'mimeType' => 'video/*',
'uploadType' => 'multipart'
)
);
print_r($response);
So now I have several problems, which I don't know how to tackle.
Which $client->.... functions must be present if I'm already authorized (via OAuth playground)
How to refresh token with refresh token?
So far the only response I get is Google_Service_Exception
Message: { "error": { "errors": [ { "domain": "global", "reason": "required", "message": "Login Required", "locationType": "header", "location": "Authorization" } ], "code": 401, "message": "Login Required" } }
It's my second day of trying to upload video via api with PHP and it's driving me nuts. I hope you guys will help me out.
If you need any additional informations, please let me know and I will provide. Thank you!!
UPDATE
After adding following code
$client->setAccessToken('<ACCESS_TOKEN>');
I get following errors
div style="border:1px solid #990000;padding-left:20px;margin:0 0 10px 0;">
<h4>An uncaught Exception was encountered</h4>
<p>Type: Google_Service_Exception</p>
<p>Message: {
"error": {
"errors": [
{
"domain": "youtube.quota",
"reason": "quotaExceeded",
"message": "The request cannot be completed because you have exceeded your \u003ca href=\"/youtube/v3/getting-started#quota\"\u003equota\u003c/a\u003e."
}
],
"code": 403,
"message": "The request cannot be completed because you have exceeded your \u003ca href=\"/youtube/v3/getting-started#quota\"\u003equota\u003c/a\u003e."
}
}
</p>
<p>Filename: /home/vagrant/workspace/spot-scouting-adminpage/rest/vendor/google/apiclient/src/Google/Http/REST.php</p>
<p>Line Number: 118</p>
Which is of course not true, since I have never made a single successful request to google. Here is prof:
Maybe the problem is that a have generated access key via developers.google.com???
You have missed just a small step to set access token.
Once you get the access token set it with google client :
$client->setAccessToken($accessToken);
And then use youtube service:
$service = new Google_Service_YouTube($client);

Error when creating folder in google drive

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.

Allow users to upload videos to my youtube channel without login

I have selected Application type "other and web application" while creating separate projects in Youtube developer console and using following code.
$scope = array('https://www.googleapis.com/auth/youtube.upload', 'https://www.googleapis.com/auth/youtube');
$client = new Google_Client();
$client->setClientId($OAUTH2_CLIENT_ID);
$client->setClientSecret($OAUTH2_CLIENT_SECRET);
$client->setAccessType('offline');
$client->setApprovalPrompt('force');
$client->setAccessToken('ya29.GlyKBK9LdtYRLNDYUdhXlhTiY_d51nLUZrIdikYoRY3M_5YQOpt5Pkx-uJ1RYpsvPOKyf4hTNBhKwOJ_fEncTURyNBeZa9ISRoVAmcuFaAlI_YgcQAs97GCbHklvXg');
$client->setScopes($scope);
$youtube = new Google_Service_YouTube($client);
// Check if an auth token exists for the required scopes
$tokenSessionKey = 'token-' . $client->prepareScopes();
if (isset($_GET['code'])) {
if (strval($_SESSION['state']) !== strval($_GET['state'])) {
die('The session state did not match.');
}
$client->authenticate($_GET['code']);
$_SESSION[$tokenSessionKey] = $client->getAccessToken();
header('Location: ' . $redirect);
}
if (isset($_SESSION[$tokenSessionKey])) {
$client->setAccessToken($_SESSION[$tokenSessionKey]);
}
But it always give following error.
A service error occurred: { "error": { "errors": [ { "domain":
"global", "reason": "authError", "message": "Invalid Credentials",
"locationType": "header", "location": "Authorization" } ], "code":
401, "message": "Invalid Credentials" } }
I am not getting what I am doing wrong and what could be the possible fix for this?

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.

Multichannels on YouTube with YouTube Analytics API

I have a youtube account with 5 channels. With the YouTube Analytics API can I get data from the primary youtube channel. But the other channels I get always error message
forbidden
Also I am the owner from these all channels.
Here my sourcecode:
$client = new Google_Client();
$client->setAuthConfig('client_secrets.json');
$client->setScopes( array(
'https://www.googleapis.com/auth/youtube.force-ssl',
'https://www.googleapis.com/auth/youtubepartner-channel-audit',
'https://www.googleapis.com/auth/youtube',
'https://www.googleapis.com/auth/youtube.readonly',
'https://www.googleapis.com/auth/yt-analytics.readonly',
'https://www.googleapis.com/auth/yt-analytics-monetary.readonly',
'https://www.googleapis.com/auth/youtubepartner')
);
$client->setAccessType("offline");
$json_str = file_get_contents("access_token.json");
$json = json_decode($json_str, true);
if (isset($json['access_token']) && $json['access_token']) {
$client->setAccessToken($json_str);
$youtube = new Google_Service_YouTubeAnalytics($client);
$report = $youtube->reports->query('channel==UC0xxxxxxxxxxx', '2017-04-01', '2017-04-30', 'views');
echo json_encode($report);
} else {
$redirect_uri = 'https://xxxxxxxxxx/oauth2callback.php';
header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}
If i have in the query-Command channel==MINE or the YouTube Channel-ID (UC0xxxxxxx) is work very well. But the other Channel-ID from the same youtube account I get this error:
PHP Fatal error: Uncaught exception 'Google_Service_Exception' with message '{
"error": {
"errors": [
{
"domain": "global",
"reason": "forbidden",
"message": "Forbidden"
}
],
"code": 403,
"message": "Forbidden"
}
}
How I can fix it?

Categories