97

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?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Mohoch
  • 2,633
  • 1
  • 26
  • 26

8 Answers8

165

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=...
serg
  • 109,619
  • 77
  • 317
  • 330
  • 1
    I tried the exact call above: just returns: {"success":true} – Paul Kenjora Aug 04 '16 at 18:56
  • 5
    This doesn't return id anymore. Use: `https://graph.facebook.com/me?fields=id&access_token=xxxxxx` – M3RS Jan 12 '19 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 Feb 07 '20 at 12:40
  • @Ant u need to implement [FaceBook Login](https://developers.facebook.com/docs/facebook-login) for getting access token – Zeeshan Ahmad Khalil Jan 08 '21 at 07: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 https://www.facebook.com/charels.woodson, then I want "charels.woodson") – Shivam Verma May 06 '21 at 14:00
  • `curl -i -H 'Authorization: Bearer ' https://graph.facebook.com/me?fields=id` cc @serg The query parameter can't be used anymore. – Ivan Black Jul 09 '21 at 02:04
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.

pashaplus
  • 3,596
  • 2
  • 26
  • 25
  • 2
    { "error": { "message": "(#100) Unknown fields: userid.", "type": "OAuthException", "code": 100 } } – Nikolay Kuznetsov Oct 24 '12 at 05:30
  • 1
    @NikolayKuznetsov: sorry man,in overlook instead of *id* i wrote *userid*, i edited now,please try again – pashaplus Oct 24 '12 at 09:02
  • 1
    No problem, I have already tried it, so I post my previous comment. – Nikolay Kuznetsov Oct 24 '12 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 Feb 23 '18 at 04:57
  • what is the access token and where to get it from – Masroor Oct 01 '20 at 11:39
  • 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 https://www.facebook.com/charels.woodson, then I want "charels.woodson") – Shivam Verma May 06 '21 at 14:03
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;
}
sakibmoon
  • 2,026
  • 3
  • 22
  • 32
prabir
  • 7,674
  • 4
  • 31
  • 43
  • 5
    It works perfectly before, but after Facebook update to the OAuth2.0. This method cannot work anymore. – lucemia Sep 28 '11 at 09: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. – Todd Menier Oct 11 '11 at 20:33
  • 2
    thats the most funny answer i ever seen :D – khunshan Mar 02 '15 at 09: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. – Matt Lyons-Wood Aug 20 '15 at 09:42
7

You can use below code on onSuccess(LoginResult loginResult)

loginResult.getAccessToken().getUserId();

SkyWalker
  • 855
  • 2
  • 14
  • 36
6

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](https://www.facebook.com/ssalmanriyaz), This is the username which will directly open users profile, with provider id it is not working. – Salman Riyaz Jun 29 '18 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"]);
AndrewSmiley
  • 1,933
  • 20
  • 32
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

Gia Dang
  • 164
  • 3
  • 8
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);
});
chavy
  • 841
  • 10
  • 20