6

Hi i'm developing an application in facebook with c# sdk and i want that the user whom liked my page can only use my application. (Like woobox)

I found some solutions in php in this link but there isn't any source about .net how can i get the liked info in ASP.NET

I find another examples in php in this link again but i can't find c# answer :\

Thanks

2
  • Could you explain why the existing answer isn't what you're looking for? Sep 9, 2011 at 2:07
  • Because it needs permissions, i need a code without getting permission like woobox.
    – Xenon
    Sep 9, 2011 at 12:59

5 Answers 5

10
+100

You get signed request when your web page is loaded within facebook canvas app; you should be able to parse signed request something similar to following:

if (Request.Params["signed_request"] != null)
{
    string payload = Request.Params["signed_request"].Split('.')[1];
    var encoding = new UTF8Encoding();
    var decodedJson = payload.Replace("=", string.Empty).Replace('-', '+').Replace('_', '/');
    var base64JsonArray = Convert.FromBase64String(decodedJson.PadRight(decodedJson.Length + (4 - decodedJson.Length % 4) % 4, '='));
    var json = encoding.GetString(base64JsonArray);
    var o = JObject.Parse(json);
    var lPid = Convert.ToString(o.SelectToken("page.id")).Replace("\"", "");
    var lLiked = Convert.ToString(o.SelectToken("page.liked")).Replace("\"", "");
    var lUserId= Convert.ToString(o.SelectToken("user_id")).Replace("\"", "");
}

You need to add reference to json libraries in order to parse signed requestin C#, download from http://json.codeplex.com/

Also refere to How to decode OAuth 2.0 for Canvas signed_request in C#? if you are worndering about signed request.

0
4

This is only possible with the legacy APIs, or with the user_likes permission. As you want a solution without specific permissions I'll show you 2 methods. Use them in combination with AJAX to refresh the page when a user presses like.

Option 1) REST API

Using the legacy API, it's possible to use Pages.IsFan

https://api.facebook.com/method/pages.isFan?
page_id=...&
uid=...&
access_token=...

Do this in C# as follows.

var appID = "....";
var appSecret = "....";
var uid = "....";
var pageId = "....";

WebClient client = new WebClient();
var appAuthUri = string.Concat("https://graph.facebook.com/oauth/access_token?",
                            "client_id=", appID,
                            "&client_secret=", appSecret,
                            "&grant_type=", "client_credentials"
                            );
var response = client.DownloadString(appAuthUri);
var access_token = response.Split('=')[1];

var isFanUri = string.Concat("https://api.facebook.com/method/pages.isFan?",
                            "format=", "json",
                            "&page_id=", pageId,
                            "&uid=", uid,
                            "&access_token=", access_token
                            );
response = client.DownloadString(isFanUri);
bool isFan;
bool.TryParse(response, out isFan);

Option 2) Client side

The FBXML method. This is done with Javascript on the client, by subscribing to an event when the user clicks the like button. It's documented here.

How do I know when a user clicks a Like button?

If you are using the XFBML version of the button, you can subscribe to the 'edge.create' event through FB.Event.subscribe.

Generate an FBXML like button here.

<div id="fb-root"></div>
<script>(function(d){
  var js, id = 'facebook-jssdk'; if (d.getElementById(id)) {return;}
  js = d.createElement('script'); js.id = id; js.async = true;
  js.src = "//connect.facebook.net/en_US/all.js#appId=132240610207590&xfbml=1";
  d.getElementsByTagName('head')[0].appendChild(js);
}(document));</script>
<div class="fb-like" data-href="http://www.thecodeking.co.uk" data-send="true" data-width="450" data-show-faces="false"></div>

Then subscribe to the edge.create event using the Javascript SDK. Place this code in the document BODY preferably just before the end.

<script type="text/javascript">
<!--
    window.fbAsyncInit = function () {
        FB.init({ appId: '245693305442004', status: true, cookie: true, xfbml: true });
        FB.Event.subscribe('edge.create',
            function (href, widget) {
                // Do something here
                alert('User just liked '+href);

            });
            (function () {
                var e = document.createElement('script'); e.async = true;
                e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
                document.getElementById('fb-root').appendChild(e);
            } ());
    };
