无法使用 PHP 的 API 访问 Youtube

Posted

技术标签:

【中文标题】无法使用 PHP 的 API 访问 Youtube【英文标题】:can't access to Youtube using the API using Php 【发布时间】:2021-12-04 21:51:01 【问题描述】:

所以我正在制作一个上传视频的网站。 我试图实现对 Youtube 的访问并从网站上传视频到 YT 并且正在工作一半的视频上传到 phpmyadmin 表创建行但之后我只得到一个空白页面而不是谷歌的身份验证页面访问 YouTube。 这是代码:

<?php

 require_once "Database_connection.php";
 require_once "Database_config.php";
 require_once "Database_class.php";
 require_once "Session.php";
  
 db = new DB;

 if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['submit']))   

$title = $_POST['Title'];
$description = $_POST['Description'];
$corso = trim($_POST['SceltaCorso']);
$tags = $_POST['tags'];
$privacy = !empty($_POST['privacy'])?$_POST['privacy']:'public';
/* al momento la variabile è disattivata perchè tutti i video verranno caricati su youtube però alcuni visibili altri privati
$youtube = trim($_POST['SceltaYoutube']);   
*/
/*limite modificato dalla configurazione vai su XAMPP riga APACHE tasto CONFIG e poi modifica 
  post_max_size = 40M; upload_max_filesize = 40M; (valori originali per ora sostituiti con 5G)*/
$maxsize = 42949672960;  //al momento la dimensione massima e di 5GB  

//if di controllo che sia stato inserito un file image con peso sotto i 5GB e gli si da le coordinate fino alla cartella di destinazione        
if (isset($_FILES['image']['name']) && $_FILES['image']['name'] != '') 

    $name_img = $_FILES['image']['name'];
    $target_dir_img = "../img/Thumbnail_Video/";
    $target_file_img = $target_dir_img.$name_img;       

    if ($_FILES['image']['size'] >= $maxsize) 
        echo "Il file è troppo grande";
    else

        move_uploaded_file($_FILES['image']['tmp_name'], $target_file_img);
    

elseif (isset($_FILES['image']['name']) == "false" ) 
    $target_file_img = "../img/Thumbnail_Video/logo_STM.png";
  
/*12/08/21 Provare a creare una tabella del database che raccolga dati solo temporaneamente per creare una anteprima del file da caricare (ES. tabella Video_Temp) */
//12/08/2021 Aggiungere la data di inserimento del file
if($_FILES["file"]["name"] != '')
    // File upload path
    $fileName = basename($_FILES["file"]["name"]);
    $filePath = "../Video/".$fileName;
    
    // Check the file type
    $allowedTypeArr = array("video/mp4", "video/avi", "video/mpeg", "video/mpg", "video/mov", "video/wmv", "video/rm");
    if(in_array($_FILES['file']['type'], $allowedTypeArr))
        // Upload file to local server
        if(move_uploaded_file($_FILES['file']['tmp_name'], $filePath))
            // Insert video data in the database
            $vdata = array(
                'Title' => $title,
                'Description' => $description,
                'Tags' => $tags,
                'Privacy' => $privacy,
                'File_name' => $fileName
            );
            $insert = $db->insert($vdata);
            
            // Store db row id in the session
            $_SESSION['uploadedFileId'] = $insert;
        else
            header("Location:".BASE_URL."Video.php?err=ue");
            exit;
        
    else
        header("Location:".BASE_URL."Video.php?err=fe");
        exit;
    
else
    header('Location:'.BASE_URL.'Video.php?err=bf');
    exit;



 // Get uploaded video data from database
 $videoData = $db->getRow($_SESSION['uploadedFileId']);

 // 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_URL);
   

 if (isset($_SESSION[$tokenSessionKey])) 
 $client->setAccessToken($_SESSION[$tokenSessionKey]);


  // Check to ensure that the access token was successfully acquired.
 if ($client->getAccessToken()) 
   
   try
// REPLACE this value with the path to the file you are uploading.
$videoPath = 'videos/'.$videoData['File_name'];

