Categories
Programming Wordpress

How to implement application-only authentication of Twitter API v1.1 in PHP/WordPress

As with everything, once you know how this actually quite easy – but when you first look at documentation on Twitter’s website about how to do this it can be a little daunting.

Twitter have recently altered their API to require authentication for all API requests. This authentication can either be Application-user or Application-only. There are many examples on the web about the former but little on the latter, so in this case we are looking at Application-only.

First of all you need to register your application so that you can obtain a consumer key and a consumer secret – these are passwords that, when combined, allow you to create an authentication string which you can register with Twitter and then send along with all of your requests to authenticate them. To do this go to https://dev.twitter.com/apps/new and complete the form as below:

  • Name: [Your application]
  • Description: [Description of your application]
  • Website: [URL of your website]
  • Callback URL: [URL of your website]

This will register your application and provide you with your consumer key and secret. Next you will need to get an access token from Twitter using these passwords, to do this you can use the following code which combines the key and secret (with a colon between), encodes them and sends them to the OAuth2 Token URL (using CURL or file_get_contents depending on what you pass as the $use_curl parameter):

private static function get_twitter_access_token($consumer_key, $consumer_secret, $use_curl) {
	// Url encode the consumer_key and consumer_secret in accordance with RFC 1738
	$encoded_consumer_key = urlencode($consumer_key);
	$encoded_consumer_secret = urlencode($consumer_secret);
	
	// Concatenate encoded consumer, a colon character and the encoded consumer secret
	$bearer_token = $encoded_consumer_key . ':' . $encoded_consumer_secret;
	
	// Base64-encode bearer token
	$base64_encoded_bearer_token = base64_encode($bearer_token);
	
	// Twitter URL that authenticates bearer tokens
	$url = "https://api.twitter.com/oauth2/token/";
	
	if ($use_curl) {
		// Set up the headers that will be used to make a call to the URL including the app name and the encoded bearer token
		$headers = array( 
			"POST /oauth2/token HTTP/1.1", 
			"Host: api.twitter.com", 
			"User-Agent: ThinkTwit Twitter App v" . ThinkTwit::get_version(),
			"Authorization: Basic " . $base64_encoded_bearer_token,
			"Content-Type: application/x-www-form-urlencoded;charset=UTF-8", 
			"Content-Length: 29"
		);

		// Setup curl
		$ch = curl_init();
		
		// Set the URL
		curl_setopt($ch, CURLOPT_URL, $url); 
		
		// Set the headers we created
		curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
		
		// Set option to not receive the headers
		$header = curl_setopt($ch, CURLOPT_HEADER, 0);
		
		// Set to use a POST call
		curl_setopt($ch, CURLOPT_POST, 1);
		
		// Set the parameter to be sent (see 
		curl_setopt($ch, CURLOPT_POSTFIELDS, "grant_type=client_credentials");
		
		// Set to return a string
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		
		// Execute the call
		$response = curl_exec($ch);
		
		// Close curl
		curl_close($ch);
	} else {				
		// Create an options context that contains the headers used to make a call to the URL including the app name and the access token
		$context = stream_context_create(array("http" => array("method" => "POST",
															   "header" => "POST /oauth2/token HTTP/1.1\r\n" .
																		   "Host: api.twitter.com\r\n" .
																		   "User-Agent: ThinkTwit Twitter App v" . ThinkTwit::get_version() . "\r\n" .
																		   "Authorization: Basic " . $base64_encoded_bearer_token . "\r\n" .
																		   "Content-Type: application/x-www-form-urlencoded;charset=UTF-8\r\n" .
																		   "Content-Length: 29\r\n",
																"content" => "grant_type=client_credentials")));
	
		// Execute the API call using the created headers
		$response = @file_get_contents($url, false, $context);
	}

	// Decode the returned JSON response
	$json = json_decode($response, true);
							
	// Verify that the token is a bearer (by checking for errors first and then checking that the type is bearer)
	if (!isset($json["errors"]) && $json["token_type"] == 'bearer') {
		// If so then return the access token
		return $json["access_token"];
	} else {
		// Otherwise if there were errors or the token was of the wrong type return null
		return null;
	}
}

