使用 PHP SDK 获取页面的最新 Facebook 帖子

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28124078/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 23:42:29  来源:igfitidea点击:

Get latest Facebook posts of page with PHP SDK

phpfacebookfacebook-graph-apifacebook-php-sdkfetch

提问by Bram Vanroy

The following code is inside a file called facebook_posts.php which I call from my index file like so: <?php require_once("http://www.example.com/design/php/facebook_posts.php"); ?>. However, where this code is put, there is no response. So neither success, nor the catch errors return an error (as I see it). I tried absolute URLs, but that didn't work either. (I hid the api and page information.) Apparently the content that follows the require_once (footer and scripts) aren't loaded. Something seems to go wrong when including the SDK.

下面的代码是一个名为facebook_posts.php这是我从我的索引文件称,像这样的内部:<?php require_once("http://www.example.com/design/php/facebook_posts.php"); ?>。然而,这个代码放在哪里,却没有任何反应。因此,成功和捕获错误都不会返回错误(如我所见)。我尝试了绝对 URL,但这也不起作用。(我隐藏了 api 和页面信息。)显然 require_once 后面的内容(页脚和脚本)没有加载。包含 SDK 时似乎出现问题。

I'm not using composer, do I need to requirethe Facebook\files or usethem? And which ones do I need for retrieving posts from a page?

我使用的不是作曲家,我需要requireFacebook\文件或use他们?从页面中检索帖子需要哪些?

<?php
// Defining FB SDK with absolute paths
define('FACEBOOK_SDK_V4_SRC_DIR', 'http://example.com/design/Facebook/');
require 'http://example.com/design/php/autoload.php';

use Facebook\FacebookSession;
use Facebook\FacebookRequest;
use Facebook\GraphUser;
use Facebook\FacebookRequestException;

FacebookSession::setDefaultApplication('{my-app-id}','{my-app-secret}');

$session = new FacebookSession('{my-long-lived-access-token}');

// Get the GraphUser object for the current user:

try {
$request = new FacebookRequest(
  $session,
  'GET',
  '/{my-page-id}/feed'
);
$response = $request->execute();
$graphObject = $response->getGraphObject();

var_dump($graphObject);
echo graphObject;
echo "banana";

} catch (FacebookRequestException $e) {
  echo "API ERROR";
} catch (\Exception $e) {
  echo "other error";
}

?>

EDIT: so I just required inall the FB files, and that seems to work. However, I don't know how to traverse/iterate the object that is returned. I.e. how to loop through the different posts (the four latest posts by the page) and echo them in HTML. A base structure would look like this:

编辑:所以我只需要在所有 FB 文件中,这似乎有效。但是,我不知道如何遍历/迭代返回的对象。即如何遍历不同的帖子(页面的四个最新帖子)并在 HTML 中回显它们。基本结构如下所示:

<time>{publish date}</time>
<p>{post message}</p>
<a href="{link to included url}">{title to included url}</a>

回答by Stéphane Bruckert

You need to use a long-lived page access-token.

您需要使用长期存在的页面访问令牌。

Page Access Token

These access tokens are similar to user access tokens, except that they provide permission to APIs that read, write or modify the data belonging to a Facebook Page. To obtain a page access token you need to start by obtaining a user access token and asking for the manage_pages permission. Once you have the user access token you then get the page access token via the Graph API.

页面访问令牌

这些访问令牌类似于用户访问令牌,不同之处在于它们为读取、写入或修改属于 Facebook 页面的数据的 API 提供权限。要获取页面访问令牌,您需要首先获取用户访问令牌并请求 manage_pages 权限。获得用户访问令牌后,您就可以通过 Graph API 获取页面访问令牌。

As @CBroe said, you should not use that access token in client-side code as it is secret/private and you don't want anyone to get it.

正如@CBroe 所说,您不应该在客户端代码中使用该访问令牌,因为它是秘密/私有的,并且您不希望任何人获得它。

