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):

  1. private static function get_twitter_access_token($consumer_key, $consumer_secret, $use_curl) {
  2.  // Url encode the consumer_key and consumer_secret in accordance with RFC 1738
  3.  $encoded_consumer_key = urlencode($consumer_key);
  4.  $encoded_consumer_secret = urlencode($consumer_secret);
  5.  
  6.  // Concatenate encoded consumer, a colon character and the encoded consumer secret
  7.  $bearer_token = $encoded_consumer_key . ':' . $encoded_consumer_secret;
  8.  
  9.  // Base64-encode bearer token
  10.  $base64_encoded_bearer_token = base64_encode($bearer_token);
  11.  
  12.  // Twitter URL that authenticates bearer tokens
  13.  $url = "https://api.twitter.com/oauth2/token/";
  14.  
  15.  if ($use_curl) {
  16.   // Set up the headers that will be used to make a call to the URL including the app name and the encoded bearer token
  17.   $headers = array(
  18.    "POST /oauth2/token HTTP/1.1",
  19.    "Host: api.twitter.com",
  20.    "User-Agent: ThinkTwit Twitter App v" . ThinkTwit::get_version(),
  21.    "Authorization: Basic " . $base64_encoded_bearer_token,
  22.    "Content-Type: application/x-www-form-urlencoded;charset=UTF-8",
  23.    "Content-Length: 29"
  24.   );
  25.  
  26.   // Setup curl
  27.   $ch = curl_init();
  28.  
  29.   // Set the URL
  30.   curl_setopt($ch, CURLOPT_URL, $url);
  31.  
  32.   // Set the headers we created
  33.   curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
  34.  
  35.   // Set option to not receive the headers
  36.   $header = curl_setopt($ch, CURLOPT_HEADER, 0);
  37.  
  38.   // Set to use a POST call
  39.   curl_setopt($ch, CURLOPT_POST, 1);
  40.  
  41.   // Set the parameter to be sent (see
  42.   curl_setopt($ch, CURLOPT_POSTFIELDS, "grant_type=client_credentials");
  43.  
  44.   // Set to return a string
  45.   curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  46.  
  47.   // Execute the call
  48.   $response = curl_exec($ch);
  49.  
  50.   // Close curl
  51.   curl_close($ch);
  52.  } else {    
  53.   // Create an options context that contains the headers used to make a call to the URL including the app name and the access token
  54.   $context = stream_context_create(array("http" => array("method" => "POST",
  55.                   "header" => "POST /oauth2/token HTTP/1.1\r\n" .
  56.                      "Host: api.twitter.com\r\n" .
  57.                      "User-Agent: ThinkTwit Twitter App v" . ThinkTwit::get_version() . "\r\n" .
  58.                      "Authorization: Basic " . $base64_encoded_bearer_token . "\r\n" .
  59.                      "Content-Type: application/x-www-form-urlencoded;charset=UTF-8\r\n" .
  60.                      "Content-Length: 29\r\n",
  61.                 "content" => "grant_type=client_credentials")));
  62.  
  63.   // Execute the API call using the created headers
  64.   $response = @file_get_contents($url, false, $context);
  65.  }
  66.  
  67.  // Decode the returned JSON response
  68.  $json = json_decode($response, true);
  69.        
  70.  // Verify that the token is a bearer (by checking for errors first and then checking that the type is bearer)
  71.  if (!isset($json["errors"]) && $json["token_type"] == 'bearer') {
  72.   // If so then return the access token
  73.   return $json["access_token"];
  74.  } else {
  75.   // Otherwise if there were errors or the token was of the wrong type return null
  76.   return null;
  77.  }
  78. }

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):

  1. // Get the Twitter access token
  2. $access_token = ThinkTwit::get_twitter_access_token($consumer_key, $consumer_secret, $use_curl);
  3.  
  4. // If user wishes to use CURL
  5. if ($use_curl) {  
  6.  // Set up the headers that will be used to make a call to the URL including the app name and the access token
  7.  $headers = array(
  8.   "GET /oauth2/token HTTP/1.1",
  9.   "Host: api.twitter.com",
  10.   "User-Agent: ThinkTwit Twitter App v" . ThinkTwit::get_version(),
  11.   "Authorization: Bearer " . $access_token,
  12.   "Content-Type: application/x-www-form-urlencoded;charset=UTF-8",
  13.  );
  14.  
  15.  // Initiate a CURL object
  16.  $ch = curl_init();
  17.  
  18.  // Set the URL
  19.  curl_setopt($ch, CURLOPT_URL, $url);
  20.  
  21.  // Set the headers we created
  22.  curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
  23.  
  24.  // Set option to not receive the headers
  25.  $header = curl_setopt($ch, CURLOPT_HEADER, 0);
  26.  
  27.  // Set to return a string
  28.  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  29.  
  30.  // Set the timeout
  31.  curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
  32.  
  33.  // Execute the API call
  34.  $feed = curl_exec($ch);
  35.  
  36.  // Close the CURL object
  37.  curl_close($ch);
  38. } else {    
  39.  // Create an options context that contains the headers used to make a call to the URL including the app name and the access token
  40.  $context = stream_context_create(array('http' => array('header' => 'Authorization: Bearer ' . $access_token)));
  41.  
  42.  // Execute the API call using the created headers
  43.  $feed = @file_get_contents($url, false, $context);
  44. }

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, project manager, RightNow and telephony expert, information security specialist, all-round geek. He is currently Professional Services 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, the 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.

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

  1. 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!

  2. 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!

Leave a Reply