【问题标题】:How to get username from Facebook ID如何从 Facebook ID 获取用户名
【发布时间】:2014-10-30 00:28:04
【问题描述】:

网上有一些关于这个问题的话题,但我没有找到任何复杂的解决方案。因此,我想请您帮忙。

我需要将 facebook id 更改为用户名。

当你像这样键入网站时:

http://facebook.com/profile.php?id=4(数字 4 是 FB id),它会给你http://www.facebook.com/zuck,这是马克扎克伯格的个人资料。

根据这个原则,我需要找出 id 是谁。

我输入了 id 4 得到它是 zuck

但是我需要它来获得更多的 id,所以手动完成会花费很多时间。请帮助我,我该怎么做。

【问题讨论】:

标签: php facebook facebook-graph-api


【解决方案1】:

如果您已经拥有该特定用户的 ID,则只需将其添加到此 url:

https://graph.facebook.com/<USER_ID>

简单示例:

function get_basic_info($id) {
    $url = 'https://graph.facebook.com/' . $id;
    $info = json_decode(file_get_contents($url), true);
    return $info;
}

$id = 4;
$user = get_basic_info($id);
echo '<pre>';
print_r($user);

这应该基本上产生:

Array
(
    [id] => 4
    [first_name] => Mark
    [gender] => male
    [last_name] => Zuckerberg
    [link] => https://www.facebook.com/zuck
    [locale] => en_US
    [name] => Mark Zuckerberg
    [username] => zuck
)

然后你可以像普通数组一样调用它:

echo $user['username'];

旁注:为什么不改用 PHP SDK。

https://developers.facebook.com/docs/reference/php/4.0.0

【讨论】:

  • 当 API v1.0 被移除时,它将在 2015 年 4 月 30 日停止工作
  • php sdk 对于这么简单的任务来说太重了,恕我直言。但答案是正确的,所以为你 +1 :)
  • @luschn 是的,这也很好,对于这样一个简单的意图可能很麻烦
  • @Andrew 很高兴这有帮助
  • 用户名字段现在不再可用
【解决方案2】:

由于 Graph API 端点 /user-id 不再提供用户名,正如 here 所讨论的那样,我在这里提出了另一种解决方法(但使用 Python 代码)

简而言之,我们打开 fb.com/USER_ID 的页面并从中获取用户名

#get html of a page via pure python ref. https://stackoverflow.com/a/23565355/248616
import requests
r = requests.get('http://fb.com/%s' % FB_USER_ID) #open profile page of the facebook user
r.raise_for_status()
html = r.content

#search string with regex ref. https://stackoverflow.com/a/4667014/248616
import re
# m = re.search('meta http-equiv="refresh" content="0; URL=/([^?]+)\?', html)
m = re.search('a class="profileLink" href="([^"]+)"', html)
href = m.group(1) #will be https://www.facebook.com/$FB_USER_NAME on 201705.24
username = href.split('/')[-1]
print(href)
print(username)

【讨论】:

  • Facebook 上不允许抓取,不要那样做。无论如何,您不再需要真实 ID 或用户名。
  • @luschn 我的应用需要为 FB 用户创建个人资料 URL 链接……这对我来说似乎是一个真实的用例。
  • “我的应用需要它”不是用例 ;) - 为什么你的应用需要它?为什么人们需要在您的应用程序中访问 facebook 的个人资料网址? - 顺便说一句,api参考说有一个用户的“链接”字段。你试过吗?
  • @luschn 链接字段我想也已弃用?
  • 我不确定,我只是使用已探索的图形 API 尝试过,但没有获得用户个人资料链接
【解决方案3】:

截至 2019 年 10 月,唯一可能的方法是在请求和权限中请求 user_links

然后在一个作用域中传递它,像这样

scope: ['user_link'] 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-05-28
    • 2014-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-09
    • 2018-07-04
    相关资源
    最近更新 更多