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

Get latest Facebook posts of page with PHP SDK

以下代码位于名为 facebook_posts.php 的文件中,我从索引文件中调用该文件,如下所示:<?php require_once("http://www.example.com/design/php/facebook_posts.php"); ?>。然而,这段代码放在哪里,却没有任何反应。因此,无论是成功还是捕获错误 return 都是错误(如我所见)。我尝试了绝对 URL,但这也不起作用。 (我隐藏了 api 和页面信息。)显然 require_once 之后的内容(页脚和脚本)未加载。包含 SDK 时似乎出了点问题。

我没有使用 Composer,我需要 require Facebook\ 文件还是 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";
}

?>

编辑:所以我只是 required in 所有 FB 文件,这似乎有效。但是,我不知道如何 traverse/iterate returned 的对象。 IE。如何循环浏览不同的帖子(该页面的四个最新帖子)并在 HTML 中回显它们。基本结构如下所示:

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

您需要使用长期有效的页面访问令牌。

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.

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

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


  1. 创建 Facebook 应用程序:

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

    • 继续 Graph API Explorer 和 select 您刚刚创建的应用程序,
    • 生成访问令牌:单击 "Get access token" 并在 "Extended Permissions" 选项卡中勾选 manage_pages
  3. Get your short-lived page access token.

    • 仍在 Graph API 资源管理器中,查询 me/accounts (GET),
    • 找到您的页面并获取其访问令牌 (3).
  4. Get your long-lived page access token.

    • 在浏览器的地址栏中粘贴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
    • 使用Access Token Debugger验证您的访问令牌永不过期

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

$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
}

从 Facebook 提要获取最新帖子所需的所有内容都在此处进行了描述:http://piotrpasich.com/facebook-fanpage-feed/

快捷方式 - 使用您的粉丝专页供稿(请将 {id} 替换为正确的 ID)

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

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

$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

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

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

1.- 创建应用程序。

2.- 转到:https://developers.facebook.com/tools/explorer/

  • Select 你新建的应用在右上角。
  • Select "Get App Token"

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

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

4.- 使用 CURL:

查询 URL

(5).- 等价于 URL:

我将所有这些放在一起,形成一个非常简单的要点:

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

  1. 创建应用程序Developer Facebook Page

然后代码示例:

<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>