web-dev-qa-db-fra.com

API client Google - Paramètre require manquant: redirect_uri

J'ai donc suivi le guide quickstart et décidé de le diviser en une classe appelée planificateur. Je travaille sur le code d'authentification, mais je continue à recevoir ce qui suit: "Erreur 400 (erreur OAuth 2) Erreur Demande invalide manquante requis Paramètre: redirect_uri".

class scheduler{

//The Google Client object
private $googleClient;

//the Google Calendar Service ojbect
private $calendarService;

/*
*   Google Calendar Setup
*
*   This creates a Google Client object so that you may create a Google Calendar object.
*
*/
function __construct(){
    //set the application name
    define("APPLICATION_NAME", "Web client 1");
    //
    define("CREDENTIALS_PATH", "~/scheduler/credentials.json");
    //
    define("CLIENT_SECRET_PATH", __DIR__ . "/scheduler/client_secret.json");
    //
    define("SCOPES", implode(" ", array(Google_Service_Calendar::CALENDAR_READONLY)));

    /*if(php_sapi_name() != "cli"){
        throw new Exception("This application must be run on the command line");    
    }*/

    //create the google client
    $this->googleClient = new Google_Client();

    //setup the client
    $this->googleClient->setApplicationName(APPLICATION_NAME);
    $this->googleClient->setDeveloperKey("AIzaSyBmJLvNdMYuFhVpWalkUdyStrEBoVEayYM");
    $this->googleClient->setScopes(SCOPES);
    $this->googleClient->setAuthConfigFile(CLIENT_SECRET_PATH);
    $this->googleClient->setAccessType("offline");

    //get the credentials file path
    $credentialsPath = expandHomeDirectory(CREDENTIALS_PATH);

    //if the file exists
    if(file_exists($credentialsPath)){

        //get the credentials from the file
        $accessToken = file_get_contents($credentialsPath); 

    }//if it does not
    else{

        //request the authorization url
        $authURL = $this->googleClient->createAuthUrl();
        //print the authorization ulr
        echo "<a href=\"$authURL\">Press Me</a><br /><br />";

        //Prompt the user to enter the auth code
        print("Enter authentication code: ");

        //
        $authCode = trim(fgets(STDIN));

        //exchange authorization for an access token
        $accessToken = $this->googleClient->authenticate($authCode);

        //store credentials to disk
        if(!file_exists(dirname($credentialsPath))){
            mkdir(dirname($credentialsPath), 0700, true);   
        }

        //put the contents into the credential files
        file_put_contents($credentialsPath, $accessToken);
    }

    $this->googleClient->setAccessToken($accessToken);

    //refresh token if its expired
    if($this->googleClient->isAccessTokenExpired()){
        $this->googleClient->refreshToken($client->getRefreshToken());

        file_put_contents($credentialsPath, $this->googleClient->getAccessToken()); 
    }
}

J'ai trouvé la cause du problème sans solution en vue. Sous ma console de développeur Google, j'ai essayé de placer " http: // localhost/ " dans la section URI de redirection autorisée. Cela me donne l’erreur "Désolé, il ya un problème. Si vous avez entré des informations, vérifiez-les et essayez à nouveau. Sinon, le problème pourrait disparaître tout seul, alors revenez plus tard." Existe-t-il un moyen de faire en sorte que Google Developer Console accepte l’URI de redirection d’un serveur localhost?

7
Joshua Blevins

Je l'ai fait au travail. Ce que je devais faire était de retourner dans la console développeur de Google et de supprimer le projet que j'avais créé. Ensuite, lors de la création d'un nouveau projet, cela m'a permis de sauvegarder mon URL localhost. Le problème qui se posait était quand je suis allé aller ajouter mon URL localhost à l'URL de redirection, il dirait que ce n'est pas possible pour le moment. Lorsque je définis l'URL de redirection avant d'appuyer sur le bouton de création, il l'accepte parfaitement.

5
Joshua Blevins

Utilisez simplement la méthode setRedirectUri($absoluteUrl) sur un objet client:

$client = new Google_Client();
$client->setRedirectUri('http://' . $_SERVER['HTTP_Host'] . '/oauth2callback.php');

via:

https://developers.google.com/api-client-library/php/auth/web-app

8
James07

La documentation "PHP Quick Start" de Google pour l'API Feuille semble être obsolète à l'adresse https://developers.google.com/sheets/api/quickstart/php .

Pour que leur démo fonctionne avec PHP 7.2+, j'ai dû modifier pas mal de choses, et ce n'est pas tout à fait clair. Vous trouverez ci-dessous une version commentée et mise à jour de leur guide de démarrage rapide qui peut être utile à quiconque éprouvant des difficultés à utiliser l'API Google Sheets et PHP.

<?php
/**
 * Updated Google Sheets Quickstart
 *
 * https://developers.google.com/sheets/api/quickstart/php
 */
require __DIR__ . '/vendor/autoload.php';

/**
 * Returns an authorized API client.
 * @return Google_Client the authorized client object
 */
function getClient() {

     // Change this to a secure location where you'll save your config *.json files
     // Make sure it isn't publicly available on the web
    $configPath = getcwd();

    // This get's generated by the script, so don't create it
    $credentialsPath = $configPath . 'credentials.json';

    $client = new Google_Client();

    // Matches the "Application Name" you enter during the "Step 1" wizard
    $client->setApplicationName( 'API App Name' );
    $client->setScopes( Google_Service_Sheets::SPREADSHEETS_READONLY );

    // You need to go through "Step 1" steps to generate this file: https://developers.google.com/sheets/api/quickstart/php
    $client->setAuthConfig( $configPath . 'client_secret.json' );
    $client->setAccessType( 'offline' );

    // This must match the "callback URL" that you enter under "OAuth 2.0 client ID" in the Google APIs console at https://console.developers.google.com/apis/credentials
    $client->setRedirectUri( 'https://' . $_SERVER['HTTP_Host'] . '/' . basename( __FILE__, '.php' ) );

    // We have a stored credentials file, try using the data from there first
    if ( file_exists( $credentialsPath ) ) {
        $accessToken = json_decode( file_get_contents( $credentialsPath ), true );
    }

    // No stored credentials found, we'll need to request them with OAuth
    else {

        // Request authorization from the user
        $authUrl = $client->createAuthUrl();
        if ( ! isset( $_GET['code'] ) ) {
            header( "Location: $authUrl", true, 302 );
            exit;
        }

        // The authorization code is sent to the callback URL as a GET parameter.
        // We use this "authorization code" to generate an "access token". The
        // "access token" is what's effectively used as a private API key.
        $authCode = $_GET['code'];
        $accessToken = $client->fetchAccessTokenWithAuthCode( $authCode );

        // Create credentials.json if it doesn't already exist (first run)
        if ( ! file_exists( dirname( $credentialsPath ) ) ) {
            mkdir( dirname( $credentialsPath ), 0700, true );
        }

        // Save the $accessToken object to the credentials.json file for re-use
        file_put_contents( $credentialsPath, json_encode( $accessToken ) );
    }

    // Provide client with API access token
    $client->setAccessToken( $accessToken );

    // If the $accessToken is expired then we'll need to refresh it
    if ( $client->isAccessTokenExpired() ) {
        $client->fetchAccessTokenWithRefreshToken( $client->getRefreshToken() );
        file_put_contents( $credentialsPath, json_encode( $client->getAccessToken() ) );
    }

    return $client;
}

// Get the API client and construct the service object.
$client = getClient();
$service = new Google_Service_Sheets( $client );

// Get values from a spreadheet and print
// https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/get
$spreadsheetId = '1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms';
$range = 'Class Data!A2:E';
$response = $service->spreadsheets_values->get($spreadsheetId, $range);
$values = $response->getValues();

if (empty($values)) {
    print "No data found.\n";
} else {
    print "Name, Major:\n";
    foreach ($values as $row) {
        // Print columns A and E, which correspond to indices 0 and 4.
        printf("%s, %s\n", $row[0], $row[4]);
    }
}
0
Kevin Leary