Determine if a Facebook user Likes your page with ASP.NET

by Duane Urban 29. February 2012 01:32

I recently started my first Facebook app beyond a static html page. After hours on Bing looking for an answer to a simple question all I found were a lot of obsolete articles or references to various Facebook SDK’s which were poorly documented and as far as the ASP.NET versions were concerned - none answered my simple question about determining if a user “Likes” your page. So I had to roll my own, blah, blah..

The good news as it turns out is that all you have to do is send a GET request to the Facebook API and if all is well it responds with a JSON formatted name : value data list of the page ID’s a user “Likes”. From there it’s a simple matter of searching the JSON string for your page’s Id. While you are at it please ignore the Facebook REST service - it's all JSON now. Also Fan" is now "Like"

The code samples are in VB.NET and C# for the web service and assume you already know the prerequisites for calling a web service from code, getting a Facebook user’s publically accessible data and user Id. The code samples below should help get you started on your way to being Marketing's next golden boy or girl :) 

Imports System.Net
Imports System.IO
Imports System.Web.Services
Imports System.Web.Services.Protocols
Imports System.ComponentModel
 ' To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
<System.Web.Script.Services.ScriptService()> _
<System.Web.Services.WebService(Namespace:="http://tempuri.org/")> _
<System.Web.Services.WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
<ToolboxItem(False)> _
Public Class FaceBookService
    Inherits System.Web.Services.WebService
    <WebMethod()> _
    Public Function GetFacebookLikeStatus(ByVal fbpageid As String, ByVal fbappid As String, _
                                          ByVal fbtoken As String, ByVal fburl As String)
        Dim strReturn As String = Nothing
        ' Placeholder for the Facbook "like" API call
        Dim strURL As String = Nothing
        strURL = "https://graph.facebook.com/me/likes?access_token=" + fbtoken
        ' Placeholder for the Facebook GET response
        Dim objGETURL As WebRequest
        objGETURL = WebRequest.Create(strURL)
        ' Declare response stream
        Dim objStream As Stream = Nothing
        ' Declare The Facebook response
        Dim strLine As String = Nothing
        ' Declare a count on the search term
        Dim intStr As Integer = 0
         Try
            ' Create an instance of the StreamReader
           
Dim objReader As New StreamReader(objStream)
           
' Get the response from the Facebook API as a JSON string.
            ' If access_token is not correct for the logged
            ' on user Facebook returns (400) bad request error
            objStream = objGETURL.GetResponse.GetResponseStream()
            ' If all is well 
            Try
                ' Execute the StreamReader
                strLine = objReader.ReadToEnd().ToString()
                ' Check if Facebook page Id exists or not
                intStr = strLine.IndexOf(fbpageid)
                If intStr > 0 Then  ' if valid return a value
                    strReturn = "1"               
                Else                ' if not valid return a value
                    strReturn = "0"
                End If
            Catch ex As Exception
                ' For testing comment out for production
                strReturn = ex.ToString()
                ' Uncomment below for production
                'strReturn = "Some friendly error message"
            End Try
            objStream.Dispose()
        Catch ex As Exception
            ' For testing comment out for production
            strReturn = ex.ToString()
            ' Uncomment below for production
            'strReturn = "Some friendly error message"
        End Try
        Return strReturn
     End Function
 End Class 

using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Net;
using System.IO;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.ComponentModel; 
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService()]
[System.Web.Services.WebService(Namespace = http://tempuri.org/)]
[System.Web.Services.WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ToolboxItem(false)]public class FaceBookService : System.Web.Services.WebService
{               
               [WebMethod()]
               public string GetFacebookLikeStatus(string fbpageid, string fbappid, string fbtoken, string fburl)
               {
                              string strReturn = null;
                              // Placeholder for the Facbook "like" API call
                              string strURL = null;
                              strURL = "https://graph.facebook.com/me/likes?access_token=" + fbtoken;
                              // Placeholder for the Facebook GET response
                              WebRequest objGETURL = null;
                              objGETURL = WebRequest.Create(strURL);
                              // Declare response stream
                              Stream objStream = null;
                              // Declare The Facebook response
                              string strLine = null;
                              // Declare a count on the search term
                              int intStr = 0;
                              try {
                                            // Create an instance of the StreamReader
                                            StreamReader objReader = new StreamReader(objStream);
                                             // Get the response from the Facebook API as a JSON string.
                                             // If access_token is not correct for the logged
                                             // on user Facebook returns (400) bad request error

                                             objStream = objGETURL.GetResponse().GetResponseStream();
                                             // If all is well 
                                             try {
                                                            // Execute the StreamReader
                                                            strLine = objReader.ReadToEnd().ToString();
                                                            // Check if Facebook page Id exists or not
                                                            intStr = strLine.IndexOf(fbpageid);          // if valid return a value
                                                            if (intStr > 0) {
                                                                           strReturn = "1";
                                                            // if not valid return a value
                                                            } else {
                                                                           strReturn = "0";
                                                            }
                                                           objStream.Dispose();
                                             } catch (Exception ex) {
                                                            // For testing comment out for production
                                                            strReturn = ex.ToString();
                                                            // Uncomment below for production
                                                            //strReturn = "Some friendly error message"
                                             }
                              } catch (Exception ex) { 
                                           
// For testing comment out for production
                                             strReturn = ex.ToString();
                                          // Uncomment below for production
                                          //strReturn = "Some friendly error message"
                              }
                               return strReturn;
                }
}
              

To get your access token for testing go to http://developers.facebook.com/docs/reference/api/ , scroll down a little and copy a shortcut from one of the links on the page displayed in the screen shot below.NOTE:  This token is only good for your current session.


 

If you need to figure out Facebook authentication go here http://developers.facebook.com/docs/authentication/.  It goes over the various callbacks between your app and Facebook and they actually have a complete code sample (in PHP) that isn't referencing some sort of SDK. 

 

Tags: ,

ASMX | ASP.NET | Facebook API