Getting Counts for Twitter Links, Facebook Likes/Shares, and Google (+1) PlusOnes in C# or PHP
I am working on a project where I need to know the number of social shares on Facebook, Twitter, and Google +1 (plusone). Facebook and Twitter make this easy with a simple URL that returns clear JSON data, but Google has not offered an official way to do it yet. However, I found someone who tracked down how to do it using Google’s JSON-RPC API, and I’ve repackaged them together in ASP.NET and PHP for anyone who wants to give it a try.
Data URLs
Here’s where you can find the data
| http://graph.facebook.com/?ids=YOURURL | |
| http://urls.api.twitter.com/1/urls/count.json?url=YOURURL | |
| https://clients6.google.com/rpc [see below for JSON-RPC] |
ASP.NET C#
Note: Since I’m using “dynamic,” this requires .NET 4.0. Also, I’m using the JavaScriptSerializer class which is officially depreciated, but will probably not actually be removed. You could also easily use Regex to get these simple values.
int GetTweets(string url) {
string jsonString = new System.Net.WebClient().DownloadString("http://urls.api.twitter.com/1/urls/count.json?url=" + url);
var json = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize(jsonString);
int count = (int)json["count"];
return count;
}
int GetLikes(string url) {
string jsonString = new System.Net.WebClient().DownloadString("http://graph.facebook.com/?ids=" + url);
var json = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize(jsonString);
int count = json[url]["shares"];
return count;
}
int GetPlusOnes(string url) {
string googleApiUrl = "https://clients6.google.com/rpc"; //?key=AIzaSyCKSbrvQasunBoV16zDH9R33D88CeLr9gQ";
string postData = @"[{""method"":""pos.plusones.get"",""id"":""p"",""params"":{""nolog"":true,""id"":""" + url + @""",""source"":""widget"",""userId"":""@viewer"",""groupId"":""@self""},""jsonrpc"":""2.0"",""key"":""p"",""apiVersion"":""v1""}]";
System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(googleApiUrl);
request.Method = "POST";
request.ContentType = "application/json-rpc";
request.ContentLength = postData.Length;
System.IO.Stream writeStream = request.GetRequestStream();
UTF8Encoding encoding = new UTF8Encoding();
byte[] bytes = encoding.GetBytes(postData);
writeStream.Write(bytes, 0, bytes.Length);
writeStream.Close();
System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse();
System.IO.Stream responseStream = response.GetResponseStream();
System.IO.StreamReader readStream = new System.IO.StreamReader(responseStream, Encoding.UTF8);
string jsonString = readStream.ReadToEnd();
readStream.Close();
responseStream.Close();
response.Close();
var json = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize(jsonString);
int count = Int32.Parse(json[0]["result"]["metadata"]["globalCounts"]["count"].ToString().Replace(".0", ""));
return count;
}
PHP
Again, thanks to Tom Anthony for the Google part
function get_tweets($url) {
$json_string = file_get_contents('http://urls.api.twitter.com/1/urls/count.json?url=' . $url);
$json = json_decode($json_string, true);
return intval( $json['count'] );
}
function get_likes($url) {
$json_string = file_get_contents('http://graph.facebook.com/?ids=' . $url);
$json = json_decode($json_string, true);
return intval( $json[$url]['shares'] );
}
function get_plusones($url) {
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, "https://clients6.google.com/rpc");
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, '[{"method":"pos.plusones.get","id":"p","params":{"nolog":true,"id":"' . $url . '","source":"widget","userId":"@viewer","groupId":"@self"},"jsonrpc":"2.0","key":"p","apiVersion":"v1"}]');
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-type: application/json'));
$curl_results = curl_exec ($curl);
curl_close ($curl);
$json = json_decode($curl_results, true);
return intval( $json[0]['result']['metadata']['globalCounts']['count'] );
}
Hope that helps someone out there!
just for fun I cobbled together a python example
import urllib2, json
data = ‘[{"method":"pos.plusones.get","id":"p","params":{"nolog":true,"id":"%s","source":"widget","userId":"@viewer","groupId":"@self"},"jsonrpc":"2.0","key":"p","apiVersion":"v1"}]‘ % "http://www.tomanthony.co.uk/"
url = "https://clients6.google.com/rpc?key=AIzaSyCKSbrvQasunBoV16zDH9R33D88CeLr9gQ"
req = urllib2.Request(url, data, {‘Content-Type’: ‘application/json’})
f = urllib2.urlopen(req)
response = f.read()
f.close()
result = json.loads(response)
print int(result[0]['result']['metadata']['globalCounts']['count'])
Really helpful article. Here is a complete list of code snippets to fetch social counts from various sites like facebook, twitter, google plus, pinterest etc: http://cube3x.com/get-social-share-counts-a-complete-guide/
Helps me. I was looking for that. i get an error but i think its a firefox error but ill throw it out there just in case.
permission denied from to get property Proxy.InstallTrigger.
if you get any idea what that is.
If you want to get Facebook `total_count` (e.g. `likes` + `shares`) here is a modification of the function:
function get_likes($url) {
$json_string = file_get_contents(‘http://graph.facebook.com/?ids=’ . $url);
$json = json_decode($json_string, true);
$total_count = 0;
if (isset($json[$url]['shares'])) $total_count += intval($json[$url]['shares']);
if (isset($json[$url]['likes'])) $total_count += intval($json[$url]['likes']);
return $total_count;
}
Thanks John, just what I needed. the google+ details were illusive elsewhere. And thanks for Tom also for doing the php version.
Hi,
Can anyone explain how to use the PHP code to display the number of likes on a html page?
I would like to know how to use it.
cheers
Alex
you will need to install php in order to do that. search google for lamp/wamp/xamp.
btw here are 2 examples on how to retrieve likes count: http://newexception.com/facebook-like-counter
I reply on marketing on Facebook and Google Plus a lot. My favorite site to get Likes for my Facebook page is GetLikesEasy.com. It’s a fast and easy Like Exchange system, and I’ve already gotten more than a thousand Likes. Check it out!. http://GetLikesEasy.com. My favorite site to get Plus Ones for Google+ is GetPlusOnesGoogle.com. http://GetPlusOnesGoogle.com
Thanks for sharing. I could run facebook and twitter but google code gives “Invalid Data” error?
Google+ doesn’t work. I think its not related with Google console settings.
Thanks John, just what I needed. the google+ details were illusive elsewhere.
Thank you
Use full one
And now +1 is not working always zero
this isn’t correct: var json = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize(jsonString); from googleplus method of c#. because Deserialize wanted two Arguments
Hey were you guys to figure out how to parst the json response like you said
var json = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize(jsonString);
int count = json[url]["shares"];
This doesn’t see to be working.
[...] a method to get a webpage url and return count of it’s +1. I searched google and just find this and the method [...]
Thanks! Now my G+ works..
Thanks, I couldn’t run Google+ too with Asp.Net.
Neo how could you run it, can you share it pls.
Well as for Google Plus
same url
on a Google Pages of My web site i get 5 likes !
But with this code i get 2 shares?
How can i get a page pluses – likes
Thanks, very useful post. Do you have php code to get “pin it” count?
Thanks,
Bibhuti
Like count is different with share count in Facebook. Your code is for share count. How to get just for Facebook like count?
Nice code by the way!
[...] Special thanks to Eric Matthys for his base inline loading widget and to John Dyer for his post on retrieving counts from various Social Networks. [...]
Thank You Devil
i have add four more functions to get Linkedin share, delicious bookmarks, Pinterest share, stumbleupon view
check this http://toolspot.org/script-to-get-shared-count.php
I have a php code for the counter but I need to add something to the counter is as follows:
1k
1100k
1200k etc
2k
2100k etc… and
2m
2500m