Bonjour,

En utilisant les API Google, j'aurais aimé récupérer la liste des chaînes auxquelles je suis abonné depuis mon compte Youtube. Pour cela, j'ai utilisé la bibliothèque PHP suivante: https://packagist.org/packages/league/oauth2-client. Après avoir appliqué toutes les informations nécessaires, j'obtiens l'erreur suivante: Uncaught UnexpectedValueException: Invalid response received from Authorization Server. Expected JSON.

Voici mon code:

<?php

require 'vendor/autoload.php';

$provider = new \League\OAuth2\Client\Provider\GenericProvider([
    'clientId'                => 'my_oauth_client_id',    // The client ID assigned to you by the provider
    'clientSecret'            => 'my_oauth_client_secret',   // The client password assigned to you by the provider
    'redirectUri'             => 'http://localhost/oauthytb/index.php',
    'urlAuthorize'            => 'https://accounts.google.com/o/oauth2/v2/auth',
    'urlAccessToken'          => 'https://oauth2.googleapis.com/token',
    'urlResourceOwnerDetails' => 'https://www.googleapis.com/auth/youtube.readonly'
]);

// If we don't have an authorization code then get one
if (!isset($_GET['code'])) {
    $options = [
        'scope' => ['https://www.googleapis.com/auth/youtube.readonly']
    ];

    // Fetch the authorization URL from the provider; this returns the
    // urlAuthorize option and generates and applies any necessary parameters
    // (e.g. state).
    $authorizationUrl = $provider->getAuthorizationUrl($options);

    // Get the state generated for you and store it to the session.
    $_SESSION['oauth2state'] = $provider->getState();

    // Redirect the user to the authorization URL.
    header('Location: ' . $authorizationUrl);
    exit;

// Check given state against previously stored one to mitigate CSRF attack
} elseif (empty($_GET['state']) || (isset($_SESSION['oauth2state']) && $_GET['state'] !== $_SESSION['oauth2state'])) {

    if (isset($_SESSION['oauth2state'])) {
        unset($_SESSION['oauth2state']);
    }

    exit('Invalid state');

} else {

    try {

        // Try to get an access token using the authorization code grant.
        $accessToken = $provider->getAccessToken('authorization_code', [
            'code' => $_GET['code']
        ]);

        // We have an access token, which we may use in authenticated
        // requests against the service provider's API.
        echo 'Access Token: ' . $accessToken->getToken() . "<br>";
        echo 'Refresh Token: ' . $accessToken->getRefreshToken() . "<br>";
        echo 'Expired in: ' . $accessToken->getExpires() . "<br>";
        echo 'Already expired? ' . ($accessToken->hasExpired() ? 'expired' : 'not expired') . "<br>";

        // Using the access token, we may look up details about the
        // resource owner.
        $resourceOwner = $provider->getResourceOwner($accessToken);

        var_export($resourceOwner->toArray());

        // The provider provides a way to get an authenticated API request for
        // the service, using the access token; it returns an object conforming
        // to Psr\Http\Message\RequestInterface.
        $request = $provider->getAuthenticatedRequest(
            'GET',
            'https://www.googleapis.com/youtube/v3/subscriptions',
            $accessToken
        );

    } catch (\League\OAuth2\Client\Provider\Exception\IdentityProviderException $e) {

        // Failed to get the access token or user details.
        exit($e->getMessage());

    }

}

?>

Merci d'avance pour votre aide.
Quentin

2 réponses


quenquen147
Auteur
Réponse acceptée

J'ai finalement trouvé le problème, cela provient de l'URL renseigné dans le urlResourceOwnerDetails dans le provider. L'url est la suivante : https://www.googleapis.com/youtube/v3/subscriptions?part=snippet%2CcontentDetails&mine=true&key=AIzaSyDay5KNU_TPCD-s_n7t6Xqqr

Bonjour,

Il faut debuger en mode pas-à-pas pour trouver où ça pete...

Déjà est-ce que l'objet $provider est bien créé ?