我有一个 Facebook 桌面应用程序并且正在使用 Graph API。我能够获得访问令牌,但完成之后 - 我不知道如何获取用户的 ID。
我的流程是这样的:
我使用所有必需的扩展权限将用户发送到 https://graph.facebook.com/oauth/authorize。在我的重定向页面中,我从 Facebook 获取代码。然后我使用我的 API 密钥对 graph.facebook.com/oauth/access_token 执行 HTTP 请求,并在响应中获得访问令牌。
从那时起,我无法获得用户 ID。
如何解决这个问题?
如果您想使用 Graph API 来获取当前用户 ID,那么只需发送请求到:
https://graph.facebook.com/me?access_token=...
最简单的方法是
https://graph.facebook.com/me?fields=id&access_token="xxxxx"
然后你会得到只包含用户 ID 的 json 响应。
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;
}
您可以在 onSuccess(LoginResult loginResult) 上使用以下代码
loginResult.getAccessToken().getUserId();
你只需要点击另一个 Graph API:
https://graph.facebook.com/me?access_token={access-token}
它还会提供您的电子邮件 ID 和用户 ID(对于 Facebook)。
使用最新的 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"]);
在 FacebookSDK v2.1 中(我无法检查旧版本)。我们有
NSString *currentUserFBID = [FBSession activeSession].accessTokenData.userID;
但是根据 FacebookSDK 中的评论
@discussion 这可能不会为 iOS 系统帐户等登录行为填充。
所以可能你应该检查它是否可用,然后是否使用它,或者调用请求来获取用户 ID
查看此 answer,其中描述了如何获取 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);
});
不定期副业成功案例分享
https://graph.facebook.com/me?fields=id&access_token=xxxxxx