ccc

API YouTube: Escribir comentario en un vídeo

Debes tener PHP 8.0 como mínimo para usar apiClient 2.0
composer require google/apiclient:^2.0
if (!isset($_SESSION)) {
  session_start();
}
DEFINE("GOOGLE_CLIENT_ID","8824XXXX");
DEFINE("GOOGLE_CLIENT_SECRET","GOCSPXXXXX");
DEFINE("GOOGLE_REDIRECT_URL","https://loquesea.com/pruebas/prueba.php");
DEFINE("VIDEO_ID","iouKxxxx");
DEFINE("CHANNEL_ID","UCoM0yxxxxx");

$apiKey = "AIzaSyDwe6war7EzN49EZfxorKXp6Oynvnw8v3g";
$clientId = "882415682099-689roe1l9lm2bjoupekn591n8rib2rc3.apps.googleusercontent.com";
$clientSecret = "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";
$channelId = "UCoM0y3Ys6dE1V-ldTpWKPQQ";
$videoId = "iouKgnDDIX4";

if (!file_exists(__DIR__ . '/vendor/autoload.php')) {
  throw new Exception(sprintf('Please run "composer require google/apiclient:~2.0" in "%s"', __DIR__));
}

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

$client = new Google_Client();

$client->setApplicationName('edc_youtube_add_coment');
$client->setClientId(GOOGLE_CLIENT_ID);
$client->setClientSecret(GOOGLE_CLIENT_SECRET);
$client->setRedirectUri(GOOGLE_REDIRECT_URL);
$client->addScope(['https://www.googleapis.com/auth/youtube.force-ssl']);

if (isset($_GET['code'])) {
    try {
        /*
        $arrAccessToken = $client->authenticate($_GET['code']);
        // print_r($accessToken);exit;
        
        $client->setAccessToken($arrAccessToken["access_token"]);
        */
        
        $arrAccessToken = $client->fetchAccessTokenWithAuthCode($_GET['code']);
        // print_r($arrAccessToken);
        echo "access_token:".$arrAccessToken["access_token"]."<hr>";
        // exit;
        // print_r($arrAccessToken);exit;
        $client->setAccessToken($arrAccessToken);

        // print_r($client);exit;
        $service = new Google_Service_YouTube($client);
        // print_r($service);exit;
        
        // echo "accessTOKEN:";print_r($accessToken);exit;
        $commentSnippet = new Google_Service_YouTube_CommentSnippet();
        $commentSnippet->setTextOriginal("lo que sea dos");
        $commentSnippet->setVideoId(VIDEO_ID);
        $commentSnippet->setChannelId(CHANNEL_ID);

        # Create a top-level comment with snippet.
        $topLevelComment = new Google_Service_YouTube_Comment();
        $topLevelComment->setSnippet($commentSnippet);
        

        # Create a comment thread snippet with channelId and top-level comment.
        $commentThreadSnippet = new Google_Service_YouTube_CommentThreadSnippet();
        $commentThreadSnippet->setVideoId(VIDEO_ID);
        $commentThreadSnippet->setChannelId(CHANNEL_ID);
        $commentThreadSnippet->setTopLevelComment($topLevelComment);

        # Create a comment thread with snippet.
        $commentThread = new Google_Service_YouTube_CommentThread();
        $commentThread->setSnippet($commentThreadSnippet);

        // print_r($commentThread);exit;
        // echo "antes";exit;

        // Call the YouTube Data API's commentThreads.insert method to create a comment.
        
        // print_r($commentThread);
        // echo "a insertar:";
        $resp = $service->commentThreads->insert('snippet', $commentThread);
        // $resp = $service->commentThreads->insert('snippet', $commentThread);



        echo "Todo OK";
    } catch (Exception $exception) {
        print_r($exception->getMessage());
    }    
} else {
    $authUrl = $client->createAuthUrl();
    header('Location: '.$authUrl);
}



Otra forma de hacerlo sería mediante JS:
<?php
$apiKey = "AIzaXXXX";
$clientId = "8824XXXX";
$channelId = "UCoM0y3YXCXXXX";
$videoId = "iouKXXXXXX";
?>

<script src="https://apis.google.com/js/api.js"></script>
<script>
  /**
   * Sample JavaScript code for youtube.commentThreads.insert
   * See instructions for running APIs Explorer code samples locally:
   * https://developers.google.com/explorer-help/code-samples#javascript
   */

  function authenticate() {
    return gapi.auth2.getAuthInstance()
        .signIn({scope: "https://www.googleapis.com/auth/youtube.force-ssl"})
        .then(function() { console.log("Sign-in successful"); },
              function(err) { console.error("Error signing in", err); });
  }
  function loadClient() {
    gapi.client.setApiKey("<?=$apiKey;?>");
    return gapi.client.load("https://www.googleapis.com/discovery/v1/apis/youtube/v3/rest")
        .then(function() { console.log("GAPI client loaded for API"); },
              function(err) { console.error("Error loading GAPI client for API", err); });
  }
  // Make sure the client is loaded and sign-in is complete before calling this method.
  function execute() {
    return gapi.client.youtube.commentThreads.insert({
      "part": [
        "snippet"
      ],
      "resource": {
        "snippet": {
          "topLevelComment": {
            "snippet": {
              "textOriginal": "prueba tres",
              "channelId": "<?=$channelId;?>",
              "videoId": "<?=$videoId;?>"
            }
          }
        }
      }
    })
        .then(function(response) {
                // Handle the results here (response.result has the parsed body).
                console.log("Response", response);
              },
              function(err) { console.error("Execute error", err); });
  }
  gapi.load("client:auth2", function() {
    gapi.auth2.init({client_id: "<?=$clientId;?>"});
  });
</script>
<button onclick="authenticate().then(loadClient)">authorize and load</button>
<button onclick="execute()">execute</button>

No hay comentarios:

Publicar un comentario