PHP/Twitter oAuth - Automated Tweets

前端 未结 2 2036
半阙折子戏
半阙折子戏 2021-02-10 06:32

Im using the following code to read to consumer_key and consumer_secret from config.php, pass it to twitter and retrieve some bits of information back

2条回答
  •  感动是毒
    2021-02-10 07:21

    You can't store the OAuth tokens in cache and to more than 1 request with it, as OAuth is there to help make the system secure, your "oauth_token" will contain some unique data, this token will only be able to make one call back to twitter, as soon as the call was made, that "oauth_token" is no longer valid, and the OAuth class should request a new "oauth_token", thus making sure that every call that was made is secure.

    That is why you are getting an "401 unauthorized" error on the second time as the token is no longer valid.

    twitter is still using OAuth v1 (v2 is still in the draft process even though facebook and google already implemented it in some parts) The image below describes the flow of the OAuth authentication. Hope it helps.

    OAuth authentication flow

    A while ago I used this to connect to twitter and send tweets, just note that it did make use of some Zend classes as the project was running on a zend server.

    require_once 'Zend/Service/Twitter.php';
    class Twitter {
    
        protected $_username = '';
        protected $_token = '';
        protected $_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);
        }
    
    }
    

提交回复
热议问题