Posting facebook api not as page - facebook

I've made facebook app, got appID and secret, and I am trying to post to a page as the page. I've granted the app permission.
But when I'm posting, new post creates "as user", not as page.
My code:
require '../lib/fb/autoload.php';
use Facebook\FacebookSession;
use Facebook\FacebookRequest;
use Facebook\GraphUser;
use Facebook\FacebookRequestException;
FacebookSession::setDefaultApplication('APP_ID','SECRET');
$session = new FacebookSession('ACCESS_TOKEN');
try {
$response = (new FacebookRequest(
$session, 'POST', '/1429642034012499/feed', array(
'message' => 'test',
'link' => 'http://mylink',
)
))->execute()->getGraphObject();
print_r($response);
} catch (FacebookRequestException $e) {
echo "Exception occured, code: " . $e->getCode();
echo " with message: " . $e->getMessage();
} catch (\Exception $e) {
}
Page to view.

This Answer is for C#, using the .NET Facebook API Library. But Logic should be same in PHP.
You have to get the Page Access Token:
Go Here: developers.facebook.com/tools/
Then Go to this Link:
Then Click on: "Get Access Token"
Then Add these Permissions:
Then Copy New access Token:
Now in C# Class I do (This is the POST A Comment as Page):
var userClient = new FacebookClient("THE NEW ACCESS TOKEN YOU JUST GENERATED");
dynamic accountInfo = userClient.Get("USER_ID" + "/accounts");
//USER_ID Should be Digits, this is the UserID when you do: facebook.com/USERID it should come up with the Admin Profile
var pageAccessToken = accountInfo.data[0].access_token;
var pageClient = new FacebookClient(pageAccessToken);
dynamic parameters = new ExpandoObject();
parameters.message = model.Message;
dynamic pageResult = pageClient.Post(string.Format("{0}/comments",), parameters);

Related

how to post on facebook using htc sense api

I am using Facebook SDK with HTC Sense Token,so i want to do that requests with user auth just with the token doing like this with the token i want to send requests with use a app(using the htc sense token) i had an appid but i had no secret code to post on facebook how to get the app htc sense app secret code to post on my wall,page etc
<?php
session_start();
require_once 'facebook-php-sdk/autoload.php';
use Facebook\FacebookSession;
use Facebook\FacebookRequest;
use Facebook\GraphUser;
use Facebook\FacebookRequestException;
use Facebook\FacebookRedirectLoginHelper;
$api_key = 'FACEBOOK_APP_ID';
$api_secret = 'FACEBOOK_APP_SECRET';
$redirect_login_url = 'http://www.yoursite.com/somefolder/file.php';
/ initialize your app using your key and secret
FacebookSession::setDefaultApplication($api_key, $api_secret);
// create a helper opject which is needed to create a login URL
// the $redirect_login_url is the page a visitor will come to after login
$helper = new FacebookRedirectLoginHelper( $redirect_login_url);
// First check if this is an existing PHP session
if ( isset( $_SESSION ) && isset( $_SESSION['fb_token'] ) ) {
// create new session from the existing PHP sesson
$session = new FacebookSession( $_SESSION['fb_token'] );
try {
// validate the access_token to make sure it's still valid
if ( !$session->validate() ) $session = null;
} catch ( Exception $e ) {
// catch any exceptions and set the sesson null
$session = null;
echo 'No session: '.$e->getMessage();
}
} elseif ( empty( $session ) ) {
// the session is empty, we create a new one
try {
// the visitor is redirected from the login, let's pickup the session
$session = $helper->getSessionFromRedirect();
} catch( FacebookRequestException $e ) {
// Facebook has returned an error
echo 'Facebook (session) request error: '.$e->getMessage();
} catch( Exception $e ) {
// Any other error
echo 'Other (session) request error: '.$e->getMessage();
}
}
if ( isset( $session ) ) {
// store the session token into a PHP session
$_SESSION['fb_token'] = $session->getToken();
// and create a new Facebook session using the cururent token
// or from the new token we got after login
$session = new FacebookSession( $session->getToken() );
try {
// with this session I will post a message to my own timeline
$request = new FacebookRequest(
$session,
'POST',
'/me/feed',
array(
'link' => 'www.finalwebsites.com/facebook-api-php-tutorial/',
'message' => 'A step by step tutorial on how to use Facebook PHP SDK v4.0'
)
);
$response = $request->execute();
$graphObject = $response->getGraphObject();
// the POST response object
echo '<pre>' . print_r( $graphObject, 1 ) . '</pre>';
$msgid = $graphObject->getProperty('id');
} catch ( FacebookRequestException $e ) {
// show any error for this facebook request
echo 'Facebook (post) request error: '.$e->getMessage();
}
if ( isset ( $msgid ) ) {
// we only need to the sec. part of this ID
$parts = explode('_', $msgid);
try {
$request2 = new FacebookRequest(
$session,
'GET',
'/'.$parts[1]
);
$response2 = $request2->execute();
$graphObject2 = $response2->getGraphObject();
// the GET response object
echo '<pre>' . print_r( $graphObject2, 1 ) . '</pre>';
} catch ( FacebookRequestException $e ) {
// show any error for this facebook request
echo 'Facebook (get) request error: '.$e->getMessage();
}
}
} else {
// we need to create a new session, provide a login link
echo 'No session, please login.';
}
You need to use a Token of your own App. Not sure why you would want to use the Token of the HTC Sense App for posting, afaik it is ONLY used for spamming - because a lot of permissions are already approved for it. Don´t do that, create your own authorization process for your own App: https://developers.facebook.com/docs/facebook-login
...and then go through Login Review with the additional permission: https://developers.facebook.com/docs/facebook-login/review
Trying to use/abuse/hijack another App is just wrong and definitely not allowed.

