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

发布于 2024-09-15 09:51:29 字数 552 浏览 5 评论 0原文

我有一个 Facebook 桌面应用程序,并且正在使用 Graph API。 我能够获取访问令牌,但完成后 - 我不知道如何获取用户的 ID。

我的流程是这样的:

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

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

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

从那时起我就无法获取用户 ID。

如何解决这个问题呢?

I have a Facebook desktop application and am using the Graph API.
I am able to get the access token, but after that is done - I don't know how to get the user's ID.

My flow is like this:

  1. I send the user to https://graph.facebook.com/oauth/authorize with all required extended permissions.

  2. In my redirect page I get the code from Facebook.

  3. Then I perform a HTTP request to graph.facebook.com/oauth/access_token with my API key and I get the access token in the response.

From that point on I can't get the user ID.

How can this problem be solved?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

谜兔 2024-09-22 09:51:29

如果您想使用 Graph API 获取当前用户 ID,只需发送请求至:

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

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=...
一指流沙 2024-09-22 09:51:29

最简单的方法是

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

您将获得仅包含 userid 的 json 响应。

The easiest way is

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

then you will get json response which contains only userid.

爱你不解释 2024-09-22 09:51:29

facebook 访问令牌看起来也很相似
则为“1249203702|2.h1MTNeLqcLqw__.86400.129394400-605430316|-WE1iH_CV-afTgyhDPc”

如果使用 | 提取中间部分, 分割你得到

2.h1MTNeLqcLqw__.86400.129394400-605430316

然后再次分割 -

最后一部分 605430316 是用户 ID。

以下是从访问令牌中提取用户 ID 的 C# 代码:

   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;
    }

警告:
访问令牌的结构没有记录,并且可能并不总是符合上述模式。使用它的风险由您自行承担。

更新
由于 Facebook 的变化。
从加密的访问令牌获取用户 ID 的首选方法如下:

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 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;
    }

WARNING:
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;
}
埋情葬爱 2024-09-22 09:51:29

您可以在 onSuccess(LoginResult loginResult) 上使用以下代码

loginResult.getAccessToken().getUserId();

You can use below code on onSuccess(LoginResult loginResult)

loginResult.getAccessToken().getUserId();

萧瑟寒风 2024-09-22 09:51:29

您只需点击另一个 Graph API:

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

它也会提供您的电子邮件 ID 和用户 ID(对于 Facebook)。

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.

一直在等你来 2024-09-22 09:51:29

使用最新的 API,这是我使用的代码

/*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"]);

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"]);
尝蛊 2024-09-22 09:51:29

在 FacebookSDK v2.1 中(我无法检查旧版本)。但是

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

根据 FacebookSDK @discussion 中的评论,

这对于 iOS 系统帐户等登录行为可能不会填充。

所以也许你应该检查它是否可用,然后是否使用它,或者调用请求来获取用户 ID

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

无力看清 2024-09-22 09:51:29

查看这个答案,其中描述了如何获取 ID 响应。
首先,您需要创建方法获取数据:

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();
}

然后只需在需要时使用您的方法即可,如下所示:

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

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);
});
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文