ccc

Mostrando entradas con la etiqueta API YouTube. Mostrar todas las entradas
Mostrando entradas con la etiqueta API YouTube. Mostrar todas las entradas

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>

API YouTube: Obtener todos los datos de un canal

https://www.googleapis.com/youtube/v3/search?key=AIzaXXXX&channelId=UCoM0y3Ys6dE1V-ldTpWKPQQ&part=snippet&maxResults=50

Para saber el Id de tu canal:
1. Inicia sesión en YouTube.
2. En la parte superior derecha, haz clic en tu imagen de perfil y luego Configuración Ajustes.
3. En el menú de la izquierda, selecciona Configuración avanzada.
4. En la página que se abrirá, puedes consultar tanto tu ID de usuario.

API YouTube: Obtener todos los comentarios (Enero/2022)

$key="AIzaXXXX";
$JSONComent = file_get_contents("https://www.googleapis.com/youtube/v3/commentThreads?part=snippet%2Creplies&videoId=".$idVideo."&key=".$key);
$JSONComent = json_decode($JSONComent);

$arrComents = array();
foreach ($JSONComent->items as $clave=>$valor) {
$arrAux = array();
$arrAux["id"] = $valor->snippet->topLevelComment->id;
$arrAux["textDisplay"] = $valor->snippet->topLevelComment->snippet->textDisplay;
$arrAux["publishedAt"] = $valor->snippet->topLevelComment->snippet->publishedAt;
$arrAux["authorDisplayName"] = $valor->snippet->topLevelComment->snippet->authorDisplayName;
$arrAux["authorProfileImageUrl"] = $valor->snippet->topLevelComment->snippet->authorProfileImageUrl;
$arrAux["mainComent"] = 1;
$arrComents[] = $arrAux;

if (isset($valor->replies->comments)) {
$total = count($valor->replies->comments);
for ($i=0;$i<$total;$i++) {
$arrAux = array();
$arrAux["id"] = $valor->replies->comments[$i]->id;
$arrAux["textDisplay"] = $valor->replies->comments[$i]->snippet->textDisplay;
$arrAux["publishedAt"] = $valor->replies->comments[$i]->snippet->publishedAt;
$arrAux["authorDisplayName"] = $valor->replies->comments[$i]->snippet->authorDisplayName;
$arrAux["authorProfileImageUrl"] = $valor->replies->comments[$i]->snippet->authorProfileImageUrl;
$arrAux["mainComent"] = 0;
$arrComents[] = $arrAux;
}
}

$JSONAux = file_get_contents("https://www.googleapis.com/youtube/v3/commentThreads?key=".$key."&part=id,snippet,replies&id=".$valor->id);
$JSONAux = json_decode($JSONAux);

if (isset($JSONAux->items[0]->replies)) {
foreach ($JSONAux->items[0]->replies as $claveAux=>$valorAux) {
$total = count($valorAux);
for ($i=0;$i<$total;$i++) {
$yaEsta = false;
$totArrComent = count($arrComents);
for ($k=0;$k<$totArrComent;$k++) {
if ($arrComents[$k]["id"] == $valorAux[$i]->id) {
$yaEsta = true;
}
}

if (!$yaEsta) {
$arrAux = array();
$arrAux["id"] = $valorAux[$i]->id;
$arrAux["textDisplay"] = $valorAux[$i]->snippet->textDisplay;
$arrAux["publishedAt"] = $valorAux[$i]->snippet->publishedAt;
$arrAux["authorDisplayName"] = $valorAux[$i]->snippet->authorDisplayName;
$arrAux["authorProfileImageUrl"] = $valorAux[$i]->snippet->authorProfileImageUrl;
$arrAux["mainComent"] = 0;
$arrComents[] = $arrAux;
}
}
}
}
} // foreach

API YouTube: meter un vídeo de YouTube como background y sin que salgan los controles

HTML:
<script src="https://www.youtube.com/player_api"></script>
<div id="myid"></div>
<div id="player"></div>

CSS:
#player {width: 100%; height: 100%; position: fixed; z-index: -99;}
#myid {background: rgba(0,0,0,.1); width: 100%; height: 100%; position: fixed; z-index: 1;}
iframe .html5-video-player .html5-watermark {display: none !important;}

JS:
var player;
function onYouTubePlayerAPIReady() {
    player = new YT.Player('player', {
        playerVars: {
            'autoplay': 1,
            'controls': 0,
            'autohide': 1,
            'wmode': 'opaque',
            'showinfo': 0,
            'loop': 1,
            'mute': 1,
'modestbranding': 1,
            //'start': 15,
            //'end': 110,
            'playlist': 'PNmJBaAOiZM'
        },
        videoId: 'PNmJBaAOiZM',
        events: {
            'onReady': onPlayerReady
        }
    });

}

function onPlayerReady(event) {
    event.target.mute();
    $('#text').fadeIn(400);
    //why this? Well, if you want to overlay text on top of your video, you
    //will have to fade it in once your video has loaded in order for this
    //to work in Safari, or your will get an origin error.
}