So for what you want to do, Javascript is not the right choice. You will have to use some server-side code, like PHP, Python or Ruby to get the posts. If that is clear, here is how you can create it.

所以对于你想做的事情,Javascript 不是正确的选择。您将不得不使用一些服务器端代码,如 PHP、Python 或 Ruby 来获取帖子。如果这很清楚,这里是您创建它的方法。



  1. Create a Facebook app:

    • keep the app id (1)and app secret (2)aside,
    • in the "advanced" settings, activate OAuth in order to avoid The application has disabled OAuth client flow.
  2. You need to create a user access token.

    • go on the Graph API Explorerand select the application you just created,
    • generate an access token: click "Get access token" and tick manage_pagesin the "Extended Permissions" tab.
  3. Get your short-lived page access token.

    • still in the Graph API explorer, query me/accounts(GET),
    • find your page and get its access token (3).
  4. Get your long-lived page access token.

    • in your browser, paste https://graph.facebook.com/oauth/access_token?client_id=(1)&client_secret=(2)&grant_type=fb_exchange_token&fb_exchange_token=(3)in the address bar,
    • replace (1), (2)and (3)by your app id, your app secret and your page access token,
    • get your new long-lived access token from the result: access_token=FAKECAALBygJ4juoBAJyb8Cbq9bvwPYQwIaX53fLTMAWZCmDan1netI30khjITZAqcw9uE0lRT4ayWGm2ZCS7s7aZCVhF3ei6m0fuy2AkTkwmzUiJI4NUOZAyZAzuL,
    • use the Access Token Debuggerto verify that your access token will never expire.
  1. 创建一个 Facebook 应用程序:

    • 将应用程序 ID (1)和应用程序机密(2)放在一边,
    • 在“高级”设置中,激活 OAuth 以避免The application has disabled OAuth client flow.
  2. 您需要创建一个用户访问令牌。

    • 继续Graph API Explorer并选择您刚刚创建的应用程序,
    • 生成访问令牌:单击“获取访问令牌”并manage_pages在“扩展权限”选项卡中打勾。
  3. 获取您的短期页面访问令牌

    • 仍然在图 API 资源管理器中,查询me/accounts( GET),
    • 找到您的页面并获取其访问令牌(3)
  4. 获取您的长期页面访问令牌

    • 在浏览器中,粘贴https://graph.facebook.com/oauth/access_token?client_id=(1)&client_secret=(2)&grant_type=fb_exchange_token&fb_exchange_token=(3)到地址栏中,
    • (1)(2)(3)替换为您的应用程序 ID、应用程序密钥和页面访问令牌,
    • 从结果中获取新的长期访问令牌:access_token=FAKECAALBygJ4juoBAJyb8Cbq9bvwPYQwIaX53fLTMAWZCmDan1netI30khjITZAqcw9uE0lRT4ayWGm2ZCS7s7aZCVhF3ei6m0fuy2AkTkwmzUiJI4NUOZAyZAzuL,
    • 使用访问令牌调试器来验证您的访问令牌永不过期


Now you can use that new access token to retrieve the posts of your page:

现在您可以使用这个新的访问令牌来检索您页面的帖子:

$session = new FacebookSession('FAKECAALBygJ4juoBAJyb8Cbq9bvwPYQwIaX53fLTMAWZCmDan1netI30khjITZAqcw9uE0lRT4ayWGm2ZCS7s7aZCVhF3ei6m0fuy2AkTkwmzUiJI4NUOZAyZAzuL');

try {
    $data = (new FacebookRequest(
        $session, 'GET', '/me/posts'
    ))->execute()->getGraphObject()->getPropertyAsArray("data");

    foreach ($data as $post){
        $postId = $post->getProperty('id');
        $postMessage = $post->getProperty('message');
        print "$postId - $postMessage <br />";
    }
} catch (FacebookRequestException $e) {
    // The Graph API returned an error
} catch (\Exception $e) {
    // Some other error occurred
}