How to autopost to facebook page with app id

How to post to Facebook page with the App ID & Secret & Page ID without need to login with the user Admin of the page to get access token, the App owner who is the Admin of the page shouldn't be enough to auto post !?
I am using PHP & SDK4 of Facebook API.
You can´t post anywhere on Facebook without authorizing. If you want to post "as Page", you need to authorize a Page admin with the "publish_pages" permission and use a Page Token. You can´t get a User or Page Token without authorization, and of course you can´t automate the authorization process. Check out the docs for detailed information: https://developers.facebook.com/docs/graph-api/reference/v2.3/page/feed#publish
You will also need to learn about Access Tokens:
https://developers.facebook.com/docs/facebook-login/access-tokens
http://www.devils-heaven.com/facebook-access-tokens/
In fact all i wanted specifically to have permanent page access token so i can auto post forever without requiring authentication from the user each time for posting.
follow these steps to get it: Permanent Access Token
then use auto post code :
session_start();
define('FACEBOOK_SDK_V4_SRC_DIR', 'facebook-php-sdk-v4-4.0-dev/src/Facebook/');
require __DIR__ . '/facebook-php-sdk-v4-4.0-dev/autoload.php';
use Facebook\FacebookSession;
use Facebook\FacebookRequest;
use Facebook\GraphUser;
use Facebook\FacebookRequestException;
use Facebook\FacebookRedirectLoginHelper;
// Facebook App
$api_key = 'xxxxxxxxxxxxxxxx'; //App ID
$api_secret = 'xxxxxxxxxxxxxxxx'; //App Secret
$page_id = 'xxxxxxxxxxxxxxxx'; //Page ID
$page_token = 'from the steps in the url';
$fb_post = array(
'message'=> 'test message',
'name'=> '',
'link'=> 'http://www.example.com/',
'picture'=> 'http://www.example.com/image.jpg',
'caption'=> '',
);
// start a session for this App
FacebookSession::setDefaultApplication($api_key, $api_secret);
try {
$session = new FacebookSession($page_token);
} catch(FacebookRequestException $e) {
die(" Error : " . $e->getMessage());
} catch(\Exception $e) {
die(" Error : " . $e->getMessage());
}
try {
// Auto posting
$page_post = (new FacebookRequest( $session, 'POST', '/'. $page_id .'/feed', $fb_post))->execute()->getGraphObject()->asArray();
// return post_id, optional
print_r( $page_post );
} catch (FacebookRequestException $e) {
// The Graph API returned an error
echo '<b style="color:blue;">'.$e->getMessage().'</b>';
} catch (\Exception $e) {
// Some other error occurred
echo '<b style="color:red;">'.$e->getMessage().'</b>';
}

