не удается получить доступ к Youtube с помощью API с использованием Php

php #google-api #google-oauth #youtube-data-api #google-api-php-client

#php #google-api #google-oauth #youtube-data-api #google-api-php-client

Вопрос:

итак, я создаю сайт для загрузки видео.
Я попытался реализовать доступ к Youtube и загружать видео на YT с сайта и работает наполовину, видео загружается на phpmyadmin в таблице создается строка, но после этого я просто получаю пустую страницу вместо страницы аутентификации Google для доступа к YT.
Вот код:

 <?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" amp;amp; 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']) amp;amp; $_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 amp;amp; !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 width="400" height="315" 
 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->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']) amp;amp; $_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']) amp;amp; $_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();
        }
    }
    ?>
 

Примечание: Все ваши видеоролики будут конфиденциальными до тех пор, пока ваша заявка не будет рассмотрена в процессе проверки. Так что выставление его на всеобщее обозрение на данный момент закончено.