【问题标题】:Programmatically post a facebook page status using Cron with the PHP API使用 Cron 和 PHP API 以编程方式发布 Facebook 页面状态
【发布时间】:2013-01-22 20:34:21
【问题描述】:

所以我一直在努力解决这个问题。我一直在查看现有问题的堆栈溢出并发现:Facebook: Post on Page as Page issue (access token / php) 但它似乎仍然无法解决我的问题。

我每天都在尝试使用 cron 作业发布到我的 Facebook 页面。我遇到了身份验证问题。这是我的代码:

    //Post to Facebook
//Variables
$app_id = "...";
$app_secret = "..."; 
$page_id = "...";
$my_url = "http://.../";
$access_token = "taken from page access token (developers.facebook.com/tools/explorer/)";

//Create the facebook object
$facebook = new Facebook(array(
 'appId' => $app_id,
 'secret' => $app_secret,
 'cookie' => true
));

//Get the access token using Facebook Graph API
//This gives permission to post to the wall
$token_url="https://graph.facebook.com/oauth/access_token?client_id=" . $app_id 
    . "&client_secret=" . $app_secret 
    . "&code=" . $access_token 
    . "&redirect_uri=" . $my_url;

$response = file_get_contents($token_url);
$params = null;
parse_str($response, $params);
$user_access_token = $params['access_token'];


//Get a list of pages and loop through
//If one matches one in the variables above, that's the one
//We're posting to
$attachment_1 = array(
    'access_token' => $user_access_token
);

$result = $facebook->api("/me/accounts", $attachment_1);
    foreach($result["data"] as $page) {
        if($page["id"] == $page_id) {
            $page_access_token = $page["access_token"];
            break;
        }
    }

//Write to the Page wall
try {
    $attachment = array(
                'access_token' => $page_access_token,
                'message'=> "Hello World"
        );

    $result = $facebook->api('/me/feed','POST', $attachment);

} catch(Exception $e) {
    //Send me an email
    ...
    mail($to, $subject, $message, $headers);
}

如果我在浏览器中访问脚本(我假设它正在使用我的 facebook 会话),则此方法有效,但当它由 cron 作业触发时则无效。

我非常感谢任何帮助。谢谢。

【问题讨论】:

    标签: php facebook api cron


    【解决方案1】:
    //Get the access token using Facebook Graph API
    //This gives permission to post to the wall
    

    如果您已经有一个页面访问令牌,那么此时此步骤是错误的 - 它是为了将 Auth 对话框传递回您的应用的代码交换为用户访问令牌。

    但由于您已经拥有页面访问令牌,您可以跳过该步骤(从上述 cmets 到 //Write to the Page wall 的所有内容)。

    您所要做的就是在 API 调用中使用您的页面访问令牌,而不是您现在提供的用户访问令牌。

    【讨论】:

    • 非常感谢,已经解决了。先生,您真是个天才 :) 出于兴趣,需要多长时间才能对这些 API 充满信心?文档让我感到困惑。
    • 另外,我看到这现在通过 Graph API 而不是我的应用程序。如果我愿意,如何更改我的解决方案以通过我的 facebook 应用程序工作?非常感谢。
    • “这现在通过 Graph API 而不是我的应用程序” – 我不确定我理解你的意思。您的意思是,这些帖子似乎是由页面本身而不是实际用户发布的?应该是这样的。如果您想以用户身份发帖,您仍然需要获取用户访问令牌,而不是页面访问令牌。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-09
    • 1970-01-01
    • 2012-04-10
    • 1970-01-01
    相关资源
    最近更新 更多