Getting facebook friends list

I made link of facebook login which requests an access token with permission to friends list:
<a href="https://www.facebook.com/dialog/oauth?response_type=token&scope=user_friends...>Login</a>
After the user passed the login successfully and accept these permissions and my app stored the access token, I tried to get his friends list by:
https://graph.facebook.com/me/friends?access_token={ACCESS_TOKEN}
But all I get is:
{
"data": [
],
"summary": {
"total_count": 245
}
}
Maybe I should request something else in the scope?
Thank you !
$request = new FacebookRequest(
$session,
'GET',
'/me/friends'
);
$response = $request->execute();
$graphObject = $response->getGraphObject();
For example in CodeIgniter I use fb library and i get friends list like this:
public function get_user_friends() {
if ( $this->session ) {
try {
$fr = new FacebookRequest( $this->session, 'GET', '/me/friends' );
$request = $fr->execute();
$user_friends = $request->getGraphObject()->asArray();
return $user_friends;
} catch(FacebookRequestException $e) {
return false;
/*echo "Exception occured, code: " . $e->getCode();
echo " with message: " . $e->getMessage();*/
}
}
}
And dont forget that it has some conditions:
Permissions
A user access token with user_friends permission is required to view the current person's friends.
This will only return any friends who have used (via Facebook Login) the app making the request.
If a friend of the person declines the user_friends permission, that friend will not show up in the friend list for this person.
More about: https://developers.facebook.com/docs/graph-api/reference/v2.2/user/friends

how can I get a facebook Page access token from a users access token using php?