//this pauses the video when it's out of view, just wrap your video in .m-//video
$(window).scroll(function() {
   var hT = $('.m-video').height(),
       wS = $(this).scrollTop();
   if (wS > hT) {
      player.pauseVideo();
   }
   else {
      player.playVideo();
   }
});

Más información en: https://codepen.io/fecoder/pen/azZYOV

Especial agradecimiento a Vicky Marín

API YouTube: Obtener datos

Obtener las características de un canal
https://www.googleapis.com/youtube/v3/channels?part=snippet&forUsername=Oscars&key=AIzaSyDoYaqpDXkzXXE2VmAS-h23DIYHcN7u4Uc

Obtener el Id de un canal de YouTube:
https://www.googleapis.com/youtube/v3/channels?key=AIzaSyDoYaqpDXkzXXE2VmAS-h23DIYHcN7u4Uc&forUsername=Oscars&part=id

Obtener los vídeos de ese canal:
https://www.googleapis.com/youtube/v3/search?order=date&part=snippet&channelId=UCb-vZWBeWA5Q2818JmmJiqQ&maxResults=25&key=AIzaSyDoYaqpDXkzXXE2VmAS-h23DIYHcN7u4Uc

// Sacar los vídeos de ese canal ordenados por views
https://www.googleapis.com/youtube/v3/search?part=snippet&channelId=UCoM0y3Ys6dE1V-ldTpWKPQQ&maxResults=50&key=AIzaSyDoYaqpDXkzXXE2VmAS-h23DIYHcN7u4Uc&order=viewCount

Al sacar todos los vídeos de un canal SOLO te permite sacar 50 como máximo pero no hay problema porque te devuelve un par de campos (nextPageToken y prevPageToken) que te permitirá hacer paginación solo añadiendo a la url el campo pageToken y así sacar los 50 siguientes y los 50 anteriores, por ejemplo:
https://www.googleapis.com/youtube/v3/search?part=snippet&channelId=UCoM0y3Ys6dE1V-ldTpWKPQQ&maxResults=50&key=AIzaSyDoYaqpDXkzXXE2VmAS-h23DIYHcN7u4Uc&order=viewCount&pageToken=CDIQAA
// Para sacar de cada vídeo del canal los views, los likes, los dislike y el número de comment
https://www.googleapis.com/youtube/v3/videos?part=statistics&id=DvQkuNwCwOo&key=AIzaSyDoYaqpDXkzXXE2VmAS-h23DIYHcN7u4Uc

// Para sacar todos los comentarios de un vídeo:
https://www.googleapis.com/youtube/v3/commentThreads?part=snippet,replies&videoId=0gj4WPPW2AU&fields=etag,eventId,items,kind,nextPageToken,pageInfo,tokenPagination,visitorId&key=AIzaSyDoYaqpDXkzXXE2VmAS-h23DIYHcN7u4Uc
Solo permite sacar 20 comentarios por vídeo pero permite paginación: en el json resultante dispones del campo nextPageToken que te permitirá sacar los siguientes 20 comentarios:
https://www.googleapis.com/youtube/v3/commentThreads?part=snippet,replies&videoId=0gj4WPPW2AU&fields=etag,eventId,items,kind,nextPageToken,pageInfo,tokenPagination,visitorId&key=AIzaSyDoYaqpDXkzXXE2VmAS-h23DIYHcN7u4Uc&pageToken=xxxxxxxxxxxxxxx
LISTAS DE REPRODUCCIÓN

Obtener listas de reproducción:
https://www.googleapis.com/youtube/v3/playlists?part=snippet&channelId=UCoM0y3Ys6dE1V-ldTpWKPQQ&key=AIzaSyDoYaqpDXkzXXE2VmAS-h23DIYHcN7u4Uc&maxResults=50

Solo te saca 50 como máximo pero puedes hacer paginación hacía delante o atrás con el valor que te da los campos:
nextPageToken y prevPageToken, por ejemplo:
https://www.googleapis.com/youtube/v3/playlists?part=snippet&channelId=UCoM0y3Ys6dE1V-ldTpWKPQQ&key=AIzaSyDoYaqpDXkzXXE2VmAS-h23DIYHcN7u4Uc&maxResults=50&pageToken=CAUQAA

Sacar una lista de reproducción en concreto:
https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&playlistId=PLirArnxvBU6p5G7zbTH-qKHXZDNf7rBNW&key=AIzaSyDoYaqpDXkzXXE2VmAS-h23DIYHcN7u4Uc&maxResults=50
También la lista concreta de reproducción tiene nextPageToken y prevPageToken para poder hacer paginación con el parámetro pageToken

Más información en:
https://developers.google.com/youtube/v3/docs/search/list?hl=es-419

