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

Xenon
  • 815
  • 11
  • 26

5 Answers5

10

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.

Community
  • 1
  • 1
Imran
  • 434
  • 5
  • 13
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>
TheCodeKing
  • 19,064
  • 3
  • 47
  • 70
  • 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 '11 at 06: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 '11 at 07: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. – TheCodeKing Sep 12 '11 at 07: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 '11 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? – TheCodeKing Sep 13 '11 at 11:53
  • Apparently if you call the IsFan API without a UID it will infer the currently logged in user, obviously this requires a client-side call. – TheCodeKing Sep 13 '11 at 17:43
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;
            }
        }
    }
}
DarthJDG
  • 16,511
  • 11
  • 49
  • 56
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.

jches
  • 4,542
  • 24
  • 36
  • Hi @chesles can you give me some information about decode_signed_request()? – Xenon Sep 12 '11 at 06:51
  • Check out the "verify and decode" heading in the [signed_request docs](http://developers.facebook.com/docs/authentication/signed_request/) for an outline on how to implement this. There are 2 parts, a signature and a payload. The payload is just [base64 encoded](http://base64decode.org/), 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 '11 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

mjs
  • 657
  • 7
  • 14
  • Same problem i couldn't get uid without getting permission so it won't works :\ – Xenon Sep 13 '11 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 '11 at 05:19