Twitter OAuth无法检索访问令牌


Twitter OAuth unable to retrieve the access token

我正在使用PHP构建一个Twitter应用程序,使用TwitterOAuth库进行用户身份验证。

我可以将用户重定向到Twitter进行身份验证,并接收oauth令牌、oauth机密和oauth验证器,但我无法完成获取访问令牌的最后一步身份验证。我在localhost上开发,我已经用设置了回调路径

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');
        }
    ?>

执行时,update.php中的$access_token变为

'{"error":"无效/过期令牌","请求":"/oauth/access_Token"}',HTTP响应状态401,而不是返回认证值。

事实证明,我的特定问题是由会话和回调url引起的。

我通过localhost/path/to/file访问索引页面,但twitter在用户身份验证后重定向到127.0.0.1/path/to/file,这意味着存储在本地主机上的会话数据在127.0.0.1无法访问。

使用127.0.0.1而不是localhost来访问索引页面解决了这个问题。