99

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?

8 Answers 8

166

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=...
6
  • 1
    I tried the exact call above: just returns: {"success":true} Commented Aug 4, 2016 at 18:56
  • 5
    This doesn't return id anymore. Use: https://graph.facebook.com/me?fields=id&access_token=xxxxxx
    – M3RS
    Commented Jan 12, 2019 at 13:10
  • 2
    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
    Commented Feb 7, 2020 at 12:40
  • @Ant u need to implement FaceBook Login for getting access token Commented Jan 8, 2021 at 7:52
  • 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") Commented May 6, 2021 at 14:00
37

The easiest way is

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

then you will get json response which contains only userid.

6
  • 2
    { "error": { "message": "(#100) Unknown fields: userid.", "type": "OAuthException", "code": 100 } } Commented Oct 24, 2012 at 5:30
  • 1
    @NikolayKuznetsov: sorry man,in overlook instead of id i wrote userid, i edited now,please try again
    – pashaplus
    Commented Oct 24, 2012 at 9:02
  • 1
    No problem, I have already tried it, so I post my previous comment. Commented Oct 24, 2012 at 14:15
  • 2
    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" } }
    – Ajit Goel
    Commented Feb 23, 2018 at 4:57
  • what is the access token and where to get it from
    – Masroor
    Commented Oct 1, 2020 at 11:39
10

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;
}
4
  • 5
    It works perfectly before, but after Facebook update to the OAuth2.0. This method cannot work anymore.
    – lucemia
    Commented Sep 28, 2011 at 9:54
  • 12
    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. Commented Oct 11, 2011 at 20:33
  • 2
    thats the most funny answer i ever seen :D
    – khunshan
    Commented Mar 2, 2015 at 9:57
  • 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. Commented Aug 20, 2015 at 9:42
7

You can use below code on onSuccess(LoginResult loginResult)

loginResult.getAccessToken().getUserId();

7

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.

1
  • 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. Commented Jun 29, 2018 at 10:20
3

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"]);
2
  • I got the idea, but it does not return userID only the token.
    – János
    Commented May 31, 2017 at 22:44
  • Keep in mind this answer is 2 years old. They may have changed some parts of the SDK Commented Jun 2, 2017 at 14:27
2

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

0

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.