在 cron 作业中使用 auth 2 的 Youtube api

问题描述 投票:0回答:2

我创建了一个 php 脚本,用于在 auth2.0 的帮助下获取我的 youtube 频道的 youtube 视频数据,包括未列出的视频。我的问题是如何在没有任何用户交互的情况下在 cron 作业中运行脚本? 无法使用服务帐户,因为 youtube api 不支持它以及脚本如何选择要选择的帐户?

<?php

require_once __DIR__ . '/vendor/autoload.php';
session_start();


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

$client = new Google_Client();
$client->setApplicationName('youtubeproject');
$client->setDeveloperKey(" ");
$client->setAccessType('offline');
$client->setScopes([
    'https://www.googleapis.com/auth/youtube.readonly',
]);
$client->setAuthConfig(' ');

//$client->setApprovalPrompt('consent');
//$client->setIncludeGrantedScopes(true);
$client->setPrompt('consent');
$client->setIncludeGrantedScopes(true);
$client->createAuthUrl();

if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
  $client->setAccessToken($_SESSION['access_token']);

  $youtube = new Google_Service_YouTube($client);
  


  $i=0;
  $pagetoken='';
  $pagetoken1='';
  youtube_calls_playlist($pagetoken);
  youtube_callsplaylistitems($pagetoken1);
} else {
        $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
  $redirect_uri = 'http://localhost/youtubeproject/' . 'oauth2callback.php/';
  header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}
function youtube_calls_playlist($pagetoken){
   
global $youtube;
global $total_ids;
if($pagetoken!=''){
       $queryParams_playlists = [
    'mine' => true,
    'pageToken'=> $pagetoken
     ];
}
else{
     $queryParams_playlists = [
    'mine' => true,
    ];
}
$response_playlists=  $youtube->playlists->listPlaylists('snippet', $queryParams_playlists);

foreach ($response_playlists->items as $playlistsid) {
    $id= $playlistsid->id;
    $ids[] = $id;

}
   
if(isset($response_playlists->nextPageToken)){
    $pagetoken=$response_playlists->nextPageToken;
    youtube_calls($pagetoken);
}
$queryParams_uploads = [
      'mine' => true
      ];

$response_uploads = $youtube->channels->listChannels('contentDetails', $queryParams_uploads);
foreach ($response_uploads->items as $uploadsid) {
     $upid= $uploadsid->contentDetails->relatedPlaylists->uploads;
     $ids1[] = $upid;
}

$total_ids=array_merge($ids,$ids1); 

}

function youtube_callsplaylistitems($pagetoken1){

global $youtube;
global $total_ids;
global $result;

if($pagetoken1!=''){
       $queryParams = [
    'playlistId' => $total_ids,
    'pageToken'=> $pagetoken
     ];
}
else{
     $queryParams = [
    'playlistId' => $total_ids];
}
 
$response = $youtube->playlistItems->listPlaylistItems('snippet', $queryParams);
foreach($response->items as $videos){
    $videoid=$videos->snippet->resourceId->videoId;
    $publishedat=$videos->snippet->publishedAt;
    $queryParams_videos= [
    'id' => $videoid];
    $response_videos = $youtube->videos->listVideos('snippet', $queryParams_videos);
    foreach($response_videos->items as $vids){
    $i=0;
    
    $description= $vids->snippet->description;
    $title= $vids->snippet->title;
    $thumbnail=$vids->snippet->thumbnails->default->url;
       $videoids[]= $videoid;
    $descriptions[]= $description;
    $titles[]=$title;
       $thumbnails[]=$thumbnail;
    }
 
   
if(isset($response->nextPageToken)){
    $pagetoken1=$response->nextPageToken;
    youtube_calls_playlist($pagetoken1);
}

   }
 
  
$result = array();
$values = array($videoids, $descriptions, $titles, $thumbnails);

foreach($videoids as $index => $key) {
    $t = array();
    foreach($values as $value) {
    $t[] = $value[$index];
}
    $result[]  = $t;
}
   print_r(json_encode($result));
 
}
?>

oauth2callback.php 代码是

<?php

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

session_start();

//$client = new Google\Client();
$client = new Google_Client();
$client->setAccessType('offline');
$client->setAuthConfigFile('client_secret_843932249311-9ittju7rjic43jh86g8talo2it8socj2.apps.googleusercontent.com.json');
$client->setRedirectUri('http://localhost/youtubeproject/' . 'oauth2callback.php/');

$client->setScopes([
    'https://www.googleapis.com/auth/youtube.readonly',
]);

if (! isset($_GET['code'])) {
  $auth_url = $client->createAuthUrl();
  header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL));

} else {
  $client->authenticate($_GET['code']);
  $_SESSION['access_token'] = $client->getAccessToken();
  $redirect_uri = 'http://localhost/youtubeproject/index.php' . '/';
  header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}

?>

我想在没有任何浏览器的情况下在 cron 作业中没有任何用户交互的情况下运行它。不知道怎么做。

php oauth-2.0 cron youtube-api
2个回答
0
投票

在没有任何用户交互的情况下在 cron 作业中运行脚本的最佳方法是使用服务帐户。服务帐户是属于应用程序或服务而不是单个用户的帐户。使用服务帐户,您可以在无需任何用户交互的情况下向 YouTube API 验证您的应用程序。

要创建服务帐户,请按照 Google Cloud Platform 文档中的说明进行操作。创建服务帐户后,您需要使用 Google APIs 控制台为该帐户生成私钥。您将使用私钥向 YouTube API 验证您的应用程序。

