如何使用访问令牌获得 Facebook 用户 ID

我有一个 Facebook 桌面应用程序,正在使用 图表 API。 我能够获得访问令牌,但是在这之后,我不知道如何获得用户的 ID。

我的流程是这样的:

  1. 我将用户发送到具有所有必需的扩展权限的 翻译: 奇芳翻译: 奇芳翻译: 奇芳翻译: 奇芳翻译: 奇芳翻译: 奇芳翻译: 奇芳翻译: 奇芳翻译: 奇芳翻译: 奇芳翻译: 奇芳翻译: 奇芳翻译: 奇芳翻译: 奇芳 https://graph.facebook.com/oauth/authorize

  2. 在我的重定向页面中,我从 Facebook 获得了代码。

  3. 然后,我使用 API 密钥对 Graph.facebook.com/oauth/access_token执行 HTTP 请求,并在响应中获得访问令牌。

从那时起,我就无法得到用户 ID 了。

这个问题如何解决?

170601 次浏览

If you want to use Graph API to get current user ID then just send a request to:

https://graph.facebook.com/me?access_token=...

The facebook acess token looks similar too "1249203702|2.h1MTNeLqcLqw__.86400.129394400-605430316|-WE1iH_CV-afTgyhDPc"

if you extract the middle part by using | to split you get

2.h1MTNeLqcLqw__.86400.129394400-605430316

then split again by -

the last part 605430316 is the user id.

Here is the C# code to extract the user id from the access token:

   public long ParseUserIdFromAccessToken(string accessToken)
{
Contract.Requires(!string.isNullOrEmpty(accessToken);


/*
* access_token:
*   1249203702|2.h1MTNeLqcLqw__.86400.129394400-605430316|-WE1iH_CV-afTgyhDPc
*                                               |_______|
*                                                   |
*                                                user id
*/


long userId = 0;


var accessTokenParts = accessToken.Split('|');


if (accessTokenParts.Length == 3)
{
var idPart = accessTokenParts[1];
if (!string.IsNullOrEmpty(idPart))
{
var index = idPart.LastIndexOf('-');
if (index >= 0)
{
string id = idPart.Substring(index + 1);
if (!string.IsNullOrEmpty(id))
{
return id;
}
}
}
}


return null;
}

The structure of the access token is undocumented and may not always fit the pattern above. Use it at your own risk.

Update Due to changes in Facebook. the preferred method to get userid from the encrypted access token is as follows:

try
{
var fb = new FacebookClient(accessToken);
var result = (IDictionary<string, object>)fb.Get("/me?fields=id");
return (string)result["id"];
}
catch (FacebookOAuthException)
{
return null;
}

The easiest way is

https://graph.facebook.com/me?fields=id&access_token="xxxxx"

then you will get json response which contains only userid.

in FacebookSDK v2.1 (I can't check older version). We have

NSString *currentUserFBID = [FBSession activeSession].accessTokenData.userID;

However according to the comment in FacebookSDK

@discussion This may not be populated for login behaviours such as the iOS system account.

So may be you should check if it is available, and then whether use it, or call the request to get the user id

With the newest API, here's the code I used for it

/*params*/
NSDictionary *params = @{
@"access_token": [[FBSDKAccessToken currentAccessToken] tokenString],
@"fields": @"id"
};
/* make the API call */
FBSDKGraphRequest *request = [[FBSDKGraphRequest alloc]
initWithGraphPath:@"me"
parameters:params
HTTPMethod:@"GET"];


[request startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection,
id result,
NSError *error) {
NSDictionary *res = result;
//res is a dict that has the key
NSLog([res objectForKey:@"id"]);

You can use below code on onSuccess(LoginResult loginResult)

loginResult.getAccessToken().getUserId();

You just have to hit another Graph API:

https://graph.facebook.com/me?access_token={access-token}

It will give your e-mail Id and user Id (for Facebook) also.

Check out this answer, which describes, how to get ID response. First, you need to create method get data:

const https = require('https');
getFbData = (accessToken, apiPath, callback) => {
const options = {
host: 'graph.facebook.com',
port: 443,
path: `${apiPath}access_token=${accessToken}`, // apiPath example: '/me/friends'
method: 'GET'
};


let buffer = ''; // this buffer will be populated with the chunks of the data received from facebook
const request = https.get(options, (result) => {
result.setEncoding('utf8');
result.on('data', (chunk) => {
buffer += chunk;
});


result.on('end', () => {
callback(buffer);
});
});


request.on('error', (e) => {
console.log(`error from facebook.getFbData: ${e.message}`)
});


request.end();
}

Then simply use your method whenever you want, like this:

getFbData(access_token, '/me?fields=id&', (result) => {
console.log(result);
});