我正在建立表单,并希望通过例如获取“ 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 - 接收Userobject但每个条目都为空(facebook restfb),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57509470/