一旦你有了私钥,你就可以用它来验证你的应用程序到 YouTube API。您可以使用 Google_Client 类来设置身份验证。这是一个如何做到这一点的例子:

// Create a new Client
$client = new Google_Client();

// Set the application name
$client->setApplicationName('My App Name');

// Set the access type to offline so that we can get a refresh token
$client->setAccessType('offline');

// Set the scopes for the API
$client->setScopes(['https://www.googleapis.com/auth/youtube.readonly']);

// Set the private key
$client->setAuthConfigFile('<path_to_private_key_file>');

// Get the access token
$client->fetchAccessTokenWithAssertion();

// Get the YouTube service
$youtube = new Google_Service_YouTube($client);

// Make API calls
$videos = $youtube->videos->listVideos(...);

// Run the script as a cron job
$cron = new CronJob(function() use ($youtube) {
    // Do whatever you need to do here
    // ...
    
    // Make API calls
    $videos = $youtube->videos->listVideos(...);
});
$cron->run();

一旦您通过 YouTube API 对您的应用程序进行了身份验证,您就可以使用该 API 发出 API 请求,而无需任何用户交互。然后,您可以在没有任何用户交互的情况下将脚本作为 cron 作业运行。


0
投票

我通过获取访问令牌和刷新令牌更新代码并保存到文件中并在 cronjob 中使用它而无需进入浏览器和用户交互。

<?php
$tokenFile   = 'C:\xampp\htdocs\youtubeproject\token.txt';
require_once __DIR__ . '/vendor/autoload.php';
session_start();


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

$client = new Google_Client();
$client->setApplicationName('');
$client->setDeveloperKey("");
$client->setAccessType('offline');
$client->setScopes([
    'https://www.googleapis.com/auth/youtube.readonly',
]);
$client->setAuthConfig('');

//$client->setApprovalPrompt('consent');
$client->setIncludeGrantedScopes(true);
$client->setPrompt('consent');
$client->setIncludeGrantedScopes(true);

// Load previously authorized credentials from a file.
    if (file_exists($tokenFile)) {
        $accessToken = json_decode(file_get_contents($tokenFile), true);
        $client->setAccessToken($accessToken);

}
else{
       if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
              $client->setAccessToken($_SESSION['access_token']);
 $accessTokenSaved= $client->getAccessToken();


 if(!file_exists(dirname($tokenFile))) {
                mkdir(dirname($tokenFile), 0700, true);
            }
file_put_contents($tokenFile, json_encode($accessTokenSaved));
}else
{
  if ($client->isAccessTokenExpired()) 
{
    // the new access token comes with a refresh token as well
    $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
   $accessTokenUpdated['refresh_token'] = $refreshTokenSaved;

        // save to file
        file_put_contents($tokenFile, json_encode($accessTokenUpdated));
}
}
}


 $youtube = new Google_Service_YouTube($client);
  


  $i=0;
  $pagetoken='';
  $pagetoken1='';
  youtube_calls_playlist($pagetoken);
  youtube_callsplaylistitems($pagetoken1);

function youtube_calls_playlist($pagetoken){
   
global $youtube;
global $total_ids;
if($pagetoken!=''){
       $queryParams_playlists = [
    'mine' => true,
    'pageToken'=> $pagetoken
     ];
}
else{
     $queryParams_playlists = [
    'mine' => true,
    ];
}
$response_playlists=  $youtube->playlists->listPlaylists('snippet', $queryParams_playlists);

foreach ($response_playlists->items as $playlistsid) {
    $id= $playlistsid->id;
    $ids[] = $id;

}
   
if(isset($response_playlists->nextPageToken)){
    $pagetoken=$response_playlists->nextPageToken;
    youtube_calls($pagetoken);
}
$queryParams_uploads = [
      'mine' => true
      ];

$response_uploads = $youtube->channels->listChannels('contentDetails', $queryParams_uploads);
foreach ($response_uploads->items as $uploadsid) {
     $upid= $uploadsid->contentDetails->relatedPlaylists->uploads;
     $ids1[] = $upid;
}

$total_ids=array_merge($ids,$ids1); 

}

function youtube_callsplaylistitems($pagetoken1){

global $youtube;
global $total_ids;
global $result;

if($pagetoken1!=''){
       $queryParams = [
    'playlistId' => $total_ids,
    'pageToken'=> $pagetoken
     ];
}
else{
     $queryParams = [
    'playlistId' => $total_ids];
}
 
$response = $youtube->playlistItems->listPlaylistItems('snippet', $queryParams);
foreach($response->items as $videos){
    $videoid=$videos->snippet->resourceId->videoId;
    $publishedat=$videos->snippet->publishedAt;
    $queryParams_videos= [
    'id' => $videoid];
    $response_videos = $youtube->videos->listVideos('snippet', $queryParams_videos);
    foreach($response_videos->items as $vids){
    $i=0;
    
    $description= $vids->snippet->description;
    $title= $vids->snippet->title;
    $thumbnail=$vids->snippet->thumbnails->default->url;
       $videoids[]= $videoid;
    $descriptions[]= $description;
    $titles[]=$title;
       $thumbnails[]=$thumbnail;
    }
 
   
if(isset($response->nextPageToken)){
    $pagetoken1=$response->nextPageToken;
    youtube_calls_playlist($pagetoken1);
}

   }
 
  
$result = array();
$values = array($videoids, $descriptions, $titles, $thumbnails);

foreach($videoids as $index => $key) {
    $t = array();
    foreach($values as $value) {
    $t[] = $value[$index];
}
    $result[]  = $t;
}
   print_r(json_encode($result));
 
}
?>

© www.soinside.com 2019 - 2024. All rights reserved.