使用带有PHP API的Cron以编程方式发布Facebook页面状态



所以我一直在努力使这项工作。我一直在堆栈溢出查看现有问题并发现:Facebook:在页面上发布为页面问题(访问令牌/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 作业触发时则无效。

我真的很感激任何帮助。谢谢。

//Get the access token using Facebook Graph API
//This gives permission to post to the wall

如果已有页面访问令牌,则此步骤此时是错误的 - 它用于将身份验证对话框传递回应用的代码交换为用户访问令牌。

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

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

相关内容

最新更新