在Twitter中获取永久用户访问令牌

时间:2012-09-25 05:23:43

标签: php

我正在使用这个php库与twitter api进行交互,名为tmhOAuth https://github.com/themattharris/tmhOAuth,我无法获得永久用户访问令牌和令牌密钥。我认为我目前正在使用的那个仅持续当前的浏览器选项卡。在下面的代码中,我将用户令牌和用户机密分配给会话。

function access_token($tmhOAuth) {
  $tmhOAuth->config['user_token']  = $_SESSION['oauth']['oauth_token'];
  $tmhOAuth->config['user_secret'] = $_SESSION['oauth']['oauth_token_secret'];

  //store user token and secret to a session to be accessed on a different page
  $_SESSION['u_token'] =  $tmhOAuth->config['user_token'];
  $_SESSION['u_secret'] = $tmhOAuth->config['user_secret'];  

  $code = $tmhOAuth->request(
    'POST',
    $tmhOAuth->url('oauth/access_token', ''),
    array(
      'oauth_verifier' => $_REQUEST['oauth_verifier']
    )
  );

  if ($code == 200) {
    $_SESSION['access_token'] = $tmhOAuth->extract_params($tmhOAuth->response['response']);
    unset($_SESSION['oauth']);
    header('Location: ' . tmhUtilities::php_self());
  } else {
    outputError($tmhOAuth);
  }
}

然后我只是从另一个页面访问用户令牌和秘密:     

$tmhOAuth = new tmhOAuth(array(
  'consumer_key'    => 'xxx',
  'consumer_secret' => 'xxx',
  $_SESSION['u_token'],
 $_SESSION['u_secret']
));

$tweet = 'tweet';

$code = $tmhOAuth->request('POST', $tmhOAuth->url('1/statuses/update'), array(
  'status' => $tweet
));

echo json_encode($code); //I always get 401 here
?>

问题是我总是得到401响应。

1 个答案:

答案 0 :(得分:2)

您是否尝试添加

'oauth_token' => $_REQUEST['oauth_token']

根据您的要求?

$code = $tmhOAuth->request(
    'POST',
    $tmhOAuth->url('oauth/access_token', ''),
    array(
      'oauth_verifier' => $_REQUEST['oauth_verifier'],
      'oauth_token' => $_REQUEST['oauth_token']
    )
);