Quantcast
Channel: Active questions tagged youtube-api - Stack Overflow
Viewing all articles
Browse latest Browse all 3831

Google API client (YouTube) errors

$
0
0

I'm trying to implement uploading video to YouTube from the server but I'm having problems with that. I'm using Laravel 9 and Google API client for php. The code is like this, pretty much the same as a google example:

public function goToAuthUrl() {    $client = new Client();    $client->setApplicationName('Test');    $client->setScopes([        YouTube::YOUTUBE_UPLOAD,    ]);    $client->setAuthConfig('client_secret_***.apps.googleusercontent.com.json');    $client->setAccessType('offline');    $authUrl = $client->createAuthUrl();    return redirect()->away($authUrl);}public function youtubeHandle(Request $request) {    session_start();    $htmlBody = '';    $client = new Google_Client();    $client->setAuthConfigFile('client_secret_***.apps.googleusercontent.com.json');    $client->setRedirectUri('https://***/youtube');    $client->addScope(YouTube::YOUTUBE_UPLOAD);    if (!isset($request->code)) {        $auth_url = $client->createAuthUrl();    } else {        $accessToken = $client->fetchAccessTokenWithAuthCode($request->code);        $client->setAccessToken($accessToken);        try{            $videoPath = url('storage/images/rain.mp4');            // Define an object that will be used to make all API requests.            $youtube = new Google_Service_YouTube($client);            $snippet = new Google_Service_YouTube_VideoSnippet();            $snippet->setTitle("Test title");            $snippet->setDescription("Test description");            $snippet->setTags(array("test"));            // Numeric video category.            $snippet->setCategoryId(27);            // Set the video's status to "public". Valid statuses are "public",            // "private" and "unlisted".            $status = new Google_Service_YouTube_VideoStatus();            $status->privacyStatus = "unlisted";            // Associate the snippet and status objects with a new video resource.            $video = new Google_Service_YouTube_Video();            $video->setSnippet($snippet);            $video->setStatus($status);            // Specify the size of each chunk of data, in bytes. Set a higher value for            // reliable connection as fewer chunks lead to faster uploads. Set a lower            // value for better recovery on less reliable connections.            $chunkSizeBytes = 1 * 1024 * 1024;            // Setting the defer flag to true tells the client to return a request which can be called            // with ->execute(); instead of making the API call immediately.            $client->setDefer(true);            // Create a request for the API's videos.insert method to create and upload the video.            $insertRequest = $youtube->videos->insert("status,snippet", $video);            // Create a MediaFileUpload object for resumable uploads.            $media = new Google_Http_MediaFileUpload(                $client,                $insertRequest,'video/*',                null,                true,                $chunkSizeBytes            );            $media->setFileSize(Storage::size('public/images/rain.mp4'));            // Read the media file and upload it chunk by chunk.            $status = false;            $handle = fopen($videoPath, "rb");            while (!$status && !feof($handle)) {                $chunk = fread($handle, $chunkSizeBytes);                $status = $media->nextChunk($chunk);            }            fclose($handle);            // If you want to make other calls after the file upload, set setDefer back to false            $client->setDefer(false);            $htmlBody .= "<h3>Video Uploaded</h3><ul>";            $htmlBody .= sprintf('<li>%s (%s)</li>',                $status['snippet']['title'],                $status['id']);            $htmlBody .= '</ul>';        } catch (Google_Service_Exception $e) {            $htmlBody .= sprintf('<p>A service error occurred: <code>%s</code></p>',                htmlspecialchars($e->getMessage()));        } catch (Google_Exception $e) {            $htmlBody .= sprintf('<p>An client error occurred: <code>%s</code></p>',                htmlspecialchars($e->getMessage()));        }        $_SESSION['token'] = $client->getAccessToken();    }    echo $htmlBody;

So, oauth process goes well, first I run goToAuthUrl() function, give the permissions, it redirects me back to the website and runs youtubeHandle() function. And here are the problems. It throws an error

Invalid request. The number of bytes uploaded is required to be equal or greater than 262144, except for the final request (it's recommended to be the exact multiple of 262144). The received request contained 16098 bytes, which does not meet this requirement.

and points to this line $status = $media->nextChunk($chunk);.

I tried to find the solutions and change the code, like changing $insertRequest variable to this:

$insertRequest = $youtube->videos->insert("status,snippet", $video, ['data' => file_get_contents(url('storage/images/rain.mp4')),'mimeType' => 'video/*','uploadType' => 'multipart']);

This way it throws another error

Failed to start the resumable upload (HTTP 200)

and video isn't being created on the channel.

Could you tell me where's the problem?


Viewing all articles
Browse latest Browse all 3831

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>