YouTube: Capturar eventos mientras se reproduce un vídeo de YouTube

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<script type="text/javascript">
    var tag = document.createElement('script');
    tag.src = "https://www.youtube.com/iframe_api";
    var firstScriptTag = document.getElementsByTagName('script')[0];
    firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

    var player;
    function onYouTubeIframeAPIReady() {
        player = new YT.Player('player', {
            height: '600',
            width: '100%',
            videoId: 'CHNdRDjeopE',
            playerVars : {
                'autoplay': 0,
            },
            events: {
                'onReady': onPlayerReady,
                'onStateChange': onPlayerStateChange
            }
        });
    }

    function onPlayerReady(event) {
        // event.target.playVideo();
    }

    function onPlayerStateChange(event) {
        if (event.data == YT.PlayerState.PLAYING) {
            console.log("Está reproduciendo, lanzar evento que se quiera");
        }
        if (event.data == YT.PlayerState.PAUSED) {
            console.log("Se ha pausado, lanzar evento que se quiera");
        }

    }
</script>
</head>
<body>
<div id="player"></div>
</body>
</html>

Los eventos que se pueden capturar son:
YT.PlayerState.ENDED
YT.PlayerState.PLAYING
YT.PlayerState.PAUSED
YT.PlayerState.BUFFERING
YT.PlayerState.CUED

API YouTube: Operaciones

a) Debes loguearte con la cuenta de gmail.
b) Para crear el canal de la empresa (pq sino te lo asocia a tu nombre de gmail) debes ir a Gestor Canales y te saldrá "Utilizar YouTube como", eliges "Para utilizar un nombre de empresa u otro nombre, haz clic aquí." Creas uno específico para la empresa.
c) Puedes modificar el diseño de la web (la imagen de la portada debe ser como mínimo de 2048X1152).
d) Para acceder externamente al canal: por ejemplo http://www.youtube.com/channel/UC8hekxSbhD42gTeimCVz999

-----------------------

YOUTUBE API

a) Primero registrarte como programador en:
http://code.google.com/apis/youtube/dashboard/ y obtienes tu
clave de desarrollador, por ejemplo: AIzaSyDoYaqpDXkzxxxxxmS-h23DIYHcN7u4Uc

-------------------------------

Obtener las estadísticas de un vídeo:
$JSON = file_get_contents("https://www.googleapis.com/youtube/v3/videos?part=statistics&id=".$idVideo."&key=AIzaXXXXVmAS-h23DIYHcN7u4Uc");

Si falla probar con:
$JSON = file_get_contents("https://www.googleapis.com/youtube/v3/commentThreads?part=snippet&maxResults=15&videoId=".$idVideo."&key=AIzaXXXXXDXkzPWE2VmAS-h23DIYHcN7u4Uc&textFormat=plainText");

$JSON_Data = json_decode($JSON);
// print_r($JSON_Data);exit;
$views = $JSON_Data->items[0]->statistics->viewCount;
$views = number_format($views, 0, ',', '.');
$likeCount  = $JSON_Data->items[0]->statistics->likeCount;
$likeCount = number_format($likeCount, 0, ',', '.');

Obtener los comentarios de un vídeo:
$JSON = file_get_contents("https://www.googleapis.com/youtube/v3/commentThreads?part=snippet%2Creplies&videoId=".$idVideo."&fields=etag%2CeventId%2Citems%2Ckind%2CnextPageToken%2CpageInfo%2CtokenPagination%2CvisitorId&key=AIzaXXXVmAS-h23DIYHcN7u4Uc");
$JSON_comentarios = json_decode($JSON);
foreach($JSON_comentarios->items as $obj){
    echo "<br>".$obj->snippet->topLevelComment->snippet->publishedAt;
    echo "<br>".$obj->snippet->topLevelComment->snippet->authorDisplayName;
    echo "<br>".$obj->snippet->topLevelComment->snippet->authorProfileImageUrl;
    echo "<br>".$obj->snippet->topLevelComment->snippet->textDisplay;
    if (isset($obj->replies->comments[0]->snippet)) { // respuestas a comentarios
       echo "<br>".$obj->replies->comments[0]->snippet->publishedAt;
       echo "<br>".$obj->replies->comments[0]->snippet->authorDisplayName;
       echo "<br>".$obj->replies->comments[0]->snippet->authorProfileImageUrl;
       echo "<br>".$obj->replies->comments[0]->snippet->textDisplay;
    }
} // foreach

Dar formato a la fecha:
$arrFecha = explode(":", $obj->replies->comments[0]->snippet->publishedAt);
$arrEstring = explode("-", $arrFecha[0]);
$ano = $arrEstring[0];
$mes = $arrEstring[1];
$dia = explode("T", $arrEstring[2]);
$fechaFinal = $dia[0]."/".$mes."/".$ano;

Consola de desarrolladores de google:
https://console.developers.google.com/ 

Más información sobre API comentarios:
https://developers.google.com/youtube/v3/docs/comments
https://developers.google.com/youtube/v3/docs/commentThreads
Hacer pruebas:
https://developers.google.com/youtube/v3/docs/comments/list#try-it