mardi 28 juin 2016

Google API with cURL in PHP: Uncaught Google_Auth_Exception: Error fetching OAuth2 access token

I'm fairly new to cURL and the Google API and I'm having a hell of a time getting it to work. I've finally got something but I keep getting this error:

<b>Fatal error</b>:  Uncaught Google_Auth_Exception: Error fetching OAuth2 access token, message: 'redirect_uri_mismatch' in /var/www/go/public_html/google-api-php-client/src/Google/Auth/OAuth2.php:126
Stack trace:
#0 /var/www/go/public_html/google-api-php-client/src/Google/Client.php(128): Google_Auth_OAuth2-&gt;authenticate('4/u5tgg1I4A64Cs...', false)
#1 /var/www/go/public_html/page/users.php(34): Google_Client-&gt;authenticate('4/u5tgg1I4A64Cs...')
#2 {main}
  thrown in <b>/var/www/go/public_html/google-api-php-client/src/Google/Auth/OAuth2.php</b> on line <b>126</b><br />

Here is the code I'm trying to execute:

require_once('../include/header.php');
require_once('../include/sidebar.php');
require_once('../google-api-php-client/src/Google/autoload.php');

if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {    
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, "https://www.googleapis.com/admin/directory/v1/groups?fields=etag%2Cgroups%2Ckind%2CnextPageToken&key={MY GOOGLE API KEY}");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
    $headers = array();
    $headers[] = "content-type:  application/json; charset=UTF-8";
    $headers[] = "Authorization: GoogleLogin auth=".$_SESSION['access_token'];
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    $return = curl_exec($ch);
    if (curl_errno($ch)) {
    echo 'Error:' . curl_error($ch);
    }
    curl_close($ch);
        $return = json_decode($return, true);

}
else {
    $client = new Google_Client();
    $client->setAuthConfigFile('{MY CLIENT SECRET JSON}');
    $client->setRedirectUri('https://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
    $client->addScope('https://www.googleapis.com/auth/admin.directory.group');

    if(!isset($_GET['code'])) {
      $auth_url = $client->createAuthUrl();
      header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL));
    }
    if(isset($_GET['code'])) {
      $client->authenticate($_GET['code']);
      $_SESSION['access_token'] = $client->getAccessToken();
      $redirect_uri = 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
      header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
    }
}
?>

Any idea what's wrong? The url I'm requesting from has been added to the Console so I'm not sure why there's a redirect issue? And I reuploaded my client_secret.json file.

Any suggestions welcome!

Aucun commentaire:

Enregistrer un commentaire