I have the following code which works fine as long as in a previous part of the application, the user accepts the applications request to publish_stream.
# The facebook library
require_once("/var/www/facebook-php-sdk-master/src/facebook.php");
# Create facebook object
$config = array();
$config['appId'] = 'appId_here';
$config['secret'] = 'secret_here';
$config['fileUpload'] = false; // optional
$facebook = new Facebook($config);
$user_id = $facebook->getUser();
if ($user_id) {
try {
$user_profile = $facebook->api('/me','GET');
#check permissions
$api_call = array(
'method' => 'users.hasAppPermission',
'uid' => $user_id,
'ext_perm' => 'publish_stream'
);
#set to true if true...
$can_offline = $facebook -> api( $api_call );
#is it true?
if( $can_offline ) {
$post = array(
'message' => 'post_a_message'
);
$facebook->api('/' . $_GET["id"] . '/feed', 'POST', $post);
} else {
// can't post message - don't have permission
}
} catch (FacebookApiException $e) {
error_log($e);
exit;
}
} else {
error_log("user not logged in");
exit;
}
To try to resolve this, I attempted to insert the following code into the else statement which currently in the code above only contains the comment // can't post message - don't have permission
The code I tried to insert into that else was this:
$loginUrl = $facebook->getLoginUrl( array( 'scope' => 'publish_stream' ) );
header("Location: ".$loginUrl);
That works as long as the user accepts to allow my app to publish_stream. However, if the user does not accept, my app will keep asking the user to accept publish_stream. How do I stop that loop from happening if the user decides not to accept?
As far as i remember, $facebook -> getLoginUrl can take parameter cancel_url, which contains the link, where user should be redirected if he doesn't give your app permissions.
So the code will be something like this
$login_url = $facebook -> getLoginUrl( array(
'scope' => 'publish_stream',
'cancel_url' => YOUR_LINK_HERE
));
Here is the working code : Please check it :
Page name : events.php
You can see $redirect_uri = https://localhost/facebook_page/events.php it is returning back to same page.
<?php
$facebook_appid = "your appid"; // Facebook appplication id
$facebook_secret = "your app secret"; // Facebook secret id
$redirect_uri = "https://localhost/facebook_page/events.php"; // return url to our application after facebook login ## should be SAME as in facebook application
$scope = "publish_stream"; // User permission for facebook
$profile_id = "profile_id";// Where do you want to post it(profile id - It is a number)
$code = $_REQUEST["code"]?$_REQUEST["code"]:"";
if(empty($code)) {
$_SESSION['state'] = rand(); // CSRF protection
$dialog_url = "https://www.facebook.com/dialog/oauth?client_id=". $facebook_appid . "&redirect_uri=" . urlencode($redirect_uri) . "&state=". $_SESSION['state'] . "&scope=".$scope;
header("location:".$dialog_url);
}
if($_SESSION['state'] && ($_SESSION['state'] == $_REQUEST['state'])) {
$token_url = "https://graph.facebook.com/oauth/access_token?". "client_id=" . $facebook_appid . "&redirect_uri=" . urlencode($redirect_uri). "&client_secret=" . $facebook_secret . "&code=" . $code;
$response = #file_get_contents($token_url);
$params = null;
parse_str($response, $params);
$access_token = $params['access_token'];
}
?>
<!-- Here you can use
message, picture, link, name, caption, description, source, place, tags
as input fields-->
<form enctype="multipart/form-data" method="POST" action="https://graph.facebook.com/<?php echo $profile_id;?>/feed?access_token=<?php echo $access_token; ?>">
<input type="text" name="message" value="test" />
<input type="submit" name="submit" value="Submit" />
</form>
You can post it using jquery also.
I use the following code to check if the user has allowed publishing permisions or not:
$permissions = $facebook->api('me/permissions');
if( array_key_exists('publish_stream', $permissions['data'][0]) ) {
//Continue with posting on users wall
} else {
//Continue without posting on users wall
}
Related
I need to create a system that when the cliente publish something in his website it will be published in his facebook, but to do this i need to get the access token because the account need to still logged to my system.
I made my app and tested it in my own facebook and when i try to login by my system it work, but when i try to login with the system in the client facebook, return this error:
An error has occurred. Try again later.
My code to generate the AccessToken is this:
require_once("php-sdk/src/facebook.php"); //Up-to-date SDK files from Git
$app_id = "APP_ID"; //ID do APP
$app_secret = "APP_SECRET"; //Secret do APP
$facebook = new Facebook(array(
'appId' => $app_id,
'secret' => $app_secret
));
$page_id = 'PAGE_ID';
$message = "Teste de integração";
$token_url = 'https://graph.facebook.com/oauth/access_token?'
. 'client_id=' . $app_id
. '&client_secret=' . $app_secret
. '&grant_type=client_credentials';
$token_response = file_get_contents_curl($token_url);
$params = null;
parse_str($token_response, $params);
$app_access_token = $params['access_token'];
// Get User ID
$user = $facebook->getUser();
if ($user) {
try {
$page_info = $facebook->api("/$page_id/?fields=access_token");
//print_r($page_info);
if( !empty($page_info['access_token']) ) {
//if(!empty($app_access_token)) {
$args = array(
'access_token' => $page_info['access_token'],
'message' => $message
);
// print_r($args);
// $post_id = $facebook->api("/$page_id/feed","post",$args);
} else {
$permissions = $facebook->api("/me/permissions");
if( !array_key_exists('publish_stream', $permissions['data'][0]) ||
!array_key_exists('manage_pages', $permissions['data'][0])) {
// We don't have one of the permissions
// Alert the admin or ask for the permission!
header( "Location: " . $facebook->getLoginUrl(array("scope" => "publish_stream, manage_pages")) );
}
}
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
}
// Login or logout url will be needed depending on current user state.
if ($user) {
$logoutUrl = $facebook->getLogoutUrl();
} else {
$loginUrl = $facebook->getLoginUrl(array('scope'=>'manage_pages,publish_stream, offline_access'));
}
?>
<?php if (!$user): ?>
Login with Facebook
<?php endif ?>
I already try to reconfig the user and all the config from the user is the same from the another account that didnt return the error.
I am using the following code to post to my facebook fan page and it is working fine. Now I want to use cronjob in order to post to Facebook. I know I have to use as access token but I am not sure how to set it up. I tried to use echo my own access token and the page's access token and use it in the post api but that did not work I got this error:
Uncaught OAuthException: An active access token must be used to query information about the current user.
Here is my code that I tried:
require_once('scripts/facebook.php');
$config = array('appId' => 'xxx','secret' => 'xxx');
$params = array('scope'=>'user_likes,publish_actions,email,offline_access,publish_stream,manage_pages');
$facebook = new Facebook($config);
$user = $facebook->getUser();
if($facebook->getUser()) {
try {
$user_profile = $facebook->api('/me');
$access_token = $facebook->getAccessToken();
//echo "1. ".$access_token;
} catch(FacebookApiException $e) {
$login_url = $facebook->getLoginUrl($params);
error_log($e->getType());
error_log($e->getMessage());
}
} else {
$login_url = $facebook->getLoginUrl($params);
}
$page_id = "xxxxxxxxxxxxx";
$page_access_token = "";
$result = $facebook->api("/me/accounts");
foreach($result["data"] as $page) {
if($page["id"] == $page_id) {
$page_access_token = $page["access_token"];
//echo '<br>';
//echo "2. ".$page_access_token;
break;
}
}
$args = array(
'access_token' => 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
'message' => stripslashes($image_caption).$animaged_gif,
'name' => stripslashes($image_caption).$animaged_gif,
'link' => "http://www.example.com/images.php?i=".$image_name,
'picture' => "http://www.example.com/thumbnails/".$image_name.".png",
'actions' => array(
'name' => 'See Pic',
'link' => "http://www.example.com/images.php?i=".$image_name
)
);
$post = $facebook->api("/$page_id/feed","post",$args);
As you can see that I tried to use the actual access token that I got when I echo out my own access token. But that did not work. I also used the page's access token, but that also did not work. Can you please tell what I am missing here or what is the proper way to do this ?
After some further search I did, I came across setAccessToken and $page_info = $fb->api("/".$sInfo['pageId']."?fields=access_token"); but there is very limited resources on how to use them. I am not even sure if those will be appropriate to this problem. All I need to know is which access token I need to use and what is the appropriate code to set it up ?
This is how you can do it :
Get a short lived accesstoken.
Extend it.
Get a long lived page accesstoken. (Doesn't matter, here we are going to fetch new accesstoken every time. Less complicated, and reliable.)
Thought I would go with an algo, instead I am adding all the possible codes and documentations since this may help someone else too.
Getting short lived access token and extending it:
fetchtoken.php
<?php
//read more : https://developers.facebook.com/docs/howtos/login/server-side-login/
session_start();
$app_id = "xxxxxxxxxxxxxx";
$app_secret = "xxxxxxxxxxxxxxxx";
$my_url = "www.stackoverflow.com/"; // redirect url
$code = $_REQUEST["code"];
if(empty($code)) {
// Redirect to Login Dialog
$_SESSION['state'] = md5(uniqid(rand(), TRUE)); // CSRF protection
$dialog_url = "https://www.facebook.com/dialog/oauth?client_id="
. $app_id . "&redirect_uri=" . urlencode($my_url) . "&state="
. $_SESSION['state'] . "&scope=publish_stream,read_friendlists,email";
echo("<script> top.location.href='" . $dialog_url . "'</script>");
}
if($_SESSION['state'] && ($_SESSION['state'] === $_REQUEST['state'])) {
$token_url = "https://graph.facebook.com/oauth/access_token?"
. "client_id=" . $app_id . "&redirect_uri=" . urlencode($my_url)
. "&client_secret=" . $app_secret . "&code=" . $code;
$response = file_get_contents($token_url);
$params = null;
parse_str($response, $params);
$longtoken=$params['access_token'];
//save it to database
}
?>
So you now have a long lived accesstoken ready in your database, a text file or whatever.
cronjob.php
<?
require_once('scripts/facebook.php');
// Pull access token from the file/db
$access_token = "access token from file or db";
$facebook->setAccessToken($access_token); // sets our access token as the access token when we call something using the SDK, which we are going to do now.
$config = array('appId' => 'xxx','secret' => 'xxx');
$params = array('scope'=>'user_likes,publish_actions,email,publish_stream,manage_pages');
$facebook = new Facebook($config);
$user = $facebook->getUser();
if($facebook->getUser()) {
try {
$user_profile = $facebook->api('/me');
} catch(FacebookApiException $e) {
$login_url = $facebook->getLoginUrl($params);
error_log($e->getType());
error_log($e->getMessage());
}
}
else {
$login_url = $facebook->getLoginUrl($params);
}
$page_id = "xxxxxxxxxxxxx";
$page_access_token = "";
$result = $facebook->api("/me/accounts");
foreach($result["data"] as $page) {
if($page["id"] == $page_id) {
$page_access_token = $page["access_token"];
//echo '<br>';
//echo "2. ".$page_access_token;
break;
}
}
$args = array(
'access_token' => $page_access_token,
'message' => stripslashes($image_caption).$animaged_gif,
'name' => stripslashes($image_caption).$animaged_gif,
'link' => "http://www.example.com/images.php?i=".$image_name,
'picture' => "http://www.example.com/thumbnails/".$image_name.".png",
'actions' => array(
'name' => 'See Pic',
'link' => "http://www.example.com/images.php?i=".$image_name
)
);
$post = $facebook->api("/$page_id/feed","post",$args);
?>
Make sure you don't grab access_token(user access token / $access_token) again in the script.
Also, the access_token in $args which is the page access token should be inserted by the $page_access_token variable, and not manually.
Having offline_access in the scope does nothing than showing them on the permission dialogue box that their data can be accessed any time which can be done without that notification anyway.
This should work as long as you visit the fetch.php once at the start, and once every 60 days manually.
Let me know.
This should probably fix it.
offline_access is deprecated. It is now being replaced by a system where you get an extended expiry access_token.
When you run it manually, You generate a live access token, which is invalid after 1-2 hours after you acutally run it. And there is no way you can generate another access_token with a cron. Generating access token should be done manually.
So to fix it, have a read : https://developers.facebook.com/roadmap/offline-access-removal/
and implement this : https://developers.facebook.com/docs/howtos/login/server-side-login/
And save the Access token to your database. When you run the cron, get the token from your database.
P.S : The access_token is valid for 60 days, and it should be extended again and can be done by the user logging in manually. The access_token generally "may" not change but just gets the expiry extended.
ADD :
Scheduling Posts :
You can also schedule the post for upto 6 months too. Just read about it and thought I would point out.
Read : https://developers.facebook.com/docs/reference/api/page/ scroll down to Posts Create sections
You can scrap the entire overhead of the Facebook API and follow this extremely simple approach.
Check what your page-specific email address is in the "Mobile" section of your page settings (https://www.facebook.com/pages/edit/?id=INSERT_YOUR_PAGE_ID_HERE&sk=mobile) and then use it here:
<?php
mail("thatEmailAddress#facebook.com", "New Status Update!", "");
?>
The body is empty because Facebook says "to update your status, write in the email subject line and leave the email body blank."
You can take a look here https://github.com/newbacknew/owloo.com. This is a base of scripts from owloo.com for get data from Facebook via the "ADS" Dashboard, also have to retrive analytics data from Twitter and Instagram.
With the base script you can get trends, interests, behavior, demographic, ages, gender qty of every country, city, stage, fanpage from facebook
The base of all script are in the WSERVICE folder of the backups folders.
I'm creating a FaceBook app where the user selects multiple images and the application generates a single image from them (PHP). I'm giving the generated image a semi-random name - $storage_url = $rack_directory . "rack_" . mt_rand() . mt_rand() . ".png"; (e.g. rack_2128639756968968165.png) and storing it temporarily as well.
I'd like the user to be able to upload the generated image to their Facebook profile directly from the page rather than downloading and then uploading it.
In looking over answers in this site as well as others it looks like I can use this:
$app_id = "YOUR_APP_ID";
$app_secret = "YOUR_APP_SECRET";
$post_login_url = "YOUR_POST-LOGIN_URL";
$album_name = 'YOUR_ALBUM_NAME';
$album_description = 'YOUR_ALBUM_DESCRIPTION';
$code = $_REQUEST["code"];
//Obtain the access_token with publish_stream permission
if(empty($code))
{
$dialog_url= "http://www.facebook.com/dialog/oauth?"
. "client_id=" . $app_id
. "&redirect_uri=" . urlencode($post_login_url)
. "&scope=publish_stream";
echo("<script>top.location.href='" . $dialog_url .
"'</script>");
}
else {
$token_url= "https://graph.facebook.com/oauth/"
. "access_token?"
. "client_id=" . $app_id
. "&redirect_uri=" . urlencode( $post_login_url)
. "&client_secret=" . $app_secret
. "&code=" . $code;
$response = file_get_contents($token_url);
$params = null;
parse_str($response, $params);
$access_token = $params['access_token'];
// Create a new album
$graph_url = "https://graph.facebook.com/me/albums?"
. "access_token=". $access_token;
$postdata = http_build_query(
array(
'name' => $album_name,
'message' => $album_description
)
);
$opts = array('http' =>
array(
'method'=> 'POST',
'header'=>
'Content-type: application/x-www-form-urlencoded',
'content' => $postdata
)
);
$context = stream_context_create($opts);
$result = json_decode(file_get_contents($graph_url, false,
$context));
// Get the new album ID
$album_id = $result->id;
//Show photo upload form and post to the Graph URL
$graph_url = "https://graph.facebook.com/". $album_id
. "/photos?access_token=" . $access_token;
echo '<html><body>';
echo '<form enctype="multipart/form-data" action="'
.$graph_url. ' "method="POST">';
echo 'Adding photo to album: ' . $album_name .'<br/><br/>';
echo 'Please choose a photo: ';
echo '<input name="source" type="file"><br/><br/>';
echo 'Say something about this photo: ';
echo '<input name="message" type="text"
value=""><br/><br/>';
echo '<input type="submit" value="Upload" /><br/>';
echo '</form>';
echo '</body></html>';
}
...to generate a unique album and upload the picture...
But - I don't want to display a form that has a user browse to and upload (after they right/control click and save the image from the page). Just take the existing generated image displayed on the page and submit that.
Is there a function that I could use so that this process occurs and the only form requirement is to submit and upload?
Thanks.
What you need is the Facebook SDK :https://developers.facebook.com/docs/reference/php/
This makes all those "Graph" calls much simpler.
Pasting from that page:
// Load the facebook SDK
require_once("facebook.php");
$config = array();
$config['appId'] = 'YOUR_APP_ID';
$config['secret'] = 'YOUR_APP_SECRET';
$config['fileUpload'] = false; // optional
$facebook = new Facebook($config);
try {
$uid = $facebook->getUser();
catch (FacebookApiException $e) {
// Not logged on - you should log them on. Various methods, but redirect to $facebook->getLoginURL() is simplest. Docs: https://developers.facebook.com/docs/reference/php/facebook-getLoginUrl/
}
Once the user is logged on, you can upload also through the SDK:
// Now upload the file
try {
$facebook->setFileUploadSupport('http://MyDomain.com/');
$response = $facebook->api(
'/me/photos/',
'post',
array(
'message' => 'Image Cpation',
'source' => '#/path/to/image' // #-sign must be the first character
)
);
}
catch (FacebookApiException $e) {
error_log('Could not post image to Facebook.');
}
You cna use an album ID in place of "me" for uploading directly to a specific album. But working your way through the SDK will help a lot more than trying it all manually with the graph calls!
Sorry, It's not a complete "here's the code" answer (there's still a bit of work to go), but that should help you upload without prompting the user.
I am developing my first facebook app, which includes creating a new album and posting photos to the user wall. By learning through facebook documentation and few tutorial and came up this code, but I am getting following error with it.
Fatal error: Uncaught OAuthException: Error validating application. Thrown in /home/base_facebook.php on line 1106
Plus: I don’t know if it matters or not, but when I am printing out the
echo $facebook->getUser();
variable it giving me ‘0’ in return even though user (which in this case is myself) is logged in.
Kindly help me through this.
Code:
$config = array(
'appId' => '3663250024856',
'secret' => 'b14ac6d2b7dbdtyb259599b06983e881',
'fileUpload' => true,
'cookie' => true
);
$facebook = new Facebook($config);
echo "USER STATUS:".$facebook->getUser();
$facebook -> setFileUploadSupport(true);
$album_details = array('message' => 'Album desc', 'name' => 'Album name');
$create_album = $facebook -> api('/me/albums', 'post', $album_details);
$album_uid = $create_album['id'];
$photo_details = array('message' => 'Photo message');
$file = "temp/".$imageName;
$photo_details['image'] = '#' . realpath($file);
$upload_photo = $facebook -> api('/' . $album_uid . '/photos', 'post', $photo_details);
The best working solution I've found in the web. Add the below code at the top of your php page:
$app_id = "YOUR_APP_ID";
$app_secret = "YOUR_APP_SECRET";
$my_url = "YOUR_URL";
$code = $_REQUEST["code"];
if(empty($code)) {
$_SESSION['state'] = md5(uniqid(rand(), TRUE)); //CSRF protection
$dialog_url = "http://www.facebook.com/dialog/oauth?client_id="
. $app_id . "&redirect_uri=" . urlencode($my_url) . "&state="
. $_SESSION['state'];
echo("<script> top.location.href='" . $dialog_url . "'</script>");
}
if($_REQUEST['state'] == $_SESSION['state']) {
$token_url = "https://graph.facebook.com/oauth/access_token?"
. "client_id=" . $app_id . "&redirect_uri=" . urlencode($my_url)
. "&client_secret=" . $app_secret . "&code=" . $code;
$response = #file_get_contents($token_url);
$params = null;
parse_str($response, $params);
$graph_url = "https://graph.facebook.com/me?access_token="
. $params['access_token'];
}
Even though the user is logged in, the user needs to give permission to your app before you can make api calls.
Basically the flow for user authentication using facebook php sdk should be like this:
Detect whether the user is logged in and given permission to your app.
If he hasn't given permission, redirect him to the login and application permission page. After logging in and giving permission, he'll be redirected back again to your application page.
Otherwise, show the content of your app, make api calls,...
Here is a modified sample code from the php sdk's documentation page to handle authentication that should work if you just modify the appId, appSecret and redirect_uri:
<?php
require_once 'fb_php_sdk/facebook.php';
$appId = 'your_app_id';
$appSecret = 'your_app_secret';
// Create your Application instance (replace this with your appId and secret).
$facebook = new Facebook(
array(
'appId' => $appId,
'secret' => $appSecret,
'fileUpload' => true,
'cookie' => true
));
// Get User ID
$user = $facebook->getUser();
if ($user)
{
try {
// Proceed knowing you have a logged in user who's authenticated.
$user_profile = $facebook->api('/me');
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
}
// Login or logout url will be needed depending on current user state.
if ($user)
{
$logoutUrl = $facebook->getLogoutUrl();
}
else
{
$loginUrl = $facebook->getLoginUrl(
array(
'canvas' => 1,
'fbconnect' => 0,
'scope' => '',//these are the extended permissions you will need for your app, add/remove according to your requirement
'redirect_uri' => 'http://apps.facebook.com/test_app_azk/',//this is the redirect uri where user will be redirected after allow,
));
}
if ($user)
{
//show the content of your app
//make api calls
var_dump($user_profile);
}
else
{
//redirect user to loginUrl
echo "<script>parent.location = '".$loginUrl."';</script>";
}
Hope this helps.
The problem might lie within the else statement. Instead of using else use if(!user). That should fix the issue.
I'm totally frustrated with my first facebook app project. I'm having major issues with what seems to be a simple task.
I want to setup a cron job on my server (easy) that will post something smart on a facebook page (not my profile), and it should be posted as page. I coded myself into a corner and am totally confused now... Can anyone help, please?
I've been thru pretty much every error message and am now stuck on
"OAuthException: Error validating application."
Here's what I have now:
First php -> Gets a new Access Token for my page access. This part seems to work fine, as I get the next page called and receive a new access token.
<?php
require_once 'facebook.php';
$app_id = "1234....";
$app_secret = "5678....";
$my_url = "http://.../next.php";
$facebook = new Facebook(array(
'appId' => $app_id,
'secret' => $app_secret,
'cookie' => true
));
// known valid access token stored in a database
$access_token = "abc....";
$code = $_REQUEST["code"];
// If we get a code, it means that we have re-authed the user
//and can get a valid access_token.
if (isset($code)) {
$token_url="https://graph.facebook.com/oauth/access_token?
client_id="
. $app_id . "&redirect_uri=" . urlencode($my_url)
. "&client_secret=" . $app_secret
. "&code=" . $code . "&display=popup";
$response = file_get_contents($token_url);
$params = null;
parse_str($response, $params);
$access_token = $params['access_token'];
}
// Attempt to query the graph:
$graph_url = "https://graph.facebook.com/me?"
. "access_token=" . $access_token;
$response = curl_get_file_contents($graph_url);
$decoded_response = json_decode($response);
//Check for errors
if ($decoded_response->error) {
// check to see if this is an oAuth error:
if ($decoded_response->error->type== "OAuthException") {
// Retrieving a valid access token.
$dialog_url= "https://www.facebook.com/dialog/oauth?"
. "client_id=" . $app_id
. "&redirect_uri=" . urlencode($my_url);
echo("<script> top.location.href='" . $dialog_url
. "'</script>");
} else {
echo "other error has happened";
}
} else {
// success
echo("success" . $decoded_response->name);
}
function curl_get_file_contents($URL) {
$c = curl_init();
curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($c, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($c, CURLOPT_URL, $URL);
$contents = curl_exec($c);
$err = curl_getinfo($c,CURLINFO_HTTP_CODE);
curl_close($c);
if ($contents) return $contents;
else return FALSE;
}
?>
Next php -> Read the access token and post on the wall. I get the access token from my query string, but then why do I receive the error message. My id, secret and page id are all in order...
<?php
require_once 'facebook.php';
$app_id = "1234....";
$app_secret = "5678....";
$page_id = "0909....";
$facebook = new Facebook(array(
'appId' => $app_id,
'secret' => $app_secret,
'cookie' => true
));
$access_token = $_GET['code'];
echo($access_token);
try {
$attachment = array(
'access_token' => $access_token,
'message'=> "Hello World"
);
$result = $facebook->api('/'.$page_id.'/feed','POST',
$attachment);
var_dump($result);
} catch(Exception $e) {
echo $e;
}
?>
I'm sure there is a simpler way to do so.... and a way to actually make it work!
Any help is appreciated!
I followed this script
Update facebook page status from that page itself
and this
https://developers.facebook.com/blog/post/500
Thank you.
// firstly include the fb sdk
$facebook = new Facebook(array(
'appId' => 'your app id',
'secret' => 'your app secret',`enter code here`
'cookie' => true,
));
$session = $facebook->getUser();
$loginUrl = $facebook->getLoginUrl(
array(
'scope' => 'user_status,publish_stream,email,user_location,user_birthday,friends_birthday,manage_pages',
'redirect_uri' => 'http://www.example.com/'
)
);
$logoutUrl = $facebook->getLogoutUrl(
array(
// any url u want to redirsct onto
'redirect_uri' => 'http://www.example.com/'
)
);
// when redirected from facebook get the code
$code = $_GET['code'];
//
$my_url = 'http://www.example.com/';
$app_id = 'your app id ';
$app_secret = 'your app secret ';
// here we have the access token so we will play with it
if (isset($code)) {
$token_url="https://graph.facebook.com/oauth/access_token?client_id="
. $app_id . "&redirect_uri=" . urlencode($my_url)
. "&client_secret=" . $app_secret
. "&code=" . $code ;
$response = file_get_contents($token_url);
$params = null;
parse_str($response, $params);
$user_access_token = $params['access_token'];
}
// here we got the access token of user over here in $user_access_token
// now we will get for our page
//------ get PAGE access token
$attachment_1 = array(
'access_token' => $user_access_token
);
$page_id = 'your page id ';
$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 page wall
try {
$attachment = array(
'access_token' => $page_access_token,
'message'=> 'hello world posting like admin!',
'page_id'=> $page_id
);
$result = $facebook->api('/'.$page_id.'/feed','POST',$attachment);
//$result = $facebook->api('/me/feed','POST', $attachment);
var_dump($result);
} catch(Exception $e) {
echo $e;
}
From your code, it appears you are not getting a PAGE access token which you need, but instead you're using a USER access token, hence why the API doesn't like it. For more information on how to get a PAGE access token from a USER one, please see the Page login section of https://developers.facebook.com/docs/authentication/
After many hours of trial and error, here's my solution that works so far.
<?php
require_once 'facebook.php';
//------ vars
$app_id = "123...";
$app_secret = "abc...";
$page_id = "999...";
$my_url = "http://exactly the same as defined /";
//------ fb object
$facebook = new Facebook(array(
'appId' => $app_id,
'secret' => $app_secret,
'cookie' => true
));
//------ verification CODE
// this is not pretty -> the code should be received with a another graph query...
// but I couldn't get this to work. Thus I'm using my last known Verification Code
$code = "ABC123...";
//------ get USER access token
if (isset($code)) {
$token_url="https://graph.facebook.com/oauth/access_token?client_id=" . $app_id
. "&client_secret=" . $app_secret
. "&code=" . $code
. "&redirect_uri=" . $my_url;
$response = file_get_contents($token_url);
$params = null;
parse_str($response, $params);
$user_access_token = $params['access_token'];
} else {
echo("No code");
}
//------ get PAGE access token
$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 page wall
try {
$attachment = array(
'access_token' => $page_access_token,
'message'=> 'hello world!'
);
$result = $facebook->api('/me/feed','POST', $attachment);
var_dump($result);
} catch(Exception $e) {
echo $e;
}
?>