I am trying to get a page access token starting out with just a users access token stored in my database and a page id. So far I have not been using the facebook.php instead just using php's curl_* functions. So far I can send posts to the page (with a hard coded page id) but I want to impersonate the page when doing so.
Can I do this easily without facebook.php, that would be nice as it might save me from feeling like I should rewrite what I've done so far. If not, then how would I get the page access token from the facebook object - remember so far at least I don't store user ids or page ids in my db, just user access tokens and of course my app id and secret.
I've been looking at the example for getting page access tokens but I find it not quite what I need as it gets a user object and in so doing seems to force the user to login to facebook each time, but I stored the user access token to avoid exactly that from happening.
Do I need more permissions than manage_page and publish_stream? I tried adding offline_access but it doesn't seem available anymore (roadmap mentions this).
here is some of my code from my most recent attempt which uses the facebook.php file:
// try using facebook.php
require_once 'src/facebook.php';
// Create our Application instance
$facebook = new Facebook(array(
'appId' => $FB_APP_ID, // $FB_APP_ID hardcoded earlier
'secret' => $FB_APP_SECRET, // $FB_APP_SECRET hardcoded earlier
));
$facebook->setAccessToken($FB_ACCESS_TOKEN );
//got user access token $FB_ACCESS_TOKEN from database
// Get User ID -- why?
$user = $facebook->getUser();
//------ get PAGE access token
$attachment_1 = array(
'access_token' => $FB_ACCESS_TOKEN
);
$result = $facebook->api("/me/accounts", $attachment_1);
foreach($result["data"] as $page) {
if($page["id"] == $page_id) {// $page_id hardcoded earlier
$page_access_token = $page["access_token"];
break;
}
}
echo '<br/>'.__FILE__.' '.__FUNCTION__.' '.__LINE__.' $result= ' ;
var_dump($result); //this prints: array(1) { ["data"]=> array(0) { } }
$facebook->setAccessToken($page_access_token );
// Get User ID, why - re-init with new token maybe?
$user = $facebook->getUser();
//------ write to page wall
try {
$attachment = array(
'access_token' => $page_access_token,
'link' => $postLink,
'message'=> $postMessage
);
$result = $facebook->api('/me/feed','POST', $attachment);
echo '<br/>'.__FILE__.' '.__FUNCTION__.' '.__LINE__.' $result= ' ;
var_dump($result);
} catch(Exception $e) {
echo '<br/>'.__FILE__.' '.__FUNCTION__.' '.__LINE__.' $e= ' ;
var_dump($e); /*this gives : "An active access token must
be used to query information about the
current user." */
}
die;
Thanks
PS: I hardcoded the user id and started calling
$result = $facebook->api("/$user_id/accounts", $attachment_1);
and I still get an empty result.
PPS: The Graph API Explorer does not show my fan pages either even though my account is set as the Manager. My attempts to post work but show as being from my account rather than from the page.
PPPS: made a little progress by adding permissions on the graph explorer page to get an access token that way but that doesn't help as I need to the the access token programmatically. When a user with many fan pages logs in to my site I want to show them the list of their facebook fan pages to choose from. In practice aren't the permissions just granted on the app?
PPPPS: the list of permissions on my app now stands at : email, user_about_me, publish_actions
and
Extended Permissions:
manage_pages, publish_stream, create_note, status_update, share_item
do I need more? when I try now I still fail to get anything from the call to:
$facebook->api("/$user_id/accounts", $attachment_1);
Px5S: DOH!!! I see now that I was neglecting to add the manage_pages permissions to my call for a user access token when my scripts first get one and store it in the DB. But when I reuse that new access token I still get the error : "An active access token must be used to query information about the current user." So, can't such tokens be reused? Aren't they long term? will read more stuff...
Here is my functioning code, still messy but seems to work, note the scopes on the first $dialog_url, and please feel free to mock my code or even suggest improvements :
function doWallPost($postName='',$postMessage='',$postLink='',$postCaption='',$postDescription=''){
global $FB_APP_ID, $FB_APP_SECRET;
$APP_RETURN_URL=((substr($_SERVER['SERVER_PROTOCOL'],0,4)=="HTTP")?"http://":"https://").$_SERVER['HTTP_HOST'].$_SERVER['SCRIPT_NAME'].'?returnurl=1';
$code = $_REQUEST["code"];
$FB_ACCESS_TOKEN = getFaceBookAccessToken( );
$FB_ACCESS_TOKEN_OLD = $FB_ACCESS_TOKEN;
//if no code ot facebook access token get one
if( empty($code) && empty($FB_ACCESS_TOKEN) && $_REQUEST["returnurl"] != '1')
{
// if( $_REQUEST["returnurl"] == '1') die;
$dialog_url = "http://www.facebook.com/dialog/oauth?client_id=".$FB_APP_ID."&redirect_uri=".$APP_RETURN_URL."&scope=publish_stream,manage_pages";
header("Location:$dialog_url");
}
if( empty($FB_ACCESS_TOKEN) ){
if($_REQUEST['error_code'] == '200'){
return null;
}else if (!empty($code)){
$token_url = "https://graph.facebook.com/oauth/access_token?client_id=".$FB_APP_ID."&redirect_uri=".urlencode($APP_RETURN_URL)."&client_secret=".$FB_APP_SECRET."&code=".$code;
$access_token = file_get_contents($token_url);
$param1=explode("&",$access_token);
$param2=explode("=",$param1[0]);
$FB_ACCESS_TOKEN=$param2[1];
}else{
return null;
}
}
if(!empty($FB_ACCESS_TOKEN) && $FB_ACCESS_TOKEN_OLD != $FB_ACCESS_TOKEN) {
setFaceBookAccessToken( $FB_ACCESS_TOKEN);
}
$_SESSION['FB_ACCESS_TOKEN'] = $FB_ACCESS_TOKEN;
$page_name = '';
$page_id = getFaceBookPageId(); //from db
if(empty($page_id ) ) return null;
//in case there are multiple page_ids separated by commas
if(stripos($page_id, ',') !== false ){
$page_ids = explode(',', $page_id) ;// = substr($page_id, 0, stripos($page_id, ','));
}
$result = null;
foreach($page_ids as $page_id){
$page_id = trim($page_id);
if( !empty($FB_ACCESS_TOKEN)){
//get page_id
require_once 'src/facebook.php';
// Create our Application instance (replace this with your appId and secret).
$facebook = new Facebook(array(
'appId' => $FB_APP_ID,
'secret' => $FB_APP_SECRET
));
$facebook->setAccessToken($FB_ACCESS_TOKEN );
//------ get PAGE access token
$page_access_token ='';
$attachment_1 = array(
'access_token' => $FB_ACCESS_TOKEN
);
$result = $facebook->api("/me/accounts", $attachment_1);
if(count($result["data"])==0) {
return null;
}
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,
'link' => $postLink,
'message'=> $postMessage
);
$result = $facebook->api('/me/feed','POST', $attachment);
} catch(Exception $e) {
return null;
}
} //end if( !empty($FB_ACCESS_TOKEN))
}//end foreach
return $result; }
Now, I wonder if I can send the same message to several pages at once ...
Yup, just by looping over the ids, see above, it now supports multiple page ids.
And unless someone wants to contribute to the code - there's lots of ways it can be improved - I'm done.