Now that you have the access token you can make use of it quite simply by calling the method and then passing the returned value in the header of your requests. If you have previously followed my instructions on how to call the Twitter API using JSON then you will recognise this code which makes a call to the given $url (you should have already constructed this to call the relevant part of the Twitter API, in my example we used GET search/tweets):

// Get the Twitter access token
$access_token = ThinkTwit::get_twitter_access_token($consumer_key, $consumer_secret, $use_curl);

// If user wishes to use CURL
if ($use_curl) {			
	// Set up the headers that will be used to make a call to the URL including the app name and the access token
	$headers = array( 
		"GET /oauth2/token HTTP/1.1", 
		"Host: api.twitter.com", 
		"User-Agent: ThinkTwit Twitter App v" . ThinkTwit::get_version(),
		"Authorization: Bearer " . $access_token,
		"Content-Type: application/x-www-form-urlencoded;charset=UTF-8", 
	); 

	// Initiate a CURL object
	$ch = curl_init();

	// Set the URL
	curl_setopt($ch, CURLOPT_URL, $url);
	
	// Set the headers we created
	curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
	
	// Set option to not receive the headers
	$header = curl_setopt($ch, CURLOPT_HEADER, 0);

	// Set to return a string
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

	// Set the timeout
	curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);

	// Execute the API call
	$feed = curl_exec($ch);

	// Close the CURL object
	curl_close($ch);
} else {				
	// Create an options context that contains the headers used to make a call to the URL including the app name and the access token
	$context = stream_context_create(array('http' => array('header' => 'Authorization: Bearer ' . $access_token)));

	// Execute the API call using the created headers
	$feed = @file_get_contents($url, false, $context);
}

And there you have it – the $feed will contain the returned JSON feed containing your requested tweets!

Finally, one thing to note is that if you have followed my series on how to access the Twitter API then you will need to note that the results returned are different – now you need to locate “statuses” instead of “results” and also bear in mind that the user details are now stored under “user”, so you have one further level to traverse.

I hope someone else finds this useful!

About Stephen Pickett


Stephen Pickett is a programmer, IT strategist and architect, project manager and business analyst, Oracle Service Cloud and telephony expert, information security specialist, all-round geek. He is currently Technical Director at Connect Assist, a social business that helps charities and public services improve quality, efficiency and customer engagement through the provision of helpline services and CRM systems.

Stephen is based in south Wales and attended Cardiff University to study Computer Science, in which he achieved a 2:1 grading. He has previously worked for Think Consulting Solutions, a leading voice on not-for-profit fundraising, Fujitsu Services and Sony Manufacturing UK as a software developer.

Stephen is the developer of ThinkTwit, a WordPress plugin that allows you to display multiple Twitter feeds within a blog.

By Stephen Pickett

Stephen Pickett is a programmer, IT strategist and architect, project manager and business analyst, Oracle Service Cloud and telephony expert, information security specialist, all-round geek. He is currently Technical Director at Connect Assist, a social business that helps charities and public services improve quality, efficiency and customer engagement through the provision of helpline services and CRM systems.

Stephen is based in south Wales and attended Cardiff University to study Computer Science, in which he achieved a 2:1 grading. He has previously worked for Think Consulting Solutions, a leading voice on not-for-profit fundraising, Fujitsu Services and Sony Manufacturing UK as a software developer.

Stephen is the developer of ThinkTwit, a Wordpress plugin that allows you to display multiple Twitter feeds within a blog.

7 replies on “How to implement application-only authentication of Twitter API v1.1 in PHP/WordPress”

Those ~120 lines of code explain things far more clearly than the 1000’s of words Twitter use on the docs site.

Thanks for taking the time to share!

Hi Brent,

Not a problem, I’m glad you and others have found it helpful! Thanks for taking the time to comment, it is very rewarding to get nice comments such as yours and is very appreciated!

Thanks for this, I was looking for some straight forward examples of getting an app only token with Twitter and adapting your examples to my app worked like a charm. One of the few times I’ve had my first API requests work on the first run.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: