【问题标题】:Receive Userobject but every entry is null (facebook restfb)接收用户对象,但每个条目都是空的(facebook restfb)
【发布时间】:2019-12-21 21:11:45
【问题描述】:

我正在构建一个表单,并希望通过例如获取“first_name”和“last_name”等字段。 facebook 或 google 数据,但只接收一个对象,每个条目都是“null”

我尝试添加一个自定义 ScropeBuilder,获取不同的帐户。

我的应用程序仅将访问令牌提供给浏览器终端,因此我可以通过邮递员发送请求以获取我想要的数据。

令牌控制器:

package com.example.demo;

import com.restfb.DefaultFacebookClient;
import com.restfb.FacebookClient;
import com.restfb.Version;
import com.restfb.scope.FacebookPermissions;
import com.restfb.scope.ScopeBuilder;
import com.restfb.types.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.security.SecurityProperties;
import org.springframework.social.connect.ConnectionRepository;
import org.springframework.social.facebook.api.Facebook;
import org.springframework.social.facebook.api.FacebookProfile;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping(value="/tokencontroller")
public class TokenController {

    @Autowired
    Facebook facebook;
    @Autowired
    ConnectionRepository connectionRepository;



    @RequestMapping(value = "/userdata/{accessToken}", method = RequestMethod.POST)
    public UserModel userMod(@PathVariable(value = "accessToken") String accessToken) {

        UserModel userModel = new UserModel();

        ScopeBuilder scopeBuilder = new ScopeBuilder();
        scopeBuilder.addPermission(FacebookPermissions.PUBLIC_PROFILE);
            /*if(connectionRepository.findPrimaryConnection(Facebook.class) == null) {
                return null;
            }*/


        System.out.println("\n \n \n accesstoken: "+accessToken);
        FacebookClient fbClient = new DefaultFacebookClient(accessToken, Version.VERSION_4_0);
        User user = fbClient.fetchObject("me",User.class);
        System.out.println("User: "+user);
        System.out.println("Firstname: "+user.getFirstName());
        return userModel;
    }

    @RequestMapping(value = "/getURL")
    public void getUrl(){
        ScopeBuilder scopeBuilder = new ScopeBuilder();
        scopeBuilder.addPermission(FacebookPermissions.PUBLIC_PROFILE);

        FacebookClient client = new DefaultFacebookClient(Version.LATEST);
        String url = client.getLoginDialogUrl("502780177145376","/connect/facebook",scopeBuilder);

        System.out.println(url);
    }
}
```

facebookConnect.html
```HTML
<!DOCTYPE html >
<html>
<head>
    <title>Facebook Login JavaScript Example</title>
    <meta charset="UTF-8"/>
    <script src="scripts/facebookSDK.js"></script>
</head>
<body>
<h1>lala land</h1>
<!--
  Below we include the Login Button social plugin. This button uses
  the JavaScript SDK to present a graphical Login button that triggers
  the FB.login() function when clicked.
-->

<script>
    // This is called with the results from from FB.getLoginStatus().
    function statusChangeCallback(response) {
        console.log('statusChangeCallback');
        console.log(response);
        // The response object is returned with a status field that lets the
        // app know the current login status of the person.
        // Full docs on the response object can be found in the documentation
        // for FB.getLoginStatus().
        if (response.status === 'connected') {
            // Logged into your app and Facebook.
            testAPI();
        } else {
            // The person is not logged into your app or we are unable to tell.
            document.getElementById('status').innerHTML = 'Please log ' +
                'into this app.';
        }
    }

    // This function is called when someone finishes with the Login
    // Button.  See the onlogin handler attached to it in the sample
    // code below.
    function checkLoginState() {
        FB.getLoginStatus(function(response) {
            statusChangeCallback(response);
        });
    }

    window.fbAsyncInit = function() {
        FB.init({
            appId      : '502780177145376',
            cookie     : true,  // enable cookies to allow the server to access
                                // the session
            xfbml      : true,  // parse social plugins on this page
            version    : 'v4.0' // The Graph API version to use for the call
        });

        // Now that we've initialized the JavaScript SDK, we call
        // FB.getLoginStatus().  This function gets the state of the
        // person visiting this page and can return one of three states to
        // the callback you provide.  They can be:
        //
        // 1. Logged into your app ('connected')
        // 2. Logged into Facebook, but not your app ('not_authorized')
        // 3. Not logged into Facebook and can't tell if they are logged into
        //    your app or not.
        //
        // These three cases are handled in the callback function.

        FB.getLoginStatus(function(response) {
            statusChangeCallback(response);
        });

    };

    // Load the SDK asynchronously
    (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 = "https://connect.facebook.net/en_US/sdk.js";
        fjs.parentNode.insertBefore(js, fjs);
    }(document, 'script', 'facebook-jssdk'));


    // Here we run a very simple test of the Graph API after login is
    // successful.  See statusChangeCallback() for when this call is made.
    function testAPI() {
        console.log('Welcome!  Fetching your information.... ');
        FB.api('/me',{"fields":"first_name"}, function(response) {

            console.log('Successful login for: ' + response.name);
            document.getElementById('status').innerHTML =
                'Thanks for logging in, ' + response.name + '!';
        });
    }

    function login(){
        FB.login(function(response){
            console.log("\n Response: "+response.connectionState);
            try{
                if(response == 'connected')
                console.log("Connected: "+true);

            else{
                console.log("not connected");
                console.log("accesstoken: " + response.authResponse.accessToken);

            }}
            catch (e) {
                console.log(e);
                console.log("is nich");

            }
        });

    }
</script>

<button onclick="login()">Login Button</button>

<div id="status">
</div>

</body>
</html>
```


I expect the output to be:
```JSON
{
    "firstName": John,
    "lastName": Johnson,
    "address":  myAddress, 
    "birthDay": myBirthday,
    "email": myEmail,
    "gender": myGender
}
```

Actual output is:
```JSON
{
    "firstName": null,
    "lastName": null,
    "address": null,
    "birthDay": null,
    "email": null,
    "gender": null
}
```

When logging it in console there is no exception or error message, just:
```
accesstoken: EAAHJRqHb3iABAEyFblVBaOAaEjbsw8q4cNSQsQuFbSI40r3GZAAZBMe6e0VZCrNX1I8L16VZAeWVZALrws0AmcLFZCgcuJHyRB3briOYS7QKCm3T7fIi3WZBsAngtIpDlewm14ZCIq66FMtZB5ZChZBkNUciwcpJJ3f0ZAuvcYozEZANAZB3KIuY7KKmHdnaVj5vkSdL0NlgAnZBrBcsZAZBp6NZBeUygz

User: User[about=null ageRange=null bio=null birthday=null birthdayAsDate=null context=null cover=null currency=null devices=[] education=[] email=null favoriteAthletes=[] favoriteTeams=[] firstName=null gender=null hometown=null hometownName=null id=111826290166761 idsForApps=[] idsForBusiness=[] idsForPages=[] inspirationalPeople=[] installType=null installed=null interestedIn=[] invitableFriends=[] isSharedLogin=null isVerified=null labels=[] languages=[] lastName=null likes=null link=null locale=null location=null meetingFor=[] metadata=null middleName=null name=John Johnson nameFormat=null paymentPricepoints=null picture=null political=null publicKey=null quotes=null relationshipStatus=null religion=null securitySettings=null sharedLoginUpgradeRequiredBy=null shortName=null significantOther=null sports=[] testGroup=null thirdPartyId=null timezone=null tokenForBusiness=null type=null updatedTime=null username=null verified=null videoUploadLimits=null viewerCanSendGift=null website=null work=[]]

Firstname: null```

I don't get why it's not fetching the correct userdata.

May anyone can help me?


You can check it out at github if u want to: https://github.com/rosariop/FacebookSpringboottest2

【问题讨论】:

    标签: javascript java spring-boot spring-social restfb


    【解决方案1】:

    如果您想通过 access-token 获取用户详细信息,您需要生成具有适当配置的访问令牌,请参考以下屏幕

    生成访问令牌时需要包含所有特定信息

    【讨论】:

      【解决方案2】:

      您已指定需要哪些字段。

      所以这条线

      User user = fbClient.fetchObject("me",User.class);
      

      需要改成

      User user = fbClient.fetchObject("me",User.class, Parameter.with("fields","first_name,last_name"));
      

      字段参数被添加到查询中,您可以准确地获得所请求对象(和 ID)的这些字段。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-08-31
        • 2011-03-27
        • 1970-01-01
        • 1970-01-01
        • 2020-10-25
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多