2015-03-24 151 views
1

我使用TwitterOAuth庫構建了一個Twitter應用程序,用於用戶身份驗證。Twitter OAuth無法檢索訪問令牌

我能夠將用戶重定向到Twitter進行身份驗證,並接收oauth令牌,oauth secret和oauth驗證程序,但是我無法在獲取訪問令牌的情況下完成身份驗證的最後一步。 我開發本地主機上,我已經建立回調路徑與

http://127.0.0.1:80/TwitterApp/update.php

我的應用程序讀取和寫入權限。

這裏是我的代碼:

的index.php

<?php 
    session_start(); 
    include "twitteroauth/autoload.php"; 
    include "oauthConsts.php"; 

    use Abraham\TwitterOAuth\TwitterOAuth; 

    // request authentication tokens 
    $oauth = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET); 
    $request_token = $oauth->getRequestToken(
        'http://127.0.0.1/TwitterApp/update.php'); 

    $_SESSION['oauth_token'] = $request_token['oauth_token']; 
    $_SESSION['oauth_secret'] = $request_token['oauth_token_secret']; 

    if($oauth->getLastHttpCode()==200){ 
     // Let's generate the URL and redirect 
     $url = $oauth->getAuthorizeURL($request_token['oauth_token']); 
     header('Location: '. $url); 
    } else { 
     echo "something went wrong"; 
    } 

?> 

update.php

<?php 
     session_start(); 
     include "twitteroauth/autoload.php"; 
     include "oauthConsts.php"; 

     use Abraham\TwitterOAuth\TwitterOAuth; 

     if(!empty($_GET['oauth_verifier']) && !empty($_SESSION['oauth_token']) 
      && !empty($_SESSION['oauth_secret'])) { 
      $oauth = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, 
         $_SESSION['oauth_token'], $_SESSION['oauth_secret']); 
      $access_token = $oauth->oauth("oauth/access_token", 
          array("oauth_verifier" => $_GET['oauth_verifier'])); 

      $_SESSION['access_token'] = $access_token; 

     } 
     else { 
      header('Location: index.php'); 
     } 
    ?> 

在執行時,$中的access_token成爲update.php

'{「error」:「無效/過期 令牌」,「請求」:「/ oauth/access_token」}'與HTTP響應狀態 401而不是返回認證值。

回答

0

事實證明我的問題是由會話和回調url造成的。

我是通過本地主機/路徑訪問索引頁/到/文件,但Twitter被重定向到127.0.0.1/path/to/file用戶認證後,意味着存儲在本地主機會話數據127.0.0.1無法訪問。

使用127.0.0.1而不是localhost訪問索引頁解決了這個問題。