Facebook Graph API - 如何获取用户所在国家/地区?

发布于 2024-10-19 17:18:59 字数 213 浏览 2 评论 0 原文

我正在使用他们的 Graph API 开发 Facebook 应用程序。我之前使用已弃用的 REST API 开发了一个应用程序。

我遇到一个问题,因为我无法检索用户的国家/地区,只能检索他们的“位置” - 这只是城市和州/地区的组合格式(例如“德克萨斯州休斯顿”)。

如何使用 Graph API 检索用户的国家/地区?如果这不能直接实现,那么可能有哪些解决方法来实现这一目标?

I'm developing a Facebook application using their Graph API. I have previously developed an app using the deprecated REST API.

I've come across a problem in that I can't retrieve the user's country, only their 'location' - which is just the city and state / region in a combined format (such as 'Houston, Texas').

How is it possible to retrieve the user's country using the Graph API? If this isn't directly possible, what workarounds might there be to achieve this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(10

神妖 2024-10-26 17:18:59

https://api.facebook.com/method/fql.query?format=json&query=SELECT%20current_location%20FROM%20user%20WHERE%20uid=4&access_token=

[
  {
    "current_location": {
      "city": "Palo Alto",
      "state": "California",
      "country": "United States",
      "zip": "",
      "latitude": 37.4441,
      "longitude": -122.163,
      "id": 104022926303756,
      "name": "Palo Alto, California"
    }
  }
]

FQL 文档

https://api.facebook.com/method/fql.query?format=json&query=SELECT%20current_location%20FROM%20user%20WHERE%20uid=4&access_token=<ACCESS_TOKEN>

[
  {
    "current_location": {
      "city": "Palo Alto",
      "state": "California",
      "country": "United States",
      "zip": "",
      "latitude": 37.4441,
      "longitude": -122.163,
      "id": 104022926303756,
      "name": "Palo Alto, California"
    }
  }
]

FQL Documentation

柠北森屋 2024-10-26 17:18:59

我发现的一个解决方案(只是一种解决方法)是使用 GeoNames API - http: //www.geonames.org/export/web-services.html

使用类似的内容:

http://api.geonames.org/search?q=houston%2C%20texas&featureClass=P&username=myusername

返回 xml 对象中的结果,其中国家/地区作为数据的一部分。

然而,我对此解决方案并不是特别满意,因为它给我的应用程序增加了不必要的复杂性 - 而且对此免费服务的请求限制为每小时 2000 个,每天 30,000 个。

One solution I have found, which is merely a workaround, is to use the GeoNames API - http://www.geonames.org/export/web-services.html

Using something like:

http://api.geonames.org/search?q=houston%2C%20texas&featureClass=P&username=myusername

Returns results in an xml object, with the country as part of the data.

I'm not particularly happy with this as a solution however, as it adds an unnecessary layer of complications on to my application - plus requests to this free services are limited to 2000 per hour and 30,000 per day.

救赎№ 2024-10-26 17:18:59

使用php sdk:

需要
'facebook.php';

$facebook = 新
Facebook(数组('appId'=>;
'APPID', '秘密' =>
'应用程序秘密',
'cookie'=>正确,));

然后要求签署请求:

 $signed_request = $facebook->getSignedRequest();
  $country = $signed_request["用户"]["国家"];

现在 $country 有一个字符串,例如“us”代表美国,“uk”代表英国等。

Use the php sdk:

require
'facebook.php';

$facebook = new
Facebook(array( 'appId' =>
'APPID', 'secret' =>
'APPSECRET',
'cookie' => true, ));

Then ask for a signed request:

  $signed_request = $facebook->getSignedRequest();
  $country = $signed_request["user"]["country"];

Now $country has a string such as "us" for United States and "uk" for United Kingdom etc.

离去的眼神 2024-10-26 17:18:59

这是一个好问题。

问题是,任何在 facebook 下运行的应用程序都必须经过 facebook 服务器 - fb 代理,因此您获得的 IP 不是访问者的 IP,而是 facebook 服务器的 IP,而这是没有用的。

我还没有看到任何解决方案,除了从用户的个人资料中获取用户的国家/地区,这只有在用户公开或授权其权限时才可能实现。

这是您可能也想查看的有用链接:

That is a good question.

The problem is that any application run under facebook has to go through facebook servers - fb proxy and because of this the IP you get is not that of visitors but facebook's servers' instead which is of no use.

I have not seen any solution for this yet except for getting user's country from his profile which again is only possible if user had made it public or authorized the permission for it.

Here is useful link you might want to check out there too:

茶花眉 2024-10-26 17:18:59

你应该这样尝试:

/* make the API call */
[[FBRequest requestForMe] startWithCompletionHandler:^(FBRequestConnection *connection,
                                                           NSDictionary<FBGraphUser> *user,
                                                           NSError *error)
    {
        if (!error)
        {
            self.countryName    = [[[user objectForKey:@"location"] valueForKey:@"name"] componentsSeparatedByString:@", "][1];
            self.countryCode    = [self getCountryCodeForCountry:STUser.countryName];
        }
}];

-(NSString *)getCountryCodeForCountry:(NSString*)country
{
    NSMutableArray *countries = [self getCountries];
    NSArray *countryCodes = [NSLocale ISOCountryCodes];

    NSDictionary *codeForCountryDictionary = [[NSDictionary alloc] initWithObjects:countryCodes forKeys:countries];

    return [codeForCountryDictionary objectForKey:country];
}

+(NSMutableArray *)getCountries
{
    NSMutableArray *countries = [NSMutableArray array];

    NSArray *countryCodes = [NSLocale ISOCountryCodes];
    countries = [NSMutableArray arrayWithCapacity:[countryCodes count]];

    for (NSString *countryCode in countryCodes)
    {
        NSString *identifier = [NSLocale localeIdentifierFromComponents:[NSDictionary dictionaryWithObject: countryCode forKey: NSLocaleCountryCode]];
        NSString *country = [[NSLocale currentLocale] displayNameForKey: NSLocaleIdentifier value: identifier];
        [countries addObject: country];
    }

    return countries;
}

You should try like this:

/* make the API call */
[[FBRequest requestForMe] startWithCompletionHandler:^(FBRequestConnection *connection,
                                                           NSDictionary<FBGraphUser> *user,
                                                           NSError *error)
    {
        if (!error)
        {
            self.countryName    = [[[user objectForKey:@"location"] valueForKey:@"name"] componentsSeparatedByString:@", "][1];
            self.countryCode    = [self getCountryCodeForCountry:STUser.countryName];
        }
}];

-(NSString *)getCountryCodeForCountry:(NSString*)country
{
    NSMutableArray *countries = [self getCountries];
    NSArray *countryCodes = [NSLocale ISOCountryCodes];

    NSDictionary *codeForCountryDictionary = [[NSDictionary alloc] initWithObjects:countryCodes forKeys:countries];

    return [codeForCountryDictionary objectForKey:country];
}

+(NSMutableArray *)getCountries
{
    NSMutableArray *countries = [NSMutableArray array];

    NSArray *countryCodes = [NSLocale ISOCountryCodes];
    countries = [NSMutableArray arrayWithCapacity:[countryCodes count]];

    for (NSString *countryCode in countryCodes)
    {
        NSString *identifier = [NSLocale localeIdentifierFromComponents:[NSDictionary dictionaryWithObject: countryCode forKey: NSLocaleCountryCode]];
        NSString *country = [[NSLocale currentLocale] displayNameForKey: NSLocaleIdentifier value: identifier];
        [countries addObject: country];
    }

    return countries;
}
獨角戲 2024-10-26 17:18:59

使用官方 Facebook Graph API /me?fields=hometown 它将返回您,例如“布拉格,捷克共和国”

我相信你可以用针把字符串炸开','最后一个元素应该是国家

use the official Facebook Graph API /me?fields=hometown it will return you e.g. "Prague, Czech Republic"

I believe you can explode the string by needle ',' and the last element should be the country

地狱即天堂 2024-10-26 17:18:59

对于 iframe 应用程序,FB 服务器不会隐藏 ip,这意味着您可以进行 ip 地址查找

http://phpweby.com /software/ip2country

该脚本对我来说有点错误,但完成了工作。

for iframe apps, then ip is not hidden by FB servers, meaning you can do ip address lookup

http://phpweby.com/software/ip2country

the script was a bit buggy for me but did the job.

稀香 2024-10-26 17:18:59

根据Facebook的文档,您可以获得2个字母的ISO 3166-1 来自用户区域设置的国家/地区代码。

Facebook 区域设置分别遵循 ISO 语言和国家/地区代码,
用下划线连接。基本格式是“ll_CC”,其中
''ll'' 是两个字母的语言代码,''CC'' 是两个字母的语言代码
国家代码。例如,“en_US”代表美国英语。

FQL 示例:

SELECT locale FROM user WHERE uid = me()

响应:

{
  "data": [
    {
      "locale": "en_US"
    }
  ]
}

According to Facebook's documentation, you can get the 2-letter ISO 3166-1 country code from the user's locale.

Facebook locales follow ISO language and country codes respectively,
concatenated by an underscore. The basic format is ''ll_CC'', where
''ll'' is a two-letter language code, and ''CC'' is a two-letter
country code. For instance, 'en_US' represents US English.

Example FQL:

SELECT locale FROM user WHERE uid = me()

Response:

{
  "data": [
    {
      "locale": "en_US"
    }
  ]
}
莳間冲淡了誓言ζ 2024-10-26 17:18:59

您可以使用 FQL 查询按国家/地区查看终生关注者数量(通过对您的 FB 页面的点赞)。使用标记化会话值设置 JSON 查询,并通过 PHP 发送 FQL 查询,其中包含您要定位的页面的 object_ID 和生命周期。选择指标,并将指标设置为 page_fans_country - 并将数据转储到 CSV 文件中。您应该按国家/地区代码(多行)返回终生关注者总数(按喜欢)的列表。设置数据透视表以获取跨多个数据页的聚合索引,并按国家/地区代码排名。以下是 FQL 查询的示例:

SELECT metric, value FROM Insights WHERE object_id=[your page ID gone here] AND metric='page_fans_country' AND end_time=end_time_date('2013-04-28') AND period=period('lifetime' )

You can see the lifetime number of followers (by likes to your FB page) by country using an FQL query. Set up a JSON query using the tokenized session value, and send an FQL query through via PHP with the object_ID of the page you are targeting and period of lifetime. select metric, and set the metric to page_fans_country - and dump the data into a CSV file. You should get back a list of total lifetime followers (by likes) by country code (multiple rows). Setup a pivot table to get an aggregated index across multiple pages of data, and rank by country code. Here's example of the FQL query:

SELECT metric, value FROM insights WHERE object_id=[your page ID goes here] AND metric='page_fans_country' AND end_time=end_time_date('2013-04-28') AND period=period('lifetime')

谷夏 2024-10-26 17:18:59

Valerchik 发布的答案确实是正确的,但万一有人会寻找 PHP 解决方案,那么我最终得到了一些东西像这样:

$token = Yii::app()->facebook->getAccessToken();
$fqlRequest = 'https://api.facebook.com/method/fql.query?query=' .
              'SELECT%20' . $fqlAttributeName . '%20FROM%20user%20WHERE%20' .
                    'uid=' . $fbUserId . '&access_token=' . $token;
$ret = file_get_contents($fqlRequest);

if (!empty($ret)) {
    ...

所有用户属性的列表可以在这里找到:
https://developers.facebook.com/docs/reference/fql/user/< /a>

我希望它能帮助别人:)

Answer posted by Valerchik is the right one indeed, but in case someone would look for PHP solution, then I ended up with something like this:

$token = Yii::app()->facebook->getAccessToken();
$fqlRequest = 'https://api.facebook.com/method/fql.query?query=' .
              'SELECT%20' . $fqlAttributeName . '%20FROM%20user%20WHERE%20' .
                    'uid=' . $fbUserId . '&access_token=' . $token;
$ret = file_get_contents($fqlRequest);

if (!empty($ret)) {
    ...

List of all user's attributes can be found here:
https://developers.facebook.com/docs/reference/fql/user/

I hope it will help someone :)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文