Facebook Graph Api - Posting to Fan Page as an Admin

I've setup a script which allows users to post messages to a fan page on Facebook. It all works but there's one small issue.
The Problem:
When the post is added to the page feed it displays the posting user's personal account.
I would prefer it to show the account of the page (like when you're admin of the page it says it came from that page). The account I'm posting with have admin rights to the page, but it still shows as a personal post.
HTTP POST
$url = "https://graph.facebook.com/PAGE_ID/feed";
$fields = array (
'message' => urlencode('Hello World'),
'access_token' => urlencode($access_token)
);
$fields_string = "";
foreach ($fields as $key => $value):
$fields_string .= $key . '=' . $value . '&';
endforeach;
rtrim($fields_string, '&');
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, count($fields));
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
$result = curl_exec($ch);
curl_close($ch);
To post as Page not as User, you need the following:
Permissions:
publish_stream
manage_pages
Requirements:
The page id and access_token (can be obtained since we got the required permissions above)
The current user to be an admin (to be able to retrieve the page's access_token)
An access_token with long-lived expiration time of one of the admins if you want to do this offline (from a background script)
PHP-SDK Example:
<?php
/**
* Edit the Page ID you are targeting
* And the message for your fans!
*/
$page_id = 'PAGE_ID';
$message = "I'm a Page!";
/**
* This code is just a snippet of the example.php script
* from the PHP-SDK <http://github.com/facebook/php-sdk/blob/master/examples/example.php>
*/
require '../src/facebook.php';
// Create our Application instance (replace this with your appId and secret).
$facebook = new Facebook(array(
'appId' => 'app_id',
'secret' => 'app_secret',
));
// Get User ID
$user = $facebook->getUser();
if ($user) {
try {
$page_info = $facebook->api("/$page_id?fields=access_token");
if( !empty($page_info['access_token']) ) {
$args = array(
'access_token' => $page_info['access_token'],
'message' => $message
);
$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'));
}
// ... rest of your code
?>
Here the connected $user is supposed to be the admin.
Result:
More in my tutorial
As far as I know, all you have to do is specify a uid (that is, the page's ID) in your call to stream.publish
EDIT
Have a look at impersonation
Because the is the only relevant posting in the google results for "facebook graph won't post to page as page" I want to make a note of the solution I found. You need an access token with manage_pages permissions. Then call
https://graph.facebook.com/<user_id>/accounts?access_token=<access_token>
This will list all the pages the user has access to and will provide the access tokens for each. You can then use those tokens to post as the page.
The Graph API expects the parameter page_id (The Object ID of the Fan Page) to be passed in as an argument to API calls to get the events posted in a Fanpage wall. Not mentioned anywhere in the official Graph API documentation, but it works. I have tested it successfully with the Official PHP SDK v3.0.1
The required application permissions would be create_event and manage_pages
An Example would look something like this:
//Facebook/Fan Page Id
$page_id = '18020xxxxxxxxxx';
//Event Start Time
$next_month = time() + (30 * 24 * 60 * 60);
//Event Paramaeters
$params = array(
'page_id' => $page_id, // **IMPORTANT**
'name' => 'Test Event Name',
'description' => 'This is the test event description. Check out the link for more info: http://yoursite.com',
'location' => 'Kottayam, Kerala, India',
'start_time' => $next_month
);
$create_event = $facebook->api("/$page_id/events", "post", $params);
The answer lies with acquiring a permission of "manage_pages" on the FB:login button, like so:
<fb:login-button perms="publish_stream,manage_pages" autologoutlink="true"></fb:login-button>`
When you get those permissions, you can then get a structured list back of all the pages the logged-in user is an Admin of. The URL to call for that is:
https://graph.facebook.com/me/accounts?access_token=YourAccessToken
I HATE the Facebook documentation, but here is a page with some of the information on it: https://developers.facebook.com/docs/reference/api/
See the 'Authorization' and 'Page Login' sections in particular on that page.
A great resource to put all of this together (for Coldfusion Developers) is Jeff Gladnick's CFC on RIA Forge: http://facebookgraph.riaforge.org/
I added the following UDF to Jeff's CFC if you care to use it:
<cffunction name="getPageLogins" access="public" output="true" returntype="any" hint="gets a user's associated pages they manage so they can log in as that page and post">
<cfset var profile = "" />
<cfhttp url="https://graph.facebook.com/me/accounts?access_token=#getAccessToken()#" result="accounts" />
<cfif IsJSON(accounts.filecontent)>
<cfreturn DeserializeJSON(accounts.filecontent) />
<cfelse>
<cfreturn 0/>
</cfif>
</cffunction>
What this returns is a structure of all the pages the logged-in user is an Admin of. It returns the page NAME, ID, ACCESS_TOKEN and CATEGORY (not needed in this context).
So, VERY IMPORTANT: The ID is what you pass to set what page you are posting TO, and the ACCESS_TOKEN is what you pass to set who you are POSTING AS.
Once you have the list of pages, you can parse the data to get a three-element array with:
ID - ACCESS_TOKEN - NAME
Be careful though, because the Facebook ACCESS_TOKEN does use some weird characters.
Let me know if you need any additional help.
You must retrieve access_tokens for Pages and Applications that the user administrates.
The access tokens can be queried by calling /{user_id}/accounts via the Graph API.
More details:
https://developers.facebook.com/docs/facebook-login/permissions/v2.0 -> Reference -> Pages
This is how I do it with PHP SDK 4.0 and Graph API 2.3:
/**
* Posts a message, link or link+message on the page feed as a page entity
*
* #param FacebookSession $session (containing a page admin user access_token)
* #param string $pageId
* #param string $message - optional
* #param string $link - optional
*
* #return GraphObject
*/
function postPageAsPage( $session, $pageId, $message = '', $link = '' ){
// get the page token to make the post request
$pageToken = ( new FacebookRequest(
$session,
'GET',
"/$pageId" . "?fields=access_token"
))->execute()->getGraphObject();
return ( new FacebookRequest(
$session,
'POST',
"/$pageId/feed",
array(
'access_token' => $pageToken->getProperty( 'access_token' ),
'message' => $message,
'link' => $link,
)
))->execute()->getGraphObject();
}