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

Facebook http://graph.facebook.com/?ids=YOURURL
Twitter http://urls.api.twitter.com/1/urls/count.json?url=YOURURL
Google 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!

23 thoughts on “Getting Counts for Twitter Links, Facebook Likes/Shares, and Google (+1) PlusOnes in C# or PHP

  1. 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’])

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

  3. 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;
    }

  4. 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

  5. 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

  6. this isn’t correct: var json = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize(jsonString); from googleplus method of c#. because Deserialize wanted two Arguments

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

      1. private int GetLikes(string url)
        {
        int number_of_likes = 0;
        dynamic value = “”;
        int count = 0;
        //object c;
        url = “EVOLVEIndia”;
        //using (WebClient client = new WebClient())
        //{
        string jsonString = new System.Net.WebClient().DownloadString(“https://graph.facebook.com/?ids=” + url);
        System.Web.Script.Serialization.JavaScriptSerializer obj1 = new System.Web.Script.Serialization.JavaScriptSerializer();
        Dictionary objDic = (Dictionary)obj1.Deserialize(jsonString);
        bool success = false;
        success = objDic.TryGetValue(“EVOLVEIndia”, out value);
        if (success)
        {
        success = value.TryGetValue(“likes”, out value);
        if (success)
        {
        number_of_likes = (int)value;
        }
        }
        return number_of_likes;
        }
        this code is working for facebook likes in c#

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

  8. emelőgép, daru, földmunkagép, üzembehelyezés, emelőgép
    szakértő országosan, profin, megbízhatóan, szakértelemmel.
    Crane and heavy machine expert.

  9. I have read so many articles or reviews about
    the blogger lovers except this article is really a fastidious article, keep it up.

Comments are closed.