if(!empty($videoData['Youtube_video_id']))
    // Uploaded video data
    $videoTitle = $videoData['Title'];
    $videoDesc = $videoData['Description'];
    $videoTags = $videoData['Tags'];
    $videoId = $videoData['Youtube_video_id'];
else
    // Create a snippet with title, description, tags and category ID
    // Create an asset resource and set its snippet metadata and type.
    // This example sets the video's title, description, keyword tags, and
    // video category.
    $snippet = new Google_Service_YouTube_VideoSnippet();
    $snippet->setTitle($videoData['Title']);
    $snippet->setDescription($videoData['Description']);
    $snippet->setTags(explode(",", $videoData['Tags']));

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

    // Set the video's status to "public". Valid statuses are "public",
    // "private" and "unlisted".
    $status = new Google_Service_YouTube_VideoStatus();
    $status->privacyStatus = $videoData['Privacy'];

    // 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(filesize($videoPath));


    // 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);
    
    // Update youtube video id to database
    $db->update($videoData['Video_id'], $status['Video_id']);
    
    // Delete video file from local server
    @unlink("../Video/".$videoData['File_name']);
    
    // uploaded video data
    $videoTitle = $status['snippet']['Title'];
    $videoDesc = $status['snippet']['Description'];
    $videoTags = implode(",",$status['snippet']['Tags']);
    $videoId = $status['Video_id'];


// uploaded video embed html

$youtubeURL = 'https://youtu.be/'.$videoId;
$htmlBody .= "<p class='succ-msg'>Video Uploaded to YouTube</p>";
$htmlBody .= '<embed   
 src="https://www.youtube.com/embed/'.$videoId.'"></embed>';
$htmlBody .= '<ul><li><b>YouTube URL: </b><a href="'.$youtubeURL.'">'.$youtubeURL.'</a></li>';
$htmlBody .= '<li><b>Title: </b>'.$videoTitle.'</li>';
$htmlBody .= '<li><b>Description: </b>'.$videoDesc.'</li>';
$htmlBody .= '<li><b>Tags: </b>'.$videoTags.'</li></ul>';
$htmlBody .= '<a href="../Php/Logout.php">Logout</a>';

   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()));
  $htmlBody .= 'Please reset session <a href="../Php/Logout.php">Logout</a>';
 

  $_SESSION[$tokenSessionKey] = $client->getAccessToken();
  elseif (OAUTH_CLIENT_ID == '') 
  $htmlBody = <<<END
 <h3>Client Credentials Required</h3>
 <p>
   You need to set <code>\$oauthClientID</code> and
   <code>\$oauthClientSecret</code> before proceeding.
  <p>
    END;
   else 
    // If the user hasn't authorized the app, initiate the OAuth flow
  $state = mt_rand();
  $client->setState($state);
  $_SESSION['state'] = $state;

  $authUrl = $client->createAuthUrl();
  $htmlBody = <<<END
  <h3>Authorization Required</h3>
  <p>You need to <a href="$authUrl">authorize access</a> before proceeding.<p>
  END;
  
   ?>

我认为问题出在这一行之后:$insert = $db-&gt;insert($vdata);,但我找不到它。欢迎提出建议和建议,谢谢。

【问题讨论】:

【参考方案1】:

我认为您的代码中发生了很多事情,您应该将其拆分以便能够更好地调试您的问题。

这是我用于授权的代码。看看吧。

oauth2callback.php

require_once __DIR__ . '/vendor/autoload.php';
require_once __DIR__ . '/Oauth2Authentication.php';

// Start a session to persist credentials.
session_start();

// Handle authorization flow from the server.
if (! isset($_GET['code'])) 
    $client = buildClient();
    $auth_url = $client->createAuthUrl();
    header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL));
 else 
    $client = buildClient();
    $client->authenticate($_GET['code']); // Exchange the authencation code for a refresh token and access token.
    // Add access token and refresh token to seession.
    $_SESSION['access_token'] = $client->getAccessToken();
    $_SESSION['refresh_token'] = $client->getRefreshToken();    
    //Redirect back to main script
    $redirect_uri = str_replace("oauth2callback.php",$_SESSION['mainScript'],$client->getRedirectUri());    
    header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));


?>



