I finally got round to writing my first Twitter App using Zend OAuth.
Here are my tips and explanation to getting your Twitter App up and running.
Getting Started
Register at http://dev.twitter.com/ and create your first App. You can change all the settings at any time, so don’t worry about getting them wrong.
Setting Up the Twitter App
Authorise a Domain URL, you can even use localhost for testing purposes.
It is important you set the Callback URL otherwise you can’t use the Browser App option and your OAuth will fail.
Quickly access your App’s details at http://twitter.com/oauth.
When coding with Zend OAuth, read the documentation carefully!
It has everything you need.
My Mistake
I did not understand how to grab the Access Token. Reason? It’s a two part process. Requesting, then Receiving.
The Code
Here is a working example of a Request Token with Zend OAuth and your Twitter App’s Consumer Key and Consumer Secret.
(Note the keys used are the ones from Zend’s Article)
$config = array(
'callbackUrl' => 'http://example.com/callback.php',
'siteUrl' => 'http://twitter.com/oauth',
'consumerKey' => 'gg3DsFTW9OU9eWPnbuPzQ',
'consumerSecret' => 'tFB0fyWLSMf74lkEu9FTyoHXcazOWpbrAjTCCK48A'
);
$consumer = new Zend_Oauth_Consumer($config);
// fetch a request token
$token = $consumer->getRequestToken();
// persist the token to storage
$_SESSION['TWITTER_REQUEST_TOKEN'] = serialize($token);
// redirect the user
$consumer->redirect();
Steps you must do:
- Use the Callback URL to receive the Access Token
- Store the Request Token in a $_SESSION
- Follow the getAccessToken() example and store this in a $_SESSION or Database (recommended)
Why store the Access Token in a Database?
The best thing about the Access Token is that once you’ve successfully requested one, it never expires!
So save the hassle of requesting a new token and use it throughout your website. Great thing is, it can’t be compromised!
Without the the Consumer Key and Consumer Secret, you can’t hijack the users account for malicious purposes.
Please leave a comment if you want me to write another article about how to implement the example into your scripts or maybe I’ll update this one.