PHP Youtube API v3 - 直接上传 - 未经授权的消息

标签 php youtube google-api-php-client

我正在尝试使用 API v3 将视频直接上传到 Youtube。

我正在使用服务帐户场景(https://developers.google.com/accounts/docs/OAuth2?hl=es&csw=1#scenarios),我解决了google-api-php-client库中的一些问题(读取p12文件并避免isAccessTokenExpired总是返回假)。

<?php
/** Config */ 
$private_key_password = 'notasecret';
$private_key_file = 'xxxxxxxx-privatekey.p12';
$applicationName = 'xxxxx-youtube';
$client_secret = 'CLIENT_SECRET';
$client_id = 'xxxxxxxxxxxxx.apps.googleusercontent.com';
$service_mail = 'xxxxxxxxxxx@developer.gserviceaccount.com';
$public_key = 'xxxxxxxxxxx';

/** Constants */ 
$scope = 'https://www.googleapis.com/auth/youtube';
$url_youtube_token = 'https://accounts.google.com/o/oauth2/token';

/** Create and sign JWT */ 
$jwt = new Google_AssertionCredentials($service_mail, $scope, $private_key_file, $private_key_password, $url_youtube_token);
$jwt_assertion = $jwt->generateAssertion();

/** Use JWT to request token */
$data = array(
    'grant_type' => 'urn:ietf:params:oauth:grant-type:jwt-bearer',
    'assertion' => $jwt_assertion,
);

// use key 'http' even if you send the request to https://...
$options = array(
    'http' => array(
        'header'  => "Content-type: application/x-www-form-urlencoded\r\n",
        'method'  => 'POST',
        'content' => http_build_query($data),
    ),
);

$context = stream_context_create($options);
$result = file_get_contents($url_youtube_token, false, $context);

此时我在 json 响应中获得了访问 token ,如下所示:

{
  "access_token" : "1/8xbJqaOZXSUZbHLl5EOtu1pxz3fmmetKx9W8CV4t79M",
  "token_type" : "Bearer",
  "expires_in" : 3600
}

没有“created”、“refresh_token”和“id_token”字段。因此,我修复了 Google_OAuth2 类中的 setAccessToken 方法,如果未设置,则将“created”字段设置为 time()。否则 isAccessTokenExpired 总是返回 false。

现在,让我们开始上传文件。

    try{
        // Client init 
        $client = new Google_Client();
        $client->setClientId($client_id);
        $client->setClientSecret($client_secret);
        $client->setApplicationName($applicationName);

        $client->setAccessToken($result);

        if ($client->getAccessToken()) {

            if($client->isAccessTokenExpired()) {
                // @TODO Log error 
                echo 'Access Token Expired!!<br/>'; // Debug
            }

            $youtube = new Google_YoutubeService($client);

            $videoPath = "./test.mp4";

            // Create a snipet with title, description, tags and category id
            $snippet = new Google_VideoSnippet();
            $snippet->setTitle("fmgonzalez test " . time());
            $snippet->setDescription("fmgonzalez test " . time() );
            $snippet->setTags(array("tag1", "tag2"));

            // Numeric video category. See
            // https://developers.google.com/youtube/v3/docs/videoCategories/list
            $snippet->setCategoryId("22");

            // Create a video status with privacy status. Options are "public", "private" and "unlisted".
            $status = new Google_VideoStatus();
            $status->privacyStatus = "public";

            // Create a YouTube video with snippet and status
            $video = new Google_Video();
            $video->setSnippet($snippet);
            $video->setStatus($status);

            // Size of each chunk of data in bytes. Setting it higher leads faster upload (less chunks,
            // for reliable connections). Setting it lower leads better recovery (fine-grained chunks)
            $chunkSizeBytes = 1 * 1024 * 1024;

            // Create a MediaFileUpload with resumable uploads
            $media = new Google_MediaFileUpload('video/*', null, true, $chunkSizeBytes);
            $media->setFileSize(filesize($videoPath));

            // Create a video insert request
            $insertResponse = $youtube->videos->insert("status,snippet", $video,
                array('mediaUpload' => $media));

            $uploadStatus = false;

            // Read file and upload chunk by chunk
            $handle = fopen($videoPath, "rb");
            $cont = 1;
            while (!$uploadStatus && !feof($handle)) {
                $chunk = fread($handle, $chunkSizeBytes);
                $uploadStatus = $media->nextChunk($insertResponse, $chunk);
                echo 'Chunk ' . $cont . ' uploaded <br/>';
                $cont++;
            }

            fclose($handle);

            echo '<br/>OK<br/>';

        }else{
            // @TODO Log error 
            echo 'Problems creating the client';
        }

    } catch(Google_ServiceException $e) {
        print "Caught Google service Exception ".$e->getCode(). " message is ".$e->getMessage(). " <br>";
        print "Stack trace is ".$e->getTraceAsString();
    }catch (Exception $e) {
        echo $e->getMessage();
    }

但我收到一条“无法开始可续传上传” 消息。

调试,Google_MediaFileUpload 中的方法 getResumeUri 我有这个响应正文:

"error": {
    "errors": [
    {
        "domain": "youtube.header",
        "reason": "youtubeSignupRequired",
        "message": "Unauthorized",
        "locationType": "header",
        "location": "Authorization"
    }
    ],
    "code": 401,
    "message": "Unauthorized"
}

我找到了有关其他场景的示例,但没有找到有关此场景的示例。

我应该怎么做才能最终上传视频文件?关于这种情况的任何例子?

提前致谢。

最佳答案

它可能看起来微不足道,但您是否在要将视频上传到的帐户中至少创建了一个 channel 。我对 access_token 使用了与您几乎相同的解决方法,然后遇到了同样的问题,直到我进入我的 Youtube 帐户上传部分并看到消息在上传视频之前至少创建了一个 channel 。希望对您有所帮助。

关于PHP Youtube API v3 - 直接上传 - 未经授权的消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21723447/

相关文章:

php - 如何在用户注册时创建目录(PHP)

php - mySQL 和 html 形式

php - YouTube API v3 停止返回 status.publishAt

google-drive-api - 使用 Google Picker 从 Google Drive 下载文件

php - 如何使用分页检索下一个结果集?

php - Google+ 身份验证 : refreshToken() returns invalid_grant error

php - 从 PHP 中的大型 CSV 文件中读取多列

php - 从 mysql 中的两个不同表中选择总计但得到不同的答案

api - 使用GoogleCL上传YouTube视频

api - YouTube API v3 : a Video Response's contentDetails. contentRating