尝试使用google PHP api使用referesh令牌

时间:2015-08-23 12:58:33

标签: php oauth google-api

这是我第一次通过谷歌登录,我是初学程序员。我一直坚持使用google api和outh 2来实现刷新令牌。

以下是我用来实现登录的代码

<?php 
ob_start();
session_start();
require_once 'init.php'; 

require('vendor/autoload.php');

//Details for setting up the google login

$client = new Google_Client();
$client->setAccessType("offline");
$client->setAuthConfigFile('client_secrets.json');
$client->setScopes(array('https://www.googleapis.com/auth/plus.login','https://www.googleapis.com/auth/userinfo.email', 'https://www.googleapis.com/auth/plus.me'));
$oauth2 = new Google_Service_Oauth2($client);


/************************************************
  Logout function
 ************************************************/
if (isset($_REQUEST['logout'])) {
  unset($_SESSION['token']);
  $client->revokeToken();
   header('Location:http://localhost:1234/trial/log-inlogic/'); 
}

/************************************************
  Get the code back from the OAuth 2.0 flow,
  exchange that with the authenticate()
  function. 
 ************************************************/
if (isset($_GET['code'])) {
    $client->authenticate($_GET['code']);
    $_SESSION['token'] = $client->getAccessToken();
    header('Location: http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']);
}

/************************************************
  If we have an access token, I make
  requests, else I generate an authentication URL.
 ************************************************/
if (isset($_SESSION['token'])) {
    $client->setAccessToken($_SESSION['token']);
}
else {
  $authUrl = $client->createAuthUrl();
}

/************************************************
 In case the token is expired, this is where i have a problem
************************************************/
if ($client->getAccessToken()) {
  //Check if our token has expired.
  if ($client->isAccessTokenExpired()) {        
      // create this function to store the referesh token in the database

     $refreshToken = getRefreshToken();
     $client->refreshToken($refreshToken);
  } 

   //Basic User Information
 $user = $oauth2->userinfo->get();
    try {
    google_login( $user );
    }catch (Exception $e) {
        $error = $e->getMessage();
    }

  $_SESSION['token']=$client->getAccessToken();
  //Save the refresh token on our database.
}

//Simple function to store a given refresh_token on a database
function setRefreshToken () {  
  if (isset($_SESSION['k_id'])) {
    $k_id=$_SESSION['k_id'];
     $accesstoken=$_SESSION['token'];
$token=json_decode($_SESSION['token']);
echo $token->refresh_token;
    $result =query("UPDATE users SET refreshtoken=$token WHERE k_id='$k_id'");
  }  
}

//Retrieves the refresh_token from our database.
function getRefreshToken () {
  if (isset($_SESSION['k_id'])) {
  $k_id=$_SESSION['k_id'];
  $result = query("SELECT refresh_token FROM users WHERE k_id='$k_id'");
  if(count($result)==0){

  }
  else{
  return $result[0]['refresh_token'];
  }
}
}

function google_login($user )
    {
        // escape variables for security
        $name = $user['name'];
        $email = $user['email'] ;
        $social_id = $user['id'] ;
        $picture = $user['picture'] ;

        $result = query("SELECT k_id FROM users where email = '$email'");

        $count = count($result);
        if( $count == 1){
            $_SESSION['logged_in'] = true;
            $_SESSION['k_id']=$result[0]['k_id'];
$result = query("SELECT gog_id FROM users where email = '$email'");
    if($result[0]['gog_id']){
  setRefreshToken();          
    }
    else{
$add_user = query("INSERT INTO users (gog_id) VALUES(?)", $social_id);

      }
        }else{
$add_user = query("INSERT INTO users (gog_id, email, name, pic) VALUES(?, ?, ?, ?)", $social_id, $email, $name, $picture);
                    if( $add_user === false)
                    {
                        apologize("Whoops! There was an error at our end. We deeply apologisze.");
                    }
                    //the new user has been added
                    $return_id = query("SELECT k_id FROM users WHERE gog_id = ?", $social_id);

                    //storing the user id in session superglobal                    
                    $_SESSION["k_id"]=$return_id[0]["k_id"];
                        }

        }

        ?>


<?php ob_end_flush(); ?> 

我遇到的问题是setRefreshToken()功能。这是我得到的错误

Notice: Undefined property: stdClass::$refresh_token in C:\xampp\htdocs\trial\log-inlogic\config.php on line 88

Catchable fatal error: Object of class stdClass could not be converted to string in C:\xampp\htdocs\trial\log-inlogic\config.php on line 89

有人可以告诉我可能是什么问题,我在网上进行了研究,并且所有人都在推荐相同的解决方案。

0 个答案:

没有答案