简体   繁体   中英

Post to Facebook wall with script, with automatic login

I'm able to post to my Facebook wall page when logged in using a PHP script (and the Graph API). I have a news page on my main website, and would like to push news items out to Facebook as they are posted to my site (which I guess is backwards from how many people use the API).

I've granted offline_access and publish_stream to my FB account, for the FB application.

If I close my FB session and try to post from my news page, Facebook presents a login page. I've granted access, so I don't know what else I'm missing.

If I understand your question correctly, I think I have just solved the same problem. I could not solve it entirely using the graph API, but a combination of the graph api and legacy rest api did the trick. Once you have granted permission for your app to post to your facebook page wall, the following code should do what you want:

$url = "https://graph.facebook.com/oauth/access_token";
$client_id = "XXXXXXXXXXXXXX";
$client_secret = "XXXXXXXXXXXXXXXXXXXXXXXXXXXX";
$postString = "client_id=$client_id&client_secret=$client_secret&type=client_cred";
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_FAILONERROR, 1);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $postString);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); 
$token = curl_exec($curl);
curl_close($curl);

$message = rawurlencode($description.'. Notes:'.$notes);
$url = "https://api.facebook.com/method/stream.publish";
$postString = "message=$message&uid=XXXXXXXXXXXXX&$token";
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_FAILONERROR, 1);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $postString);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); 
$response = curl_exec($curl);
curl_close($curl);

Few things worth noting.
1. The uid in the rest api $postString is the uid for your facebook PAGE. You do not need a target_id because when the uid is of a page it can only publish to itself.
2. Your $message must be rawurlencoded because that is the form accepted by the rest api.
3. This will post to your page as your APP, not as the user who made the post to your website. To do that you would need to have the publish_stream permission from all of your users.

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM