6

I'm building a website that makes use of Facebook connect. I'm authenticating users client-side with the javascript SDK and calling an AJAX method on my server every time a user logs in to check if the user is known to my app, and if the user is new to store their FBID in my database to register them as a new user.

My question is: Can the access token returned by Facebook to the Javascript SDK be used server-side (with the PHP SDK for example)? Can I send the access token string to the server via an AJAX call, store it in my database (along with a timestamp so I know how long it's valid for) and then use it to make calls to the graph API server-side? Is this even a logical thing to do?

Casey Flynn
  • 13,654
  • 23
  • 103
  • 194

2 Answers2

3

Yes, this should work. Look at this question: How to properly handle session and access token with Facebook PHP SDK 3.0?

This is a workaround for the old JS and new PHP SDK. In my app I send the access token generated by the JS SDK via a form to my PHP. I have no doubts that this also works by sending the access token via ajax!

Community
  • 1
  • 1
Sascha Galley
  • 15,711
  • 5
  • 37
  • 51
3

Using Jquery:

//Set an error message
var oops = ("Put your something went wrong message here.");
//Function to post the data to the server
    function save(uid, accessToken){
        $.post("../foo/bar", { uid: uid, access_token: accessToken, etc, etc }, function(data){
            alert("Successfully connected to Facebook.");
            location.reload();
        }, "text");
    }
    function handler(x){
        if (x.authResponse){
            var token = x.authResponse.accessToken;
            var uid   = x.authResponse.id;
            FB.api("/me/accounts", {access_token: token},
            function(response){
                if(response.data.length == 0) {
//Regular facebook user with one account (profile)
                    save(uid, token);
                }else{
//Handle multiple accounts (if you want access to pages, groups, etc)
                }
            });
        }else{
            alert(oops);
        }
    }
    FB.login(handler, {scope: 'The list of permissions you are requesting goes here'});

Any improvement suggestions are always appreciated.

Sherms
  • 1,567
  • 1
  • 15
  • 31
  • I'm curious what you think of my implementation. This is the header of my pages: (loads the javascript sdk and detects user login/logout) http://pastebin.com/sSR1zrfN and this is the included javascript file that calls my server for every user login/logout: http://pastebin.com/ET1C6deQ – Casey Flynn Aug 02 '11 at 14:55
  • Lines 60-70 are relevant in the first file. That's how I'm doing my user login/logout detection. – Casey Flynn Aug 02 '11 at 14:56