使用移动应用程序中的Facebook Graph API
-
14-10-2019 - |
题
我有一个小 纸牌游戏 在Facebook(和少数俄罗斯社交网络),通过旧的REST API获取用户的ID,名字和头像。
现在我试图开发与使用移动应用程序相同的游戏 柔性 英雄SDK用于Android和iPhone。这意味着我不能将本机SDK用于这些平台,但必须使用 Oauth在Facebook页面上呈现.
我正在尝试编写一个简短的PHP脚本,该脚本会将用户信息返回我的移动应用程序。我的脚本已经可以得到令牌:
<?php
define('FB_API_ID', 'XXX');
define('FB_AUTH_SECRET', 'XXX');
$code = @$_GET['code'];
# this is just a link for me, for development puposes
if (!isset($code)) {
$str = 'https://graph.facebook.com/oauth/authorize?client_id=' . FB_API_ID .
'&redirect_uri=http://preferans.de/facebook/mobile.php&display=touch';
print "<html><body><a href=\"$str\">$str</a></body></html>";
exit();
}
$req = 'https://graph.facebook.com/oauth/access_token?client_id=' . FB_API_ID .
'&redirect_uri=http://preferans.de/facebook/mobile.php&client_secret=' . FB_AUTH_SECRET .
'&code=' . $code;
$ch = curl_init($req);
curl_setopt($ch, CURLOPT_HEADER, FALSE);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$page = curl_exec($ch);
if (curl_errno($ch))
exit('Download failed');
curl_close($ch);
parse_str($page, $data);
#header('Content-Type: text/xml; charset=utf-8');
#print('<?xml version="1.0"? ><app>');
print_r($data);
#print('</app>');
?>
这效果很好,我恢复了令牌:
Array
(
[access_token] => 262578703638|2.OwBuoa2fT5Zp_yo2hFUadA__.3600.1294904800-587287941|ycUNaHVxa_8mvenB9JB1FH3DcAA
[expires] => 6697
)
但是,我现在如何使用这个令牌来查找用户的名称和头像,尤其是我对当前用户ID的了解感到困惑?
在使用REST API时,我一直通过调用当前用户ID $userid=$fb->require_login()
解决方案
请参阅文档: http://developers.facebook.com/docs/api
使用卷曲来要求: https://graph.facebook.com/me/?access_token=xxxxxxx
“/我”将为您提供所需的所有信息。
$req = 'https://graph.facebook.com/me/?access_token=' . $access_token;
$ch = curl_init($req);
curl_setopt($ch, CURLOPT_HEADER, FALSE);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$page = curl_exec($ch);
if (curl_errno($ch))
exit('Download failed');
curl_close($ch);
$user_object = json_decode($page);
var_dump($user_object);
会返回类似的东西:
object(stdClass)#1 (20) {
["id"]=>
string(10) "1017193642"
["name"]=>
string(19) "Lance Scott Rushing"
["first_name"]=>
string(5) "Lance"
["middle_name"]=>
string(5) "Scott"
["last_name"]=>
string(7) "Rushing"
["link"]=>
string(36) "http://www.facebook.com/LanceRushing"
.....
其他提示
由于我无法添加评论,我会在这里回答。
为了获取个人资料图片,您需要请求 https://graph.facebook.com/ID/picture
. 。如果您只需要特定字段,则可以这样指定: https://graph.facebook.com/ID?fields=uid,name,etc&access_token=token
另外,您可以使用PHP SDK授权和登录用户,以便您不必手动获取令牌 - 它可以简化您的代码。例如,您可以做的不是每个卷曲的请求 $facebook->api(request);
一个很好的描述和例子在这里 http://apps.facebook.com/graphapidemo/.