drbhjey445647 2015-08-23 12:58
浏览 60
已采纳

尝试使用谷歌PHP API的刷新令牌

This is my first time implementing login via google and I am a beginner programmer. I have been stuck on implementing refresh tokens using google api and outh 2.

Here is the code I am using to implement the login

<?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(); ?> 

The problem I have is in the setRefreshToken() function. This the error I get

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

Can someone tell me what might be the problem, I have researched online and all the people are recommending the same solution.

  • 写回答

1条回答 默认 最新

  • dongya6997 2015-08-26 10:46
    关注

    The error in

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

    is because the server didn't return a refresh token in the response. You can solve this by revoking the access and granting it again by using $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
    

    This is because you are trying to write an object as a string

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

    try this instead

    $result =query("UPDATE users SET refreshtoken='$token->refresh_token' WHERE k_id='$k_id'");
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乘性高斯噪声在深度学习网络中的应用
  • ¥15 运筹学排序问题中的在线排序
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥30 python代码,帮调试,帮帮忙吧