ChatGPT解决这个技术问题 Extra ChatGPT

How to get the Facebook user id using the access token

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:

I send the user to https://graph.facebook.com/oauth/authorize with all required extended permissions. In my redirect page I get the code from Facebook. 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?


s
serg

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=...

I tried the exact call above: just returns: {"success":true}
This doesn't return id anymore. Use: https://graph.facebook.com/me?fields=id&access_token=xxxxxx
What is the 'access_token'? I tried using the page access token and the user access token. I get 'invalid token' responses using this.
@Ant u need to implement FaceBook Login for getting access token
How can I fetch/get the username. I am using passport-facebook with nodsjs. My scopes are: ['public_profile','user_gender','user_managed_groups','pages_show_list','email'] And, while calling passport-facebook, profile-fields are: profileFields: ['id','name','email','gender','birthday','displayName','picture.type(large)'] Any idea, how can I get username? (Just for ref: if profile is facebook.com/charels.woodson, then I want "charels.woodson")
p
pashaplus

The easiest way is

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

then you will get json response which contains only userid.


{ "error": { "message": "(#100) Unknown fields: userid.", "type": "OAuthException", "code": 100 } }
@NikolayKuznetsov: sorry man,in overlook instead of id i wrote userid, i edited now,please try again
No problem, I have already tried it, so I post my previous comment.
I am getting the following error My access token is active. { "error": { "message": "An active access token must be used to query information about the current user.", "type": "OAuthException", "code": 2500, "fbtrace_id": "HA0UNBRymfa" } }
what is the access token and where to get it from
s
sakibmoon

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

It works perfectly before, but after Facebook update to the OAuth2.0. This method cannot work anymore.
I wish I had heeded the warning about this approach. We got caught with our pants down today as out of the blue the format of the access tokens seems to have changed. I highly recommend avoiding this approach and going with the accepted answer.
thats the most funny answer i ever seen :D
Also note that methods like this don't verify the given user ID - anybody could splice in whatever id they want and this code would blindly trust it.
S
SkyWalker

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.


Im getting only provider_id and name from that, But im not getting username from facebook. Like link, This is the username which will directly open users profile, with provider id it is not working.
A
AndrewSmiley

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

I got the idea, but it does not return userID only the token.
Keep in mind this answer is 2 years old. They may have changed some parts of the SDK
G
Gia Dang

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


c
chavy

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