Sunday, January 20, 2013

How to Connect in Twitter API Using PHP

Connecting to twitter is very tiring because you have to make all the strings required by the twitter API correct. So lets start

First you need to do it to create an application in https://dev.twitter.com and fill the requirements there. Once finished you will have your $consumerKey and $consumerSecret.
I have declared a session start here so that we can just get our tokens directly once we obtain it.

 <?php   
 session_start();  
   $host = "https://api.twitter.com/oauth/request_token";  
   $consumerKey = "h0YUvJVE6AdYBsBLxhL7Nw";  
   $consumerSecret = "AYS7EcrqzcjambZIHsZtXZxOGn0VfJRgYJrqI5aqQ0&";  
   $nonce = time();  
   $timestamp = time();  
   $oauth_signature_method = "HMAC-SHA1";  
   $callback = "";  

All of these variable are self-explanatory since it is all the variables needed by the Twitter API. Note that you should set your $callback in your twitter application.
First, we should obtain the $signature_base_string. In the first $signature_base_string that we will create it using the variables above.

$signature_base_string = "POST&". rawurlencode($host).'&'  
               .rawurlencode("oauth_callback=").rawurlencode($callback)  
               .rawurlencode("&oauth_consumer_key=". ($consumerKey))  
               .rawurlencode("&oauth_nonce=". rawurlencode($nonce))  
               .rawurlencode("&oauth_signature_method=".$oauth_signature_method)  
               .rawurlencode("&oauth_timestamp=".$timestamp)  
               .rawurlencode("&oauth_version=1.1");  
First thing you should note is that strings that will be put in the $signature_base_string should be URL Encoded. This is a dummy $signature_base_string because we still don't have the $oauth_signature.
The $signature_base_string would look something like this:

 POST&https%253A%252F%252Fapi.twitter.com%252Foauth%252Frequest_token%26oauth_consumer_key%3Dh0YUvJVE6AdYBsBLxhL7Nw%2Coauth_nonce%3D1358732765%2Coauth_signature_method%3DHMAC-SHA1%2Coauth_timestamp%3D1358732765%2Coauth_version%3D1.1%2Coatuh_signature%3DuV%2FogNLV%2FwS%2FVYNpdxbxtF5TJro%3D  

Since we have now created our $signature_base_string, we can now make our $oauth_signature. (If you want to clarify things on what these variables represents, you should read a bit in https://dev.twitter.com/docs/auth/creating-signature).

 $oauth_signature = base64_encode(hash_hmac('sha1', $signature_base_string, $consumerSecret,true));  

The signature is calculated by passing the signature base string and signing key to the HMAC-SHA1 hashing algorithm. The details of the algorithm are explained in depth here, but thankfully there are implementations of HMAC-SHA1 available for every popular language. For example, PHP has the hash_hmac function (https://dev.twitter.com/docs/auth/creating-signature).

 We will now write our HTTP header that will be used in our cUrl method.

   $r = "Authorization: OAuth ".'oauth_callback="'.$callback.'"'  
                 .', oauth_consumer_key="'. rawurlencode($consumerKey)  
                 .'", oauth_nonce="'. rawurlencode($nonce)  
                 .'", oauth_signature_method="'.$oauth_signature_method  
                 .'", oauth_timestamp="'.$timestamp  
                 .'", oauth_version="1.1'  
                 .'", oauth_signature="'.rawurlencode($oauth_signature).'"';  
  $r = array($r,'Expect:');  

We will now use cUrl with the settings that we wanted and call the cUrl method.

  $options = array(CURLOPT_HTTPHEADER=>$r,  
            CURLOPT_HEADER=>false,  
            CURLOPT_URL=>$host,  
            CURLOPT_POST=>true,  
            CURLOPT_POSTFIELDS => "",  
            CURLOPT_RETURNTRANSFER=>true,  
            CURLOPT_SSL_VERIFYPEER=>false);  
   $ch = curl_init();  
   curl_setopt_array($ch, $options);  
   $response= curl_exec($ch);  

After executing this, our $response will contain the oauth_token and the oauth_token_secret. We can save it in our session that it can be used in later transactions.

  $response_array = explode('&', $response);  
   $_SESSION['oauth_token'] = $response_array[0];  
   $_SESSION['oauth_token_secret'] = $response_array[1];  

Once we obtain our tokens needed, we can now redirect to our page to the twitter to authenticate us.
  header("Location: https://api.twitter.com/oauth/authenticate?".$response_array[0]);  

Here is the full source code:

 <?php    
   session_start();  
   $host = "https://api.twitter.com/oauth/request_token";  
   $consumerKey = "h0YUvJVE6AdYBsBLxhL7Nw";  
   $consumerSecret = "AYS7EcrqzcjambZIHsZtXZxOGn0VfJRgYJrqI5aqQ0&";  
   $nonce = time();  
   $timestamp = time();  
   $oauth_signature_method = "HMAC-SHA1";  
   $callback= "";+  
   $signature_base_string = "POST&". rawurlencode($host).'&'  
               .rawurlencode("oauth_callback=").rawurlencode($callback)  
               .rawurlencode("&oauth_consumer_key=". ($consumerKey))  
               .rawurlencode("&oauth_nonce=". rawurlencode($nonce))  
               .rawurlencode("&oauth_signature_method=".$oauth_signature_method)  
               .rawurlencode("&oauth_timestamp=".$timestamp)  
               .rawurlencode("&oauth_version=1.1");  
   $oauth_signature = base64_encode(hash_hmac('sha1', $signature_base_string, $consumerSecret,true));  
   $r = "Authorization: OAuth ".'oauth_callback="'.$callback.'"'  
                 .', oauth_consumer_key="'. rawurlencode($consumerKey)  
                 .'", oauth_nonce="'. rawurlencode($nonce)  
                 .'", oauth_signature_method="'.$oauth_signature_method  
                 .'", oauth_timestamp="'.$timestamp  
                 .'", oauth_version="1.1'  
                 .'", oauth_signature="'.rawurlencode($oauth_signature).'"';  
   $r = array($r,'Expect:');  
   $options = array(CURLOPT_HTTPHEADER=>$r,  
            CURLOPT_HEADER=>false,  
            CURLOPT_URL=>$host,  
            CURLOPT_POST=>true,  
            CURLOPT_POSTFIELDS => "",  
            CURLOPT_RETURNTRANSFER=>true,  
            CURLOPT_SSL_VERIFYPEER=>false);  
   $ch = curl_init();  
   curl_setopt_array($ch, $options);  
   $response= curl_exec($ch);  
   $response_array = explode('&', $response);  
   $_SESSION['oauth_token'] = $response_array[0];  
   $_SESSION['oauth_token_secret'] = $response_array[1];  
  header("Location: https://api.twitter.com/oauth/authenticate?".$response_array[0]);  
 ?>  

In my next post, I will show how to create a post status request in twitter.



No comments:

Post a Comment