Facebook Javascript Ajax身份验证

时间:2016-05-24 18:40:53

标签: javascript ajax facebook cordova

我已经通过Facebook验证了我的Cordova应用程序,虽然我正在尝试检索一些数据并且我收到错误。想知道我的网址是否不正确。任何人都可以发现这个错误吗?

错误:

app: makeAPICalls: error:setting authenticatedUser to Yes and skip registration.{"readyState":0,"status":0,"statusText":"Error: SyntaxError: DOM Exception 12"}    

function makeAPICallsFB(token) {
$.ajax(
    {
        //url: 'https://api.linkedin.com/v1/people/~?format=json',
        url: 'https://graph.facebook.com/v2.6/me?fields=id,first_name,last_name,bio,email,work,friends,picture{url}',
        //url: 'https://graph.facebook.com/v2.6/oauth/access_token',
        beforeSend: function (xhr) {
            try {
                console.log("Authorization...");
                xhr.setRequestHeader('authorization', 'Bearer ' + token);
                console.log("Finished Auth...");
            } catch(err) {
                alert(err);
            }
        },
        success: function (linkedInData) {
            console.log("TEST....");
            if (linkedInData != null) {
                console.log("Success");
                try {
                    console.log('app: makeAPICalls LinkedInData: ' + JSON.stringify(linkedInData) + " token: " + token);
                    console.log('name: ' + linkedInData.id);
                    vsetaService.saveLinkedInData(linkedInData, token);
                    checkUserStatus();
                } catch(err) {
                    alert(err);
                }
            } else {
                alert("Data is NULL!");
            }
        },
        error: function (error) {
            console.log("app: makeAPICalls: error:setting authenticatedUser to Yes and skip registration." + JSON.stringify(error));
            //navigator.notification.confirm('Unable to connect to LinkedIn at this time.', confirmCallback, "VSETA - Think Material", ["Ok"]);
            //Take user to Home if an error with LinkedIn + Temp assign access
            authenticatedUser = 1;
            homeScreen();
        }
    });
console.log("Finished!");
}

这是我的FB登录

function oauth2_loginFaceBook() {
    $.oauth2({
        type: 'post',
        auth_url: 'https://www.facebook.com/v2.6/dialog/oauth',           // required
        response_type: 'code',      // required - "code"/"token"
        token_url: 'https://www.facebook.com/v2.6/oauth/access_token',          // required if response_type = 'code'
        logout_url: '',         // recommended if available
        client_id: 'confidential',          // required
        client_secret: 'confidential',      // required if response_type = 'code'
        redirect_uri: 'http://localhost/callback',       // required - some dummy url
        other_params: { scope: 'public_profile', state: 'somethingrandom1234' }        // optional params object for scope, state, display...
    }, function (token, response) {
        console.log('app: oauth2_login Success: ' + response.text);
        // do something with token or response
        makeAPICallsFB(token);

    }, function (error, response) {
        console.log('app: oauth2_login ERROR: ' + response.text + " AuthenticateUser anyways to allow access to App as of right now.");
        //Take user to Home if an error with LinkedIn + Temp assign access
        authenticatedUser = 1;
        homeScreen();
    });
}

感谢任何帮助!

编辑:Linkedlin已正确完成,代码几乎完全相同!

function makeAPICalls(token) {
$.ajax(
    {
        //url: 'https://api.linkedin.com/v1/people/~?format=json',
        url: 'https://api.linkedin.com/v1/people/~:(id,first-name,last-name,picture-urls::(original),headline,industry,num-connections,location,summary,specialties,site-standard-profile-request,api-standard-profile-request,public-profile-url,picture-url,positions:(id,title,summary,start-date,end-date,is-current,company:(id,name,type,size,industry,ticker)),educations:(id,school-name,field-of-study,start-date,end-date,degree,activities,notes))?format=json',
        beforeSend: function (xhr) {
            xhr.setRequestHeader('authorization', 'Bearer ' + token);
        },
        success: function (linkedInData) {
            if (linkedInData != null) {

                console.log('app: makeAPICalls LinkedInData: ' + JSON.stringify(linkedInData) + " token: " + token);
                vsetaService.saveLinkedInData(linkedInData, token);

                checkUserStatus();
            }
        },
        error: function (error) {
            console.log("app: makeAPICalls: error:setting authenticatedUser to Yes and skip registration." + JSON.stringify(error));

            //navigator.notification.confirm('Unable to connect to LinkedIn at this time.', confirmCallback, "VSETA - Think Material", ["Ok"]);
            //Take user to Home if an error with LinkedIn + Temp assign access
            authenticatedUser = 1;
            homeScreen();
        }
    });
}

我在想它可能是网址。有什么建议吗?

1 个答案:

答案 0 :(得分:0)

我认为问题可能是图片{url}

如果您需要其个人资料照片的网址,

photoURL = "http://graph.facebook.com/" + response.id + "/picture";

修改

好吧,如果那不是我,我会告诉你我如何去做你想做的事情。

使用facebook的SDK。这种方式比使用Ajax更容易。

//1
//This initializes the SDK
FB.init({
  appId      : 'your app id goes here',
  cookie     : true,  // enable cookies to allow the server to access 
                    // the session
  xfbml      : true,  // parse social plugins on this page
  version    : 'v2.6' // use graph api version 2.6
});

//2
//This loads the SDK
(function(d, s, id) {
   var js, fjs = d.getElementsByTagName(s)[0];
   if (d.getElementById(id)) return;
   js = d.createElement(s); js.id = id;
   js.src = "//connect.facebook.net/en_US/sdk.js";
   fjs.parentNode.insertBefore(js, fjs);
 }(document, 'script', 'facebook-jssdk'));

//3
//This is the login button
<fb:login-button scope="public_profile,email" onlogin="facebookDoAThing();" data-max-rows="1" data-size="large" data-show-faces="true" data-auto-logout-link="true"></fb:login-button>

//4
//This function gets called by the button, then calls the next couple of functions
function facebookDoAThing() {
  FB.getLoginStatus(function(response) {
    statusChangeCallback(response);
  });
}

//5
//This checks that they authorized your app
function statusChangeCallback(response) {
  if (response.status === 'connected') {
    // logged into facebook and gave your app access to their account
    getInfoAndSuch(response);   
  }
}

//6
//This is where you grab their info
function getInfoAndSuch(response){
  authType = "facebook";
  authId = response.authResponse.userID; //For the api call
  // This is the SDK's api call syntax.
  FB.api('/' + authId + '?fields=id,first_name,last_name,email,permissions',
    function(response) {
            firstName = response.first_name; //grabs first name
            lastName = response.last_name; //grabs last name
            email = response.email; //grabs email       
            photoURL = "http://graph.facebook.com/" + response.id + "/picture"; //Grabs photo url, probably an easier way to do this    
    });
    //This removes your app from their account if you want that
    FB.api("/me/permissions", "delete", function(response){});

那个流程应该能够实现你想要的。