PHPBuilder - Counting Facebook Likes and Twitter Tweets in Your App



RSS Twitter
Articles

Counting Facebook Likes and Twitter Tweets in Your App

by: Voja Janjic
|
March 26, 2015

Although the number of shares and tweets can be shown on a page using widgets, sometimes you may want to use that information programmatically in your application. That will be explained in this article. You will learn how to fetch the data from Facebook and Twitter, how to optimize the connection to these web sites and how to automatically update the data.

 

Facebook Like Count

Let's start with Facebook. We will fetch the data using their Graph API by sending a HTTP GET request to the following URL:

 

https://graph.facebook.com/?ids=http://www.myurl.com/my-page

 

The response is JSON encoded and would be similar to this:

 

{
   "http://www.myurl.com/my-page": {
      "og_object": {
         "id": "659836867478500",
         "description": "Your page description",
         "title": "Your page title",
         "type": "article",
         "updated_time": "2015-03-20T16:22:53+0000",
         "url": "http://www.myurl.com/my-page"
      },
      "share": {
         "comment_count": 6,
         "share_count": 310
      },
      "id": "http://www.myurl.com/my-page"
   }
}

 

Although the API returns the data without authentication, the rate limit for non-authenticated requests is rather small and will get you blocked quickly. That's why we need to include an application token with each request. Application token is your application id and application secret separated by a pipe (|). The application token can be passed as a GET parameter:

 

https://graph.facebook.com/?ids=http://www.myurl.com/my-page&access_token=myappid|myappsecret

 

The response from above returns a piece of data called the "share count". Share count is not just a like count, but a combination of like count, share count, comment count and inbox shares for an URL.

 

However, in most cases, it is needed to sort articles by social popularity, meaning that the share count is generally an even better solution than having only the like count.

 

Another thing to note is that the Graph API has a rate limit for authenticated users as well. The limit is said to be 600 requests per 600 seconds, but that information has not been confirmed by Facebook. However, they have stated in the API documentation that the application making "too many calls" will be throttled. It is advised to check for that error in your code, and, in case the error appears, stop the code execution and wait for a certain amount of time before retrying. Here is an example of Graph API error response:

 

{ "error": { "message": "Message describing the error", "type": "OAuthException", "code": 4 , "error_subcode": subcode_number } }

 

Calling the API for each URL in cases where you have a lot of URLs can be very slow and you would lose a lot of time in sending and receiving the requests. It is a better solution to use batch requests, where you can make multiple API calls in one request:

 

https://graph.facebook.com/?ids=http://www.myurl.com/my-page,http://www.myurl.com/second-page&access_token=myappid|myappsecret

 

Note that two API calls in one request still count as 2 calls towards the API rate limit.

 

One we've covered the principles of connecting to the Facebook Graph API and fetching the data, let's see the PHP code in action:

 

// Fetch items here
		
		$i = 0;
		$news_ids = '';

		// Maximum number of URL per each batch request
		$urs_per_request = 10;
		foreach($items as $item)
		{
			if($i < $urls_per_request) 
			{
				// Still less than 10 URLs, append the item URL to a string
				$news_ids .= ',' . news_url($item);
				$i++;
			}
			else 
			{
				// We have 10 URLs now, make the API call

				$news_ids = substr($news_ids, 1);
				$url = 'https://graph.facebook.com/?ids=' . $news_ids . '&access_token=myappid|myappsecret';
				
				// Initialize cURL library
				$ch = curl_init($url);
			
				// Return server response
				curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

				// Ignore SSL
				// DON'T USE this in cases where you are transferring confidential data
				curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
				
				$raw_response = curl_exec($ch);
				curl_close($ch);
				
				// Decode server response
				$response = json_decode($raw_response);
				
				// Loop through the array of URLs
				foreach($response as $r)
				{
					
					if(isset($r->share->share_count))
					{
						// Save the share count in the database
						$item->fb_like_num = $r->share->share_count;
						$item->save();
					}
				}
				
				// Reset the counter and the URLs string
				$i = 0;
				$news_ids = '';
			}
		
		}
	
		// Repeat the connection to the API
		// This is used for cases where there are less than 10 URLs in the last batch request

			$news_ids = substr($news_ids, 1);
			$url = 'https://graph.facebook.com/?ids=' . $news_ids . '&access_token=1603919973155864|b120157a70de309966df5977f0a8256a';
			
			$ch = curl_init($url);
		
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
			curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
			
			$raw_response = curl_exec($ch);
			curl_close($ch);
			
			$response = json_decode($raw_response);
			
			foreach($response as $r)
			{
				
				if(isset($r->share->share_count))
				{
					$item->fb_like_num = $r->share->share_count;
					$item->save();
					
				}
			}
			
			$i = 0;
			$news_ids = ''; 

 

Twitter Tweet Count

Fetching the tweet count is a little different from fetching Facebook likes. There is a simple way to do it by sending a get request to the following URL:

 

http://urls.api.twitter.com/1/urls/count.json?url=http://www.mydomain.com/my-page

 

The Twitter API returns the response in JSON format:

 

{"count":1,"url":"http:\/\/wwwmydomain.com\/my-page"}

 

The Twitter API does not support batching requests. Except for that, the code is almost the same as the Facebook's:

 

$url = 'http://urls.api.twitter.com/1/urls/count.json?url=' . $url;
			
			$ch = curl_init($url);
		
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
			curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
			
			$raw_response = curl_exec($ch);
			curl_close($ch);
			
			$response = json_decode($raw_response);
			
			foreach($response as $r)
			{
				
				if(isset($r->count))
				{
					$item->twitter_num = $r-> count;
					$item->save();
				}
			}

 

Please note that this method is deprecated and will not be available in a few months. At the moment, Twitter count is not available in the new API. There is an alternative solution to the problem by using the streaming API (discussed here), but it's quite overly complicated. Hopefully the Twitter developers will do something about it soon.

 

Comment and Contribute

Your comment has been submitted and is pending approval.

Author:
Voja Janjic

Comment:



Comment:

(Maximum characters: 1200). You have characters left.