开发者

Post/update data via twitter API

What I have: Twitter app created at twitter and PHP app at localhost

What I want: post tweets/update statuses via twitter API from only(!) the app account. No twitter@anywhere, no user login, nothing fancy.

What I tried:

https://github.com/abraham/twitteroauth with access tokens from the dev.twitter.com website, returned

"POST data is not available with this token"

or something like that.

code snippet I found on some website:

// Define credentials for the Twitter account
define('TWITTER_CREDENTIALS', 'username:password');


// Set up CURL with the Twitter URL and some options
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://twitter.com/statuses/update.xml?status=test_status');
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 2);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);


// Twitter uses HTTP authenticati开发者_运维技巧on, so tell CURL to send our Twitter account details
curl_setopt($ch, CURLOPT_USERPWD, TWITTER_CREDENTIALS);


// Execute the curl process and then close
$data = curl_exec($ch);
curl_close($ch);


// If nothing went wrong, we should now have some XML data 
echo '<pre>'.htmlentities(print_r($data, true)).'</pre>';   

returned

"Basic authentication is not supported"


That big code snippet uses basic authentication, which is no longer supported by Twitter. Disregard it.

OAuth is now required by Twitter instead, which is what abraham's twitteroauth library uses. You will have to log in/authenticate using this, at least once.

You will also have to first register your app with Twitter, to receive your own Consumer Key and Consumer Secret. Then you'll be able to start using Twitter's API via twitteroauth.


Okay I've found what's the problem.

By default, Twitter sets all apps to read-only, so even when you login via PHP, you can't send POST/UPDATE. What you need to do is go to your application settings (the one where you set app name, description and avatar) and before avatar there's a "default access type", switch it to

Read, Write, & Direct Messages

and voila.

to test the app use this snippet

$twitter = new \TwitterOAuth('consumer_key', 'consumer_secret', 
                              '(oauth_token', 'oauth_token_secret');
$twitter->get('account/verify_credentials');
$twitter->post('statuses/update', array('status' => 'test status'));

Oh and you don't need to do the login stuff with your app, you get the required tokens under "My access Token" menu.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