//-->
</script>
6
  • Hi @TheCodeKing i will try the option 2 but can you tell me how can you get uid in option1? Because in this case user didn't give permission to give any info to us and without uid i can't get Page.IsFan ?
    – Xenon
    Sep 12, 2011 at 6:49
  • Hi again i tried option 2 but it works when user likes or dislikes a page but i couldn't get that if the user liked the page before :\ do you have any opinion? thanks.
    – Xenon
    Sep 12, 2011 at 7:02
  • I think you get the uid if you add a login button so users are logged into your page. Theres a function FB.getUserId. Sep 12, 2011 at 7:13
  • In Canvas application i can't have a facebook login button (It's not logical because user already logged in to facebook) so i can't get user's id?
    – Xenon
    Sep 13, 2011 at 11:20
  • If user is already logged in, I would have thought you can just call Fb.GetUserID() on the client. Does this not work? Sep 13, 2011 at 11:53
1
this.canvasAuthorizer = new CanvasAuthorizer {
    Permissions = new[] { "user_about_me", "publish_stream", "offline_access", "user_likes", "friends_about_me" }
};

this.canvasAuthorizer.Authorize();

if (FacebookWebContext.Current.IsAuthorized())
{
    this.facebookWebClient = new FacebookWebClient(FacebookWebContext.Current);

    string requested_Data = HttpContext.Current.Request.Form["signed_request"];
    dynamic decodedSignedRequest = FacebookSignedRequest.Parse(this.facebookApplication, requested_Data);

    if (decodedSignedRequest.Data.page != null)
    {
        // Funs Page
        this.IsLike = decodedSignedRequest.Data.page.liked;
    }
    else
    {
        // Application Page
        dynamic likes = this.facebookWebClient.Get("/me/likes");
        foreach (dynamic like in likes.data)
        {
            if (like.id == this.FacebookFanPageID)
            {
                this.IsLike = true;
            }
        }
    }
}
0
1

If your app is a canvas app, you could (should?) use the signed_request parameter to check if the user likes the page it's on:

# pseudocode
signed_request = decode_signed_request()
if signed_request['page']['liked']:
  # user liked page, do something cool
else:
  # user doesn't like page. redirect somewhere to tell them why they should

The signed_request is passed to your page as a POST variable; just as if there was a form field named signed_request and the form was submitted on the page previous to yours (in fact this is basically how facebook "runs" your app; the form is auto-submitted instead of waiting for a user to submit it). So in ASP.net you should be able to get it through the Request object:

Request["signed_request"]

This approach is useful if you're creating a "tab app" for a page; you can detect whether the user liked the page without them granting you extra permissions.

2
  • Hi @chesles can you give me some information about decode_signed_request()?
    – Xenon
    Sep 12, 2011 at 6:51
  • Check out the "verify and decode" heading in the signed_request docs for an outline on how to implement this. There are 2 parts, a signature and a payload. The payload is just base64 encoded, so you will have to find out how to decode it in C#; I'm not a .Net guy but I'm sure there's a decoder library in there someplace.
    – jches
    Sep 12, 2011 at 14:01
0

This can be done in PHP with the help of an SQL Query

`$result = $facebook->api(array(  "method"    => "fql.query",
                                  "query"     => "SELECT uid FROM page_fan WHERE uid=$uid AND page_id=$page_id"
                               ));

Here $result variable can be used for segregating the Fan and non-Fan content

2
  • Same problem i couldn't get uid without getting permission so it won't works :\
    – Xenon
    Sep 13, 2011 at 13:17
  • See without creating a FB session you cannot access any detail inside an application .. So first step will always be asking 4 basic set of permissions ( as required by your app ). then in the following steps you can decide based on the uid whether that person likes your page or not ..
    – mjs
    Sep 14, 2011 at 5:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.