3

私たちのサイトから YouTube にビデオをアップロードする方法を実装する必要があります。私はすでにアプリを Google Cloud に登録しており、必要なクライアント ID、クライアント シークレット コード、ブラウザ キー、リダイレクト URI、サーバー キーをすべて取得しています。また、さまざまなサイトで提案されているように、Youtube Data API V3、Google+ API、Freebase API、YouTube Analytics API をオンにしました。

以下は私のコードです:

    require_once 'google-api-php-client/src/Google_Client.php';
    require_once 'google-api-php-client/src/contrib/Google_YouTubeService.php';

    $client = new Google_Client();
    $client->setApplicationName('Application Name');
    $client->setClientId('CLIENT_ID');
    $client->setClientSecret('CLIENT_SECRET_CODE');
    $client->setRedirectUri('REDIRECT_URI');
    $client->setDeveloperKey('DEVELOPER_KEY');

    $youtube = new Google_YouTubeService($client);
    if (isset($_GET['code'])) {
        $client->authenticate();
        $_SESSION['token'] = $client->getAccessToken();
        $redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
        header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
    }

    if (isset($_SESSION['token'])){
        $client->setAccessToken($_SESSION['token']);
    }

    if ($client->getAccessToken()){
        $path_to_video_to_upload = $_FILES["video"]["tmp_name"];
        $mime_type = $_FILES["video"]["type"];
        $snippet = new Google_VideoSnippet();
        $snippet->setTitle('Highlights');
        $snippet->setDescription('Description Of Video');
        $snippet->setTags(array('training', 'Soccer'));
        $snippet->setCategoryId(17);

        $status = new Google_VideoStatus();
        $status->privacyStatus = "private";

        $video = new Google_Video();
        $video->setSnippet($snippet);
        $video->setStatus($status);

        try {
            $obj = $youtube->videos->insert("status,snippet", $video,
            array("data"=>file_get_contents($path_to_video_to_upload), 
            "mimeType" => $mime_type));
            } catch(Google_ServiceException $e) {
            print "Caught Google service Exception ".$e->getCode(). " message is ".$e->getMessage()." <br>";
            }

    $_SESSION['token'] = $client->getAccessToken();
    }

    else{
            $authUrl = $client->createAuthUrl();
            print "<a href='$authUrl'>Connect Me!</a>";
    }

私はこれらのコードを参照していました: Upload video to Youtube using Youtube API V3 and PHP

http://www.dreu.info/blog/uploading-a-video-to-youtube-through-api-version-3-in-php/

このコードを初めて実行したとき、YouTube アカウントに接続し (YouTube アカウントを Google に管理させるように求める画面が表示されました)、2 回目の試行で、この 401 メッセージ応答が返されました。

これがYouTubeサーバーからの応答です

キャッチされた Google サービス例外 401 メッセージは Error calling POST https://www.googleapis.com/upload/youtube/v3/videos?part=status%2Csnippet&uploadType=multipart&key=AIzaSyCCySI5cToH3sICTmhCEFHW7QkIDptsjXg : (401) Unauthorized

さまざまな解決策を検索しようとしましたが、役に立たなかったようです。どんな助けでも大歓迎です、ありがとう!

フォローアップの質問: 開発者キーはブラウザ キーですか、それともサーバー キーですか? コードでどちらを使用すればよいか混乱しています。キーを切り替えてみましたが、うまくいきませんでした。

4

2 に答える 2