回答by biojazzard

I've found that the most voted solution is way too complicated and only lasts 2 months.

我发现投票最多的解决方案太复杂了,只能持续 2 个月。

For me, this is the best solution using an App with Graph API 2.5:

对我来说,这是使用带有 Graph API 2.5 的应用程序的最佳解决方案:

1.- Create an App.

1.- 创建一个应用程序。

2.- Go to: https://developers.facebook.com/tools/explorer/

2.- 前往:https: //developers.facebook.com/tools/explorer/

  • Select your new created app on the right top.
  • Select "Get App Token"
  • 在右上角选择您新创建的应用程序。
  • 选择“获取应用令牌”

3.- Copy this "{ACCESS-TOKEN}" (is in the form: number|hash)

3.- 复制此“{ACCESS-TOKEN}”(格式为:number|hash)

IMPORTANT: (This are not app_id|app_secret!!!)

重要提示:(这不是 app_id|app_secret !!!)

4.- Query the URL with CURL:

4.- 使用 CURL 查询 URL:

(5).- Equivalent URL:

(5).- 等效网址:

I've put all of this together in a very simple gist:

我把所有这些放在一个非常简单的要点中:

https://gist.github.com/biojazzard/740551af0455c528f8a9

https://gist.github.com/biojazzard/740551af0455c528f8a9

回答by Ramin Darvishov

  1. Create App Developer Facebook Page.
  1. 创建应用开发者 Facebook 页面

Then code exmaple:

然后代码示例:

<ul>
<?php

$page_name = '{PAGE_NAME}'; // Example: http://facebook.com/{PAGE_NAME}
$page_id = '{PAGE_ID}'; // can get form Facebook page settings
$app_id = '{APP_ID}'; // can get form Developer Facebook Page
$app_secret = '{APP_SECRET}'; // can get form Developer Facebook Page
$limit = 5;

function load_face_posts($page_id, $page_name, $app_id, $app_secret, $limit, $message_len) {
    $access_token = "https://graph.facebook.com/oauth/access_token?client_id=$app_id&client_secret=$app_secret&grant_type=client_credentials";
    $access_token = file_get_contents($access_token); // returns 'accesstoken=APP_TOKEN|APP_SECRET'
    $access_token = str_replace('access_token=', '', $access_token);
    $limit = 5;
    $data  = file_get_contents("https://graph.facebook.com/$page_name/posts?limit=$limit&access_token=$access_token");
    $data = json_decode($data, true);
    $posts = $data[data];
    //echo sizeof($posts);

    for($i=0; $i<sizeof($posts); $i++) {
        //echo $posts[$i][id];
        $link_id = str_replace($page_id."_", '', $posts[$i][id]);
        $message = $posts[$i][message];

        echo ($i+1).". <a target='_blank' href='https://www.facebook.com/AqualinkMMC/posts/".$link_id."'>".$message."</a><br>";
    }
}

load_face_posts($page_id, $page_name, $app_id, $app_secret, $limit, $message_len);
?>
</ul>

回答by Piotr Pasich

all what you need to get latest posts from facebook feed is described here: http://piotrpasich.com/facebook-fanpage-feed/

从 facebook 提要获取最新帖子所需的所有内容都在这里描述:http: //piotrpasich.com/facebook-fanpage-feed/

In shortcut - use your fanpage feed (please replace {id} by proper id)

简而言之 - 使用您的粉丝专页提要(请用正确的 ID 替换 {id})

https://facebook.com/feeds/page.php?format=atom10&id={id}

https://facebook.com/feeds/page.php?format=atom10&id={id}

You can download the feed with this piece of code:

您可以使用以下代码下载提要:

$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $rss_url);
curl_setopt($curl, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 1.0.3705; .NET CLR 1.1.4322; Media Center PC 4.0)');
curl_setopt($curl, CURLOPT_REFERER, '');
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_TIMEOUT, 10);
$raw_xml = curl_exec($curl); // execute the curl command