Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can an access token returned by Facebook to the Javascript SDK work server-side with the PHP SDK?

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?

like image 756
Casey Flynn Avatar asked Jul 22 '11 15:07

Casey Flynn


2 Answers

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!

like image 176
Sascha Galley Avatar answered Oct 13 '22 01:10

Sascha Galley


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.

like image 31
Sherms Avatar answered Oct 13 '22 01:10

Sherms