twitteryauth
A PHP class using the Pear OAuth library to connect to the Twitter api.
Requirements
- PHP 5.3+
-
PECL OAuth (tested with 1.1)
sudo pecl install oauth
-
PECL HTTP (tested with 1.7.1)
sudo pecl install pecl_http
- PHPUnit if you want to run the tests
Example usage
In these examples, the consumer key and secret are stored as constants named CONSUMER_KEY
and CONSUMER_SECRET
respectively. First up, create a Twitteryauth object:
$options = array(
'consumer_key' => CONSUMER_KEY,
'consumer_secret' => CONSUMER_SECRET
);
$twitter = new Twitteryauth($options);
Request an authorisation URL, passing in the URL that twitter will use as a callback, and store the request secret in a session:
$url = $twitter->get_authorize_url('http://myapp.com/callback');
$_SESSION['request_secret'] = $twitter->get_config('request_secret');
header('Location: '.$url);
exit;
In your callback function, you want to grab the oauth token and pass that through to the authenticate method. If all is good, this will give you the access key and secret. You'll then want to save these in the session too, and use them in future to access the api:
$twitter->authenticate($_GET['oauth_token']);
$_SESSION['access_key'] = $twitter->get_config('access_key');
$_SESSION['access_secret'] = $twitter->get_config('access_secret');
unset($_SESSION['request_secret']); // no longer needed
var_dump($twitter->get('account/verify_credentials));
To make things easier for yourself after you have the access tokens, when you're initialising your Twitteryauth object, I'd pass in an array of options. That way, you can have the object being created in one place:
$options = array(
'consumer_key' => CONSUMER_KEY,
'consumer_secret' => CONSUMER_SECRET
);
$tokens = array('request_secret', 'access_key', 'access_secret');
foreach ($tokens as $token)
{
if (isset($_SESSION[$token]))
{
$options[$token] = $_SESSION[$token];
}
}
$twitter = new Twitteryauth($options);
You can always check to see if you're authenticated (the Twitteryauth object having the access tokens):
$twitter->is_authenticated();
To make calls to the twitter api:
$twitter->get('account/verify_credentials');
$twitter->post('statuses/update', array(
'status' => 'Trying out Twitteryauth!'
));