require_once __DIR__ . '/vendor/autoload.php';
/**
 * Gets the Google client refreshing auth if needed.
 * Documentation: https://developers.google.com/identity/protocols/OAuth2
 * Initializes a client object.
 * @return A google client object.
 */
function getGoogleClient() 
    $client = getOauth2Client();

    // Refresh the token if it's expired.
    if ($client->isAccessTokenExpired()) 
        $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
        file_put_contents($credentialsPath, json_encode($client->getAccessToken()));
    
return $client;


/**
 * Builds the Google client object.
 * Documentation: https://developers.google.com/identity/protocols/OAuth2
 * Scopes will need to be changed depending upon the API's being accessed.
 * Example:  array(Google_Service_Analytics::ANALYTICS_READONLY, Google_Service_Analytics::ANALYTICS)
 * List of Google Scopes: https://developers.google.com/identity/protocols/googlescopes
 * @return A google client object.
 */
function buildClient()
    
    $client = new Google_Client();
    $client->setAccessType("offline");        // offline access.  Will result in a refresh token
    $client->setIncludeGrantedScopes(true);   // incremental auth
    $client->setAuthConfig(__DIR__ . '/client_secrets.json');
    $client->addScope([YOUR SCOPES HERE]);
    $client->setRedirectUri(getRedirectUri());  
    return $client;


/**
 * Builds the redirect uri.
 * Documentation: https://developers.google.com/api-client-library/python/auth/installed-app#choosingredirecturi
 * Hostname and current server path are needed to redirect to oauth2callback.php
 * @return A redirect uri.
 */
function getRedirectUri()

    //Building Redirect URI
    $url = $_SERVER['REQUEST_URI'];                    //returns the current URL
    if(strrpos($url, '?') > 0)
        $url = substr($url, 0, strrpos($url, '?') );  // Removing any parameters.
    $folder = substr($url, 0, strrpos($url, '/') );   // Removeing current file.
    return (isset($_SERVER['HTTPS']) ? "https" : "http") . '://' . $_SERVER['HTTP_HOST'] . $folder. '/oauth2callback.php';

Oauth2Authentication.php

    /**
     * Authenticating to Google using Oauth2
     * Documentation:  https://developers.google.com/identity/protocols/OAuth2
     * Returns a Google client with refresh token and access tokens set. 
     *  If not authencated then we will redirect to request authencation.
     * @return A google client object.
     */
    function getOauth2Client() 
        try 
            
            $client = buildClient();
            
            // Set the refresh token on the client. 
            if (isset($_SESSION['refresh_token']) && $_SESSION['refresh_token']) 
                $client->refreshToken($_SESSION['refresh_token']);
            
            
            // If the user has already authorized this app then get an access token
            // else redirect to ask the user to authorize access to Google Analytics.
            if (isset($_SESSION['access_token']) && $_SESSION['access_token']) 
                
                // Set the access token on the client.
                $client->setAccessToken($_SESSION['access_token']);                 
                
                // Refresh the access token if it's expired.
                if ($client->isAccessTokenExpired())               
                    $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
                    $client->setAccessToken($client->getAccessToken()); 
                    $_SESSION['access_token'] = $client->getAccessToken();              
                           
                return $client; 
             else 
                // We do not have access request access.
                header('Location: ' . filter_var( $client->getRedirectUri(), FILTER_SANITIZE_URL));
            
         catch (Exception $e) 
            print "An error occurred: " . $e->getMessage();
        
    
    ?>

注意:在您的申请被认为是验证过程之前,您的视频将全部保密。因此,在这一点上将其设置为公开已经过时了。

【讨论】:

以上是关于无法使用 PHP 的 API 访问 Youtube的主要内容,如果未能解决你的问题,请参考以下文章

10月31日V1被取消后,如何继续使用PHP客户端库'googleapis / google-api-php-client'访问'Youtube Analytics API&#

IIS Web 服务器上的 Youtube 数据 API V3 PHP 无法正常工作

无法通过 api 调用 pauseVideo 访问 youtube 嵌入式 iframe

PHP Youtube Data API:未捕获的异常:必须通过composer或下载完整的软件包来安装此库

如何使用 Java API 访问 YouTube 观看次数

YouTube API v3无法正常使用[重复]