没有OAuth 2.0授权的Youtube Data API



我正在尝试构建一个简单的流程。访问Youtube数据API并获取有关Youtube频道的信息。

我在使用phpGET:之前已经做过这件事

file_get_contents('https://www.googleapis.com/youtube/v3/search?key=MYKEY&channelId= CHANNELID&maxResults=10&order=date&type=video&part=snippet');

但现在我想创建一个使用谷歌客户端访问数据的cron作业,如下所示:

<?php
require_once'/home/PROJECT/vendor/autoload.php';
$client = new Google_Client();
$client->setApplicationName('API code samples');
$client->setScopes([
'https://www.googleapis.com/auth/youtube.force-ssl',
]);
// TODO: For this request to work, you must replace
//       "YOUR_CLIENT_SECRET_FILE.json" with a pointer to your
//       client_secret.json file. For more information, see
//       https://cloud.google.com/iam/docs/creating-managing-service-account-keys
$client->setAuthConfig('client_secret.json');
$client->setAccessType('offline');
// Request authorization from the user.
$authUrl = $client->createAuthUrl();
printf("Open this link in your browser:n%sn", $authUrl);
print('Enter verification code: ');
$authCode = trim(fgets(STDIN));
// Exchange authorization code for an access token.
$accessToken = $client->fetchAccessTokenWithAuthCode($authCode);
$client->setAccessToken($accessToken);
// Define service object for making API requests.
$service = new Google_Service_YouTube($client);
$queryParams = [
'channelId' => 'CHANNELID',
'type' => 'video'
];
$response = $service->search->listSearch('snippet', $queryParams);
print_r($response);
?>

我很困惑。使用phpGET,我只需要一个API密钥。但对于谷歌客户端,我需要授权。为什么?我可以使用Google客户端使用API密钥吗?我创建了密钥,并希望在cron作业中运行它。但我会遇到这样的错误:

Open this link in your browser: https://accounts.google.com/o/oauth2/auth?response_type=code&access_type=offline&client_id=CLIENTID.apps.googleusercontent.com&redirect_uri=https%3A%2F%2FTEST.co&state&scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fyoutube.force-ssl&approval_prompt=auto Enter verification code:
Warning: Use of undefined constant STDIN - assumed 'STDIN' (this will throw an Error in a future version of PHP) in /var/www/html/index.php on line 21
Warning: fgets() expects parameter 1 to be resource, string given in /var/www/html/index.php on line 21
Fatal error: Uncaught InvalidArgumentException: Invalid code in /home/matthew/vendor/google/apiclient/src/Client.php:248 Stack trace: #0 /var/www/html/index.php(24): GoogleClient->fetchAccessTokenWithAuthCode() #1 {main} thrown in /home/matthew/vendor/google/apiclient/src/Client.php on line 248

我做错了什么?

我找到了答案。公共数据不需要OAuth 2.0。只需要setDeveloperKey
<?php
require_once'/home/PROJECT/vendor/autoload.php';
$client = new Google_Client();
$client->setApplicationName('API code samples');
$client->setDeveloperKey('API_KEY');
$service = new Google_Service_YouTube($client);
$queryParams = [
'channelId' => 'ID',
'type' => 'video'
];
$response = $service->search->listSearch('snippet', $queryParams);
print_r($response);
?>

最新更新