ccoenraets / OpenFB

Micro-library that lets you integrate browser and Cordova apps with Facebook with no plugin or SDK dependency.
MIT License
507 stars 230 forks source link

invalid token provided [solved] #107

Open De-Lac opened 8 years ago

De-Lac commented 8 years ago

I was stuck for days on this issue... I managed to login, but at the first API call ( /me for example), I got the error "

a valid access token should be provided in order to... bla bla bla"

Finally I found the solution. I consider it strange that it seems that just me I got this error. By the way, the problem is in the openfb.js library.

During the login, I store the obtained access_token in a variable

function login(callback, options) 
{..
loginWindow = window.open(loginURL + '?client_id=' + fbAppId + '&redirect_uri=' + redirectURL +
            '&response_type=token&scope=' + scope, '_blank', 'location=no,clearcache=yes');
...
}

function oauthCallback(url) {
if (url.indexOf("access_token=") > 0) 
   {
    ...
    tokenStore.fbAccessToken = obj['access_token'];
    ....
}

Then, once I invoke an API call, the function api() is executed, and here I found a problem

function api(obj) {
        var method = obj.method || 'GET',
            params = obj.params || {},
            xhr = new XMLHttpRequest(), url;
            console.log('tokenStore.fbAccessToken  '+tokenStore.fbAccessToken); // here the token is present
            // params = JSON.parse(JSON.stringify(obj));   // my solution
            params['access_token'] = tokenStore.fbAccessToken;
            console.log('access_token   '+params['access_token'] ); // this is undefined !!!!!!
            console.log('params  '+JSON.stringify(params)); // this just contains the perms asked
           ....
}

So it seems that params['access_token'] = tokenStore.fbAccessToken; is not working. I solved cloning the object, so i becomes editable. params = JSON.parse(JSON.stringify(obj));

De-Lac commented 8 years ago

and... neither the fields selection worked for me. I had to change it.... now in openfb.js I have

function api(obj) {
        var method = obj.method || 'GET',
            fields = obj.fields || {},
            xhr = new XMLHttpRequest(),
            url;

       // url = 'https://graph.facebook.com' + obj.path + '?' + toQueryString(params); // as was before
        url = 'https://graph.facebook.com' + obj.path + '?' 
              +"fields="        + fields
              +"&access_token=" + tokenStore.fbAccessToken;
        console.log('openfb '+url);   // try to open it in a browser to test

and in my controller I do

 ngFB.api({path: '/me', fields:"id, picture, email, gender, first_name, last_name, location"})
     .then(function(response)
     {...});
solcarty commented 8 years ago

Thanks!

This solution worked for me.