Writing PHP Application Using oAuth Twitter API

Twitter oAuth Diagram

Twitter OAuthIt is possible that at the time you read this article, the team microblogging service Twitter has completely blocked the authorization in its API using the Basic Authentication.

On August 31, 2010 at 8:00 am California time (19:00 MSK), all requests from the desktop and web applications made using the username and password will be rejected.

OAuth LogoAbout this service warned its developers still several months in advance and most of the applications have already upgraded, and to authorize the use of a more secure method Open Authorization (OAuth).

It allows you to authenticate a user directly without passing the user name and password, and using so-called “tokens” (tokens). This allows you to remove the developer responsible for the storage of user passwords, as users enter the password only on the site they trust (Twitter).

One of the schemes describing the principle of OAuth, can be found on the site for developers, it looks as follows:

Twitter oAuth Diagram

At first glance, the scheme may seem somewhat convoluted, so try to explain the procedure to use this method more clearly and step through an example.

An example is a script language PHP, but, in general, the algorithm for all languages (list of supported languages and libraries can be found here) Should not differ greatly.

Feature of our web-based applications in PHP would be to tape reading user and find the most frequently used questions among him and his friends (who are distinguished in communications with a #).

First, where to start – is to register their application on site Twitter Developer – http://dev.twitter.com/apps/new (for this you must log in using your Twitter-account). The form will need to fill in information about your application (name, description, etc.), And on a three-stop the settlements account:

Application Type (Type of application) – Client includes desktop applications, Browser – a web script. The difference is that after logging applications such as Browser is an automatic redirect to the URL of the script, in the case of the Client – the user is given a unique PIN-code, which must be entered in box desktop application. As you understand, for our example, choose Browser.

Callback URL – If our application, Browser – what is the URL of the page script, which will move the user after logging on the site twitter.com. This field can be filled in later, but you can just point to the site and the page on which the application will work, (even if the page is missing, the form does not give an error).

Default Access type (Type of access is the default) – set Read & Write – if your application requires not only reading the user data, but also, for example, sending messages on its behalf, changing avatar, etc. Accordingly, the Read-only – only read access. In the example I will also send a message on behalf of the user, so put up Read & Write.

Create your own Twitter Application

If desired, choose a picture for your application, enter the captcha, click on Register Application and agree to the terms of service. If you never made a mistake, then the application will be registered and you’ll be taken to its settings.

It until you can not close or burn himself these two cells, which we need – it’s Consumer key and Consumer secret. This unique keys of your application should not be known to anyone:

Twitter Application Secret Key

Now we can start developing our application, which I called PopularTags. As noted above, to work with the OAuth API for different languages have a ready library.

Twitter recommends using it to not “reinvent the wheel” by trying to write them from scratch yourself, and concentrate more on code direct application itself. And while on the website are only two libraries for PHP – oauth-PHP and twitteroauth, I also found and open-source library twitter-async. The latter is also fully functional, but still describe your example using the “officially approved” by the developers of the library – abraham’s twitteroauth.

Download the latest version here (Do not worry consoles beta). After it, see a lot of files, among them the familiar name callback.php. The archive includes a simple example that will work if you upload all the files from a folder on your web server.

Only need to be sure to register Callback URL keys in your application file config.php (the very same Consumer Key and Secret), which you gave at registration application. Example, which included, starts automatically when you move into a folder on the server (as it is called index.php), and when you first start redirects to a page with a button connect.php Sign in with Twitter, which defines the reference for To link your twitter with our application.

By clicking on the button, we go to the site twitter.com Outside query our login and password (if the user previously has not logged on) and then permission request application to access your account.

Twitter Allow Deny

After you click on Allow (or Deny) Twitter user returns to that same page, which is registered by us in the Callback URL, simultaneously transmitting unique tokens – oauth_token and oauth_token_secret.

With these tokens (instead of the login and password, as in the Basic Authentication) and we will work with the Twitter API via OAuth. Let’s look under the hood of scripts and see what we need to write your own application.

On the config.php file I have already written – there are prescribed constants with the keys of your application and Callback URL.

Index.php file begins with the library initialization

———————–

session_start ();
require_once (‘twitteroauth / twitteroauth.php’);
require_once (‘config.php’);

———————–

Any scripts that will handle the API must begin with these lines.

Next is a check for the presence in the current session of any user token. If not, we will be redirected to that same page with a button Sign in with Twitter – connect.php. It is checked whether we are filled with unique keys of our application, and if so, redirect to another leads us to the script redirect.php. On this page generates a link for communication with a user account application (called a URL authorization). To obtain such a reference is also required tokens – they are called temporary. The content of the script redirect.php:

———————————————————————-

/ * Initialize the library * /
session_start ();
require_once (‘twitteroauth / twitteroauth.php’);
require_once (‘config.php’);

/ * Create object TwitterOAuth based on the key of our application * /
$ Connection = new TwitterOAuth (CONSUMER_KEY, CONSUMER_SECRET);

/ * Get temporary tokens for authentication * /
$ Request_token = $ connection-> getRequestToken (OAUTH_CALLBACK);

/ * Write the temporary tokens into an array * /
$ _SESSION ['Oauth_token'] = $ token = $ request_token ['oauth_token'];
$ _SESSION ['Oauth_token_secret'] = $ request_token ['oauth_token_secret'];

/ * If the link to a site Twitter did not give an error (code 200), then generate a link for authentication * /

switch ($ connection-> http_code) (
case 200:
/ * Generate link and redirect to it * /
$ Url = $ connection-> getAuthorizeURL ($ token);
header (‘Location:’. $ url);
break;
default:
/ * If the connection was unsuccessful – an error * /
echo ‘Could not connect to Twitter. Refresh the page or try again later. ‘;
)

———————–

Here, I can not help but mention the fact that the library twitter-async (which is not described on the official website of the developers Twitter) procedure generate a link to authorize a much simplified. There is only one access to an object by getAuthenticateUrl () and we have a ready reference for buttons, temporary tokens, etc. – all this she does by herself.

So, we were redirected to a page with buttons “Allow / Deny”, allow the application to use our account and send Twitter Us page callback.php. Here we get the current session variables $ _SESSION ['oauth_token'] and $ _SESSION ['oauth_token_secret'], which we use to generate the final token to the application on behalf of the user. An excerpt of this piece of code:

———————–

/ * Check if not obsolete the current session (in case of user inactivity) * /
if (isset ($ _REQUEST ['oauth_token']) & & $ _SESSION ['oauth_token']! == $ _REQUEST ['oauth_token']) (
$ _SESSION ['Oauth_status'] = ‘oldtoken’;
header (‘Location:. / clearsessions.php’);
)

/ * Create object TwitteroAuth with the current session * /
$ Connection = new TwitterOAuth (CONSUMER_KEY, CONSUMER_SECRET, $ _SESSION ['oauth_token'], $ _SESSION ['oauth_token_secret']);

/ * Query the access-token-user for future permanent use * /
$ Access_token = $ connection-> getAccessToken ($ _REQUEST ['oauth_verifier']);

/ * Store them in an array * /
$ _SESSION ['Access_token'] = $ access_token;

/ * If an HTTP error was not redirected to the original file index.php * /

if (200 == $ connection-> http_code) (
/ * The user has been verified and the access tokens can be saved for future use * /
$ _SESSION ['Status'] = ‘verified’;
header (‘Location:. / index.php’);
) Else (
/ * Save HTTP status for error dialog on connnect page .* /
header (‘Location:. / clearsessions.php’);
)

———————–

After returning to index.php, we have the keys to the application and user tokens. Can refer to any resources as described in API Twitter (a list on the right column). In the example, this library is called the query:

$ Content = $ connection-> get (‘account / verify_credentials’);

As stated in the description of this function, it returns information about a user that was logged. This library is displayed in the format JSON (JavaScript Object Notation, the default format in the Twitter API) as well as the treatment goes to the class. For example, a user name:

$ Content-> name

or the number of followers (followers):

$ Content-> followers_count

While the author chose to bring the library dump JSON in a linear form:

print_r ($ content);

but the idea, I think, is clear.

It is time to move to the annex, which we mentioned at the outset. It should read the tape user (ie the tweets of those whom he Fallaway), finding in them heshtegi and select the most frequently used. The algorithm is simple – divide each tweet to separate words, will select those that contain the # symbol, and we derive the 5 most frequently used.

So, the script code:

———————————————————————-

redirect to a login page * /
if (empty ($ _SESSION ['access_token']) | | empty ($ _SESSION ['access_token'] ['oauth_token']) | | empty ($ _SESSION ['access_token'] ['oauth_token_secret'])) (
header (‘Location:. / clearsessions.php’);
)
/ * Get the user’s tokens * /
$ Access_token = $ _SESSION ['access_token'];

/ / Array Initsiruem
$ Words_Array_All = array ();

/ * Create object TwitterOAuth * /
$ Connection = new TwitterOAuth (CONSUMER_KEY, CONSUMER_SECRET, $ access_token ['oauth_token'], $ access_token ['oauth_token_secret']);

/ / Read the user’s belt with the parameter count, indicating that considered the last 200 tweets
$ TimeLine = $ connection-> get (‘statuses / home_timeline’, array (“count” => 200));

/ / Get it in a format JSON – treat each tweet
foreach ($ TimeLine as $ status)
(
$ Tweet = $ status-> text; / / text tweets
$ Author = $ status-> user-> screen_name; / / author tweets

/ / Before we treat tweet change case of letters to # Tag # tag and considered as a single
$ Tweet = mb_convert_case ($ status-> text, MB_CASE_TITLE, “UTF-8″);

/ / For clarity, we derive each tweet on the screen as: “Author: Message”
echo $ Author. “:”. $ Tweet. ”
“;

/ / Split the tweet on the words and write in an array
$ Words_Array = explode (“”, $ Tweet);

/ / Merge with the previous array
$ Words_Array_All = array_merge ($ Words_Array_All, $ Words_Array);
)

/ / Now calculate how frequent a particular item (word) and sort
$ Words_Array_All = array_count_values ($ Words_Array_All);
ArSort ($ Words_Array_All);

/ / Loop through the total array of words, find words with heshtegom (#) and write the new array
foreach ($ Words_Array_All as $ key => $ value)
(
if ((strpos ($ key ,”#”)! == false))
(
echo $ key .”(“.$ value .”)”.”
“;
$ Pop_Words [$ j] = $ key;
$ J + +;
)
)

/ / Display the first 5 elements of the array (the most popular tags)
$ PopularTags = ”
Most popular tags in my timeline: 1) “. $ Pop_Words [1].” 2) “. $ Pop_Words [2].” 3) “. $ Pop_Words [3].” 4) “. $ Pop_Words [4].” 5) “. $ Pop_Words [5].” mypopulartags # “;

echo $ PopularTags;

/ / Duplicate a message to our twitter
$ TheTweet = $ connection-> post (‘statuses / update’, array (‘status’ => $ Message));

?>

———————–

Of course, the code does not provide for error handling, and possibly some other stuff, but basically it is a working example.

If you allow access to this application, you’ll see about the next painting in your browser:

Also on the basis of this code is working and have developed an account that tracks popular tags and posts among some users of Twitter and displays them as a status in microblogging – it Works in automatic mode (thanks to the configured schedule Cron-y).

The article turned out great, but very much hope that all those who mastered it could get, then at least answer the question: “How to start and what can we do?”. And, as you have noticed, API Twitter so many different and interesting features, and daily increasing number of different services – a good example. Try to come up with an idea! ;) Successful experiments.

GD Star Rating
loading...
Writing PHP Application Using oAuth Twitter API, 8.5 out of 10 based on 10 ratings
(Visited 657 times, 1 visits today)