0

I am trying to set up a YouTube API connection test (with the test code provided by the API).

I have:

  • created an API key;
  • created an OAuth and placed the file on my server;
  • the time on my server is well synchronized.

And I get the following error:

Fatal error: Uncaught InvalidArgumentException: Invalid code in /home/.../src/Client.php:239
Stack trace:
#0 /home/.../test.php(35): Google\Client->fetchAccessTokenWithAuthCode('')
#1 {main} thrown in /home/.../src/Client.php on line 239

My code :

<?php
define('STDIN',fopen("php://stdin","r"));

/**
 * Sample PHP code for youtube.channels.list
 * See instructions for running these code samples locally:
 * https://developers.google.com/explorer-help/guides/code_samples#php
 */

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

$client = new Google_Client();
$client->setApplicationName('API code samples');
$client->setScopes([
    'https://www.googleapis.com/auth/youtube.readonly',
]);

// 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('apiGoogle/code_secret_client_80354467589-77athnqb19ps1daaskbr8dm1plhrkind.apps.googleusercontent.com.json');
$client->setAccessType('offline');

// Request authorization from the user.
$authUrl = $client->createAuthUrl();
printf("Open this link in your browser:\n%s\n", $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 = [
    'forUsername' => 'GoogleDevelopers'
];

$response = $service->channels->listChannels('snippet,contentDetails,statistics', $queryParams);
print_r($response);
Linda Lawton - DaImTo
  • 106,405
  • 32
  • 180
  • 449
  • Do post your code, please! – stvar Jan 28 '21 at 12:01
  • Have you copy-pasted the *auth code* (obtained upon issuing the URL `$authUrl` within a browser) back to your app's prompt `Enter verification code:`? Do note that your app received an empty `$authCode` upon executing the statement `$authCode = trim(fgets(STDIN));`. This indicates that you just pressed Enter at that prompt prior to pasting anything to it. – stvar Jan 28 '21 at 13:29
  • Are you running your app from [command line](https://www.php.net/manual/en/features.commandline.differences.php)? The [official PHP spec](https://www.php.net/manual/en/features.commandline.io-streams.php) of `STDIN` says: *An already opened stream to stdin. This saves opening it with *. – stvar Jan 28 '21 at 13:39

1 Answers1

0

The $authCode you are sending is not valid. Try following this instead. Make sure that you have properly configured the redirect uri in google developer console.

oauth2callback.php

<?php

// Load the Google API PHP Client Library.
require_once __DIR__ . '/vendor/autoload.php';

// Start a session to persist credentials.
session_start();

// Create the client object and set the authorization configuration
// from the client_secrets.json you downloaded from the Developers Console.
$client = new Google_Client();
$client->setAuthConfig(__DIR__ . '/client_secrets.json');
$client->setRedirectUri('http://' . $_SERVER['HTTP_HOST'] . '/oauth2callback.php');
$client->addScope(Google_Service_YouTube::YOUTUBE_READONLY);

// Handle authorization flow from the server.
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://' . $_SERVER['HTTP_HOST'] . '/';
  header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}
?>
Linda Lawton - DaImTo
  • 106,405
  • 32
  • 180
  • 449
  • Thanks a lot but i have : "Erreur 400 : redirect_uri_mismatch The redirect URI in the request, http://www.chambaud-abstrait.com/oauth2callback.php, does not match the ones authorized for the OAuth client. To update the authorized redirect URIs, visit: https://console.developers.google.com/apis/credentials/oauthclient/${your_client_id}?project=${your_project_number}" – Anthony Chambaud Artiste pein Jan 28 '21 at 13:05
  • you need to properly set up the redirect URI in google developer console. – Linda Lawton - DaImTo Jan 28 '21 at 13:16