【问题标题】:Trying to use referesh tokens with google PHP api尝试将刷新令牌与 google PHP api 一起使用
【发布时间】:2015-08-26 18:46:36
【问题描述】:

这是我第一次通过谷歌实现登录,我是一名初学者。我一直坚持使用 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

谁能告诉我可能是什么问题,我在网上研究过,所有人都推荐相同的解决方案。

【问题讨论】:

    标签: php oauth google-api


    【解决方案1】:

    中的错误

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

    是因为服务器没有在响应中返回刷新令牌。您可以通过使用 $client->revokeToken()

    撤销访问并再次授予它来解决此问题
    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
    

    这是因为你试图将一个对象写成一个字符串

    $result =query("UPDATE users SET refreshtoken=$token WHERE k_id='$k_id'");
    

    试试这个

    $result =query("UPDATE users SET refreshtoken='$token->refresh_token' WHERE k_id='$k_id'");
    

    【讨论】:

    • 即使在撤销我的令牌并具有离线访问权限后,我得到的访问令牌没有刷新令牌,这是我得到的令牌 {"access_token":"ya29.6wFbDmfokCH7iQ5NHix5L9N5lisWfF8PN999M-zLcqTPnMLt5caFnu_MmUsW_-bD8ixb6Y75pGL2 ","token_type":"Bearer","expires_in":3600,"id_token":"eyJhbGciOiJSUzI1RE0NDE5OTMzMjUsImV4cCI6MTQ0MTk5NjkyNX0.I7av6lHKWxt2ztFFS2nug","created":1441993325}ya29.6wFbDmfokCH7iQ5NHix5L9N5lisWfF8PN999M-zLcqTPnMLt5caFnu_MmUsW_-bD8ixb6Y75pGL2
    • 尝试在此页面中删除对您应用的访问权限link
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-09
    • 2016-01-26
    • 1970-01-01
    • 2012-12-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多