【发布时间】:2018-11-14 12:32:56
【问题描述】:
我正在尝试从 PHP 脚本发布到 Facebook 墙上。我创建了一个 FB 应用程序,安装了 Graph PHP API,并实现了一些测试脚本,如下所示:
fbinit.php:
<?php
session_start();
require_once('src/Facebook/autoload.php');
$fb = new Facebook\Facebook([
'app_id' => 'REDACTED',
'app_secret' => 'REDACTED',
'default_graph_version' => 'v2.9',
]);
?>
fbpost.php:
<?php
include('fbinit.php');
$helper = $fb->getRedirectLoginHelper();
$permissions = ['manage_pages','publish_pages']; //'publish_actions'
$loginUrl = $helper->getLoginUrl('https://www.REDACTED.net/fb-callback.php', $permissions);
echo '<a href="' . htmlspecialchars($loginUrl) . '">Log in with Facebook!</a>';
?>
fb-callback.php:
<?php
include('fbinit.php');
$helper = $fb->getRedirectLoginHelper();
$_SESSION['FBRLH_state']=$_GET['state'];
try {
$accessToken = $helper->getAccessToken();
} catch(Facebook\Exceptions\FacebookResponseException $e) {
echo 'Graph returned an error: ' . $e->getMessage();
exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
if (! isset($accessToken)) {
echo 'No OAuth data could be obtained from the signed request. User has not authorized your app yet.';
exit;
}
try {
$response = $fb->get('me/accounts', $accessToken->getValue());
$response = $response->getDecodedBody();
} catch(Facebook\Exceptions\FacebookResponseException $e) {
echo 'Graph returned an error: ' . $e->getMessage();
exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
echo "<pre>";
print_r($response);
echo "</pre>";
?>
我第一次打开fbpost.php时,按预期要求登录Facebook,并要求允许在页面上代表我发帖,这很好。但随后我被重定向到回调页面并出现以下错误:
Graph returned an error: Can't load URL: The domain of this URL isn't included in the app's domains. To be able to load this URL, add all domains and sub-domains of your app to the App Domains field in your app settings.
我已经添加了我能想到的应用 URL 和回调 URL 的所有组合,但没有任何效果。有关应用程序设置的屏幕截图,请参见下文。 App ID 和 secret 绝对正确。
【问题讨论】:
-
redirect_uri参数的值必须与您的登录对话框调用以及随后尝试将代码交换为令牌的 API 调用完全相同。当您生成登录 URL 并处理分布在不同脚本上的响应(即,通过不同的 URL 调用)时,很容易导致这样的问题。尝试在您的getAccessToken方法调用中明确指定回调 URL。 -
啊哈,成功了!在 getAccessToken() 中指定回调 URL 允许回调工作,然后我得到代表返回页面的数组。谢谢!如果您将此作为答案发布,我会接受。
标签: facebook-graph-api facebook-php-sdk