Search code examples
phpgoogle-tasks-api

Google task api authentication not working php


I have a file called TasksLogin.php which lets me login

session_start();
require_once 'google-api-php-client/src/Google_Client.php';
require_once 'google-api-php-client/src/contrib/Google_TasksService.php';
$client = new Google_Client();
$client->setClientId('xxxxx.apps.googleusercontent.com');
$client->setClientSecret('xxxxxxxxx');
$client->setRedirectUri('http://xxxxxxxxx/Tasks/TaskVis.html');
$client->setApplicationName("TasksForMike");
$tasksService = new Google_TasksService($client);

if (isset($_REQUEST['logout'])) {
  unset($_SESSION['token']);
}

if (isset($_SESSION['token'])) {
  $client->setAccessToken($_SESSION['token']);

} else {
  $client->setAccessToken($client->authenticate($_GET['code']));
  $_SESSION['token'] = $client->getAccessToken();

}

if (isset($_GET['code'])) {
  $redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
  header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
}
?>
<?php $_SESSION['token'] = $client->getAccessToken(); ?>

That seems to work because it redirects to TaskVis.php But in TasksVis.php I call:

$(document).ready(function() {
  $.get("tasks.php", function(data){
var json = data;
});
 });

which is the php file that gets the tasks and packages them up in a json object. but in tasks.php, I have this code that crashes:

session_start();
require_once 'google-api-php-client/src/Google_Client.php';
require_once 'google-api-php-client/src/contrib/Google_TasksService.php';
$client = new Google_Client();
$client->setClientId('xxxxxx.apps.googleusercontent.com');
$client->setClientSecret('xxxxxxxxxxxxxxx');
$client->setRedirectUri('http://xxxxxxxxx/Tasks/TaskVis.html');
$client->setApplicationName("TasksForMike");
$tasksService = new Google_TasksService($client);

if (isset($_REQUEST['logout'])) 
{
  unset($_SESSION['token']);
}
 if (isset($_GET['code'])) {
  $client->authenticate($_GET['code']);
  echo "hh";
  die();
  $_SESSION['token'] = $client->getAccessToken();
  header('Location: http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']);

}
?>

the "die" never runs and I get a 500 server error. Since the code is in the query string, why is the $client->authenticate($_GET['code']); failing ? I am trying to seperate the data code from the rendering.


Solution

  • I don't think there's any 'code' in the query string. Your 'code' value is lost when you redirect to TaskVis.php and don't include it in the redirect. Then, in that file, you're calling tasks.php here...

    $.get("tasks.php", function(data){
    

    ...so if there were any _GET values, they would be included in the call:

    $.get("tasks.php?code=xxxx", function(data){
    

    I'd be interested in knowing the nature of the 500 error also. Have you tried calling this while viewing the console in Firebug?