PHP/Twitter oAuth - 自动推文

标签 php twitter twitter-oauth

我使用以下代码从 config.php 读取 consumer_keyconsumer_secret,将其传递给 twitter 并从中检索一些信息。

下面的脚本试图做的是“缓存”request_token 和 request_secret。所以理论上我应该能够重用这些细节(所有 4 个都可以在需要时自动发推文)。

<?php

require_once('twitteroauth/twitteroauth.php');
require_once('config.php');

    $consumer_key = CONSUMER_KEY;
    $consumer_secret = CONSUMER_SECRET; 

if (isset($_GET["register"]))
{
    // If the "register" parameter is set we create a new TwitterOAuth object
    // and request a token

    /* Build TwitterOAuth object with client credentials. */

    $oauth = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET);
    $request = $oauth->getRequestToken();

    $request_token = $request["oauth_token"];
    $request_token_secret = $request["oauth_token_secret"];

    // At this I store the two request tokens somewhere.

    file_put_contents("request_token", $request_token);
    file_put_contents("request_token_secret", $request_token_secret);

    // Generate a request link and output it
    $request_link = $oauth->getAuthorizeURL($request);
    echo "Request here: <a href=\"" . $request_link . "\">" . $request_link . "</a>";
    die();
}
elseif (isset($_GET["validate"]))
{
    // This is the validation part. I read the stored request
    // tokens.

    $request_token = file_get_contents("request_token");
    $request_token_secret = file_get_contents("request_token_secret");

    // Initiate a new TwitterOAuth object. This time we provide them with more details:
    // The request token and the request token secret

    $oauth = new TwitterOAuth($consumer_key, $consumer_secret,
        $request_token, $request_token_secret);

    // Ask Twitter for an access token (and an access token secret)
    $request = $oauth->getAccessToken();

    // There we go
    $access_token = $request['oauth_token'];
    $access_token_secret = $request['oauth_token_secret'];

    // Now store the two tokens into another file (or database or whatever):
    file_put_contents("access_token", $access_token);
    file_put_contents("access_token_secret", $access_token_secret);

    // Great! Now we've got the access tokens stored.
    // Let's verify credentials and output the username.
    // Note that this time we're passing TwitterOAuth the access tokens.


    $oauth = new TwitterOAuth($consumer_key, $consumer_secret,
        $access_token, $access_token_secret);

    // Send an API request to verify credentials
    $credentials = $oauth->oAuthRequest('https://twitter.com/account/verify_credentials.xml', 'GET', array());

    // Parse the result (assuming you've got simplexml installed)
    $credentials = simplexml_load_string($credentials);

    var_dump($credentials);

    // And finaly output some text
    echo "Access token saved! Authorized as @" . $credentials->screen_name;
    die();
}
?>

当我运行 /?verify&oauth_token=0000000000000000 - 它有效但是试图重新使用生成的 token 等......我得到一个 401

这是最后一段代码,我尝试结合我的 consumer_key 和 consumer_secret 重用来自 Twitter 的详细信息并获取 401:

require_once('twitteroauth/twitteroauth.php');
require_once('config.php');

// Read the access tokens
$access_token = file_get_contents("access_token");
$access_token_secret = file_get_contents("access_token_secret");

// Initiate a TwitterOAuth using those access tokens
$oauth = new TwitterOAuth($consumer_key, $consumer_key_secret,
    $access_token, $access_token_secret);

// Post an update to Twitter via your application:
$oauth->OAuthRequest('https://twitter.com/statuses/update.xml',
    array('status' => "Hey! I'm posting via #OAuth!"), 'POST');

不确定出了什么问题,你能缓存详细信息还是我需要尝试其他方法?

最佳答案

您不能将 OAuth token 存储在缓存中,并且不能使用它来处理超过 1 个请求,因为 OAuth 可以帮助确保系统安全,您的“oauth_token”将包含一些独特的数据,该 token 将只能给 Twitter 打一个电话,一旦电话打通,“oauth_token”就不再有效,OAuth 类应该请求一个新的“oauth_token”,从而确保每次调用都是安全的。

这就是为什么您第二次收到“401 unauthorized”错误,因为 token 不再有效。

twitter 仍在使用 OAuth v1(v2 仍在起草过程中,尽管 facebook 和 google 已经在某些部分实现了它) 下图描述了 OAuth 身份验证的流程。 希望对您有所帮助。

OAuth authentication flow

不久前我用它连接到 Twitter 并发送推文,请注意它确实使用了一些 Zend 类,因为该项目在 zend 服务器上运行。

require_once 'Zend/Service/Twitter.php';
class Twitter {

    protected $_username = '<your_twitter_username>';
    protected $_token = '<your_twitter_access_token>';
    protected $_secret = '<your_twitter_access_token_secret>';
    protected $_twitter = NULL;

    //class constructor
    public function __construct() {
        $this->getTwitter();
    }

    //singleton twitter object   
    protected function getTwitter() {
        if (null === $this->_twitter) {
            $accessToken = new Zend_Oauth_Token_Access;
            $accessToken->setToken($this->_token)
                    ->setTokenSecret($this->_secret);

            $this->_twitter = new Zend_Service_Twitter(array(
                        'username' => $this->_username,
                        'accessToken' => $accessToken,
                    ));

            $response = $this->_twitter->account->verifyCredentials();
            if ($response->isError()) {
                throw new Zend_Exception('Provided credentials for Twitter log writer are wrong');
            }
        }
        return $this->_twitter;
    }

    //send a status message to twitter
    public function update( $tweet ) {
        $this->getTwitter()->status->update($tweet);
    }

}

关于PHP/Twitter oAuth - 自动推文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6686176/

相关文章:

PHP Utf8 解码问题

python - 使用 Tweepy 将推文插入 MySQL DB

ios - Twitter 警告日志 "TwitterKit must be used only from the main thread"Fabric SDK?

iphone - OAuth登录后获取用户信息

php - JavaScript 到 PHP 数组

php - 当我在我的 Mac (OS X 10.6 Snow Leopard) 上使用本地服务器时,我在哪里保存我的 HTML 和 PHP 文件

php - iframe 传输未传输任何数据

javascript - twitter 如何在不重新加载页面的情况下更改 url?

api - Twitter API request_token

iOS 推特集成