So I have been tearing my hair out trying to make this work. I have been all over stack overflow looking at existing questions and found this: Facebook: Post on Page as Page issue (access token / php) but it still doesn't seem to solve my problem.
I'm trying to post to my facebook page every day using a cron job. I am having problems with the authentication. Here's my code:
//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);
}
This works if I access the script in a browser (I assume it is using my facebook session then), but not when it is triggered by the cron job.
I would really appreciate any help. Thanks.
//Get the access token using Facebook Graph API
//This gives permission to post to the wall
If you already have a page access token, then this step is wrong at this point – it’s for exchanging the code that the Auth dialog passes back to your app for a user access token.
But since you already have your page access token, you can skip that step (everything from the above comments up to //Write to the Page wall
).
All you have to do, is to use your page access token in your API call, instead of the user access token you are giving there right now.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With