Getting twitter OAuth tokens & secrets

Tags:

My Update multiple twitter accounts via SMS from one phone script was recently updated to use OAuth (since twitter were about to pull the plug on basic auth). The OAuth tokens and secrets are kept in the file - but how do you get them?

Simples; a script linked to the application's callback URL that will allow you to log in as the users you want to use and then print the details.

Here's the script I used. As with the other script, it uses abraham's twitteroauth library. It doesn't save the information anywhere - just shows them on-screen.

<?php
 
define('CONSUMER_KEY', 'MYKEY');
define('CONSUMER_SECRET', 'MYSECRET);
 
session_start();
 
?>
<html>
	<head><title>Get credentials</title></head>
	<body>
		<h1>Grabbing your oauth token & secret, mwahaha.</h1>
<?php
 
require_once('twitteroauth.php');
 
if (isset($_REQUEST['oauth_token']) && $_SESSION['oauth_token'] === $_REQUEST['oauth_token'])
{
	/* Create TwitteroAuth object with app key/secret and token key/secret from default phase */
	$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $_SESSION['oauth_token'], $_SESSION['oauth_token_secret']);
 
	/* Request access tokens from twitter */
	$access_token = $connection->getAccessToken($_REQUEST['oauth_verifier']);
 
	/* Save the access tokens. Normally these would be saved in a database for future use. */
	$_SESSION['access_token'] = $access_token;
}
 
if (	empty($_SESSION['access_token'])
		|| empty($_SESSION['access_token']['oauth_token'])
		|| empty($_SESSION['access_token']['oauth_token_secret']))
{
	/* Build TwitterOAuth object with client credentials. */
	$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET);
 
	/* Get temporary credentials. */
	$request_token = $connection->getRequestToken();
 
	/* Save temporary credentials to session. */
	$_SESSION['oauth_token'] = $token = $request_token['oauth_token'];
	$_SESSION['oauth_token_secret'] = $request_token['oauth_token_secret'];
 
	/* If last connection failed don't display authorization link. */
	switch ($connection->http_code) {
	  case 200:
		/* Build authorize URL and redirect user to Twitter. */
		$url = $connection->getAuthorizeURL($token);
		header('Location: ' . $url);
		break;
	  default:
		/* Show notification if something went wrong. */
		echo 'Could not connect to Twitter. Refresh the page or try again later.';
	}
 
} else {
 
	/* Get user access tokens out of the session. */
	$access_token = $_SESSION['access_token'];
 
	/* Create a TwitterOauth object with consumer/user tokens. */
	$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $access_token['oauth_token'], $access_token['oauth_token_secret']);
 
	$info = $connection->get('account/verify_credentials');
 
	echo '<h2>Got details for "',$info->screen_name,'"</h2>';
	echo '<p>Token: ',$access_token['oauth_token'],'</p>';
	echo '<p>Secret: ',$access_token['oauth_token_secret'],'</p>';
 
}
?>
 
	</body>
</html>