How to post programatically to your own facebook page? - php

My situation is the following.
I am the owner of a facebook app,and a facebook page.I would like to programatically(from code) post to this facebook page.
As far as I know I need a facebook app to do that so I created one.
I am using the facebook php sdk and code igniter.(I am not using the javascript sdk).
I have the facebook object.I printed it's methods and tried printint the user id while I was logged into facebook.
This did not work.
My questions are the following:
1)Why does it not work to print the facebook id?
2)What is the most simplest solution to programatically post to my facebook page ?(from my app,or from my user)
What am I doing wrong ?
This is my code
$config = array(
'appId' => 'xxxx',
'secret' => 'xxxx',
'cookie' => true,
);
$this->load->library('facebook', $config);
echo '<pre>';print_r(get_class_methods($this->facebook));
$id = $this->facebook->getAppId();
$secret =$this->facebook->getApiSecret();
$uri = "http://tipsterscorner.com/stats/display/facebook1";//callback_url se pare ca nu e bun
//i build the facebook url.If I use this in the browser ,I get a series of popups(do you allow the application to blabla)
//I read somewhere that if I change the last parametere to code,and use curl,I will get the token in the response
//printed on the screen of the return url,but that does not happen
$facebook_url = "https://www.facebook.com/dialog/oauth?`client_id=$id&client_secret=$secret&redirect_uri=$uri&scope=publish_stream,offline_access,read_stream,manage_pages&response_type=token";`
$curl = curl_init();
// Set some options - we are passing in a useragent too here
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => $facebook_url,
CURLOPT_USERAGENT => 'Codular Sample cURL Request'
));
// Send the request & save response to $resp
$resp = curl_exec($curl);
This is the url.
http://tipsterscorner.com/stats/display/facebook1
Thank you very much.

To post on facebook by yourself and on behalf of other's using the app you need to obtain user access token. There are two kinds of Access Tokens namely App Access Token and User Access Token. When app is posting on user's behalf User Access Token is required. User Access Token is generated when a User gives permissions for the app(The dialog popup which you experienced when entering the facebook url in browser). Its solely upon user whether or not to grant permission to the app to post on their behalf. App should be developed to handle both the situations. Once User have given permission(Basic Permission which includes all publicly available info of the user), user access token will be generated. You can either store it in database table or in SESSION. Sometimes user access tokens may become invalid and new token has to be retrieved. During that time curl can be used to retrieve because user has already granted permission for the app.
http://developers.facebook.com/blog/post/2011/05/13/how-to--handle-expired-access-tokens/

Related

Facebook PHP - posting error to timeline but not to page

I am trying to post to a Facebook account (with permissions) using the PHP
API. I am giving our users two options - posting to the Feed, and posting
to a specific facebook page. I am getting an error in the first case, but
not in the second case. In the code below:
$access_token is the access token I got back from linking to my app. It's of type
"User", and has the following permissions:
email
pages_show_list
business_management
pages_read_engagement
pages_manage_metadata
pages_read_user_content
pages_manage_ads
pages_manage_posts
pages_manage_engagement
public_profile
Where $page_token is, well, a "Page" type token, with the same set of permissions.
When I post to the page, it works fine. But when I try to post to the timeline, I get
the error:
Graph Error 200 : [Timeline]: [(#200) If posting to a group, requires app being
installed in the group, and either publish_to_groups permission with user token,
or both pages_read_engagement and pages_manage_posts permission with page token;
If posting to a page, requires both pages_read_engagement and pages_manage_posts
as an admin with sufficient administrative permission]
I'm not trying to post to a group, I'm posting to an account's timeline. And, per the
access token debugger, I have the permissions requested anyway. What's going on?
My code is below:
$linkData = [
'link' => $link_to_post,
'appsecret_proof' => $app_secret_proof
];
if ( POSTING TO TIMELINE )
{
$token = $access_token;
$post_to = "/me/feed";
}
else
{
$page_id = $page_id;
$token = $page_token;
$post_to = "/$page_id/feed";
}
// THIS THROWS THE EXCEPTION:
$response = $this->fb->post($post_to, $linkData, $token);
You can not post to a personal timeline via API any more, that was removed ages ago already. (With introduction of API v2.4, if I remember correctly.)
You can only use the Share or the Feed dialog, to offer the user a way to actively share / make a post themselves, https://developers.facebook.com/docs/sharing/web

Do I still need to use Facebook user access tokens to post to Facebook pages?

I've created and stored permanent facebook page access tokens. Must I still use a user access token each time I want to post to a fb page feed, or can I use only the page access token?
Here is command I'm using to setup the post now:
$page_post = (new FacebookRequest( **$session**, 'POST', '/'. $page_id .'/feed', array(
'access_token' => $access_token,
'name' => 'Randy Steel',
'link' => 'http://www.LIPSapp.com/',
'caption' => 'Example text',
'message' => 'This is my link!',
) ));
Where $session holds the user access token and $access_token holds the permanent page access token.
If, because I have the perm page access token, I can skip getting/updating the
user access token (60 days at best), how would the above command change?
What would the value of $session need to be, or can that parameter be omitted?
Thanks in advance for any help.
With Facebook's new update like 2 years ago, pages acts like normal profile pages. So you only need access tokens of page not administrator's. Access tokens can be changed overtime or can be expired so it's best you to store administrators access token just in cas the access key losts its validity.
If you always want to post "as Page", you can use the stored Page Token - in fact, you HAVE to use the Page Token to post "as Page". You only need the User Token once, for getting an Extended Page Token.
I would not even use the PHP SDK for that, basic CURL calls are good enough. A small example of using CURL with the Facebook API can be found here: http://www.devils-heaven.com/extended-page-access-tokens-curl/

facebook sso state check: CSRF state token does not match one provided

What are the basic steps for setting up a pure server flow facebook SSO, the docs are as usual a little ambiguous?
I set up the flow with javascript popups only to later realise you are not allowed to customise the login buttons.. which when you stick them next google and twitter sso the signin box look terrible.
http://www.codecademy.com/ seem to direct to their own server which then forwards onto a URL like this:
https://www.facebook.com/dialog/oauth?response_type=code
&client_id=212500508799908&
redirect_uri=http%3A%2F%2Fwww.codecademy.com%2Fauth%2Ffacebook%2Fcallback&state=8aac5bc63c5afe8fbabe572021e7750579fefd898d7b4316&
scope=email%2Cpublish_actions
How is this URL being generated? In the facebook docs there is a function "getLoginUrl".. is this being called which generates the correct URL?
I tried directing the user directly from their browser to:
var href = 'https://www.facebook.com/dialog/oauth?' +
'client_id='+app_id+'&'+
'redirect_uri=http://www.mysite.net/authenticate_facebook.php&'+
'scope=email&';+
'state='+$('body').attr('unique');
But the at the facebook php then the following recieving code resulted in errors about the 'state' not matching... I am assuming that the state is not just a random value generate by my server and must be aquired from the facebook server?
require_once(WEBROOT_PRIVATE.'authenticate/facebook-php-sdk/src/facebook.php');
$config = array(
'appId' => 'xxx',
'secret' => 'xxx',
'fileUpload' => false,
'allowSignedRequest' => false
);
$facebook = new \Facebook($config);
$user_id = $facebook->getUser();
if($user_id)
{
try
{
$user_profile = $facebook->api('/me','GET');
}
catch(FacebookApiException $e)
{
error_log($e->getType(), 0);
error_log($e->getMessage(), 0);
}
}
SO, is this correct flow:
1 - Direct the user to my server facebook_auth.php
2 - facebook_auth.php generate the get url and forwards the user onto it
3 - The user, if required logs into facebook, allows my app
4 - my facebook_auth.php script then checks the tokens and talks server to server with facebook to verify the rest
5 - my website then logs the user in
I had a similar issue last week, and tracked it down to the state field being overwritten by multiple calls to getLoginUrl(). Each time you call getLoginUrl(), a new state token is generated in the SDK and stored in the $_SESSION (it's just a random value), so if you call it twice and the user uses the first link to log in, the second call will have reset the SDK's internal state token, and you will get this error in your logs.
The SDK looks for the same state token in the URL coming back after Facebook authorizes the user and redirects them back to your site, and if it doesn't match it will log this error (here's a link to the source).

login with facebook using oauth

<?php
require "facebook.php";
$facebook = new Facebook(array(
'appId' => '3288##########',
'secret' => 'ca2##################',
));
$user = $facebook->getUser();
I have made the app in the graph api and I have very little knowledge of graph api . I want to make a facebook login page in which user clicked on it and my app will generate the oauth for the user . after that i need the USERNAME, EMAIL,BIRTHDAY,NAME in the fre filled forms
I'm searching for this code from 3 night, but i didn't find the solution! If you have a suggestion, please write to me it! Please, anyway thanks and good day :)
You could use POST request to simulate login. I don't know Facebook's inputs, so you need to look closely into it's HTML, but here is a code for a simple PHP cURL request.
// Get cURL resource
$curl = curl_init();
// Set some options - we are passing in a useragent too here
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => 'https://www.facebook.com/login.php',
CURLOPT_USERAGENT => 'Facebook Login',
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => array(
'username' => 'username',
'password' => 'myfbpass'
)
));
// Send the request & save response to $resp
$resp = curl_exec($curl);
// Close request to clear up some resources
curl_close($curl);
Of course, Facebook has automatic login detection by using those hidden fields for getting the sessions, but using DOM Document, you can easily get those values and emulate it, at least thats how I was able to simulate login for http://z8games.com/
Good luck
Code Credit:
http://codular.com/curl-with-php
Edit:
If you are lazy, you can go ahead and try this page - http://www.daniweb.com/web-development/php/code/290893/facebook-login-with-curl
Temboo makes it simple to implement Facebook OAuth by breaking the process down into two steps:
ÌnitializeOAuth returns the Facebook authorization URL that you need to show your users so that they can grant your app access to their Facebook accounts.
FinalizeOAuth returns the access token you need to programmatically read/write a user's Facebook data.
What's more, you can test these calls from your browser and generate the source code you need in the language of your choice.
Here's a short video that shows you how to do this with Temboo, and you can check out an example and source code here.
(Full disclosure: I work at Temboo, so let me know if you have any questions!)

facebook php sdk - Error #200 when trying to use setExtendedAccessToken

I have been trying for several days now to successfully post to a client's Facebook Page wall from their website. I need to be able to do this without having a user logged in, which I was able to achieve with an extended access token generated by going to the URL provided in the docs.
What I am trying to do is to fetch an extended token using the PHP SDK as in this question - Facebook PHP SDK: getting "long-lived" access token now that "offline_access" is deprecated, however I receive the following error:
(#200) The user hasn't authorized the application to perform this action
The debug of the auth token generated by the Graph API Explorer shows myself as the User and includes the needed manage_pages and status_update scopes. However, if I run me/accounts, the perms array does not list these under the data for the page in question - not sure if this is relevant.
Here is the code that I have attempted to use:
$facebook = new Facebook(array('appId' => 'xxxxxxx', 'secret' => 'xxxxxx'));
$pageID = 'xxxxxxxx';
$facebook->setExtendedAccessToken();
$accessToken = $facebook->getAccessToken();
try {
$page_info = $facebook->api("/$pageID?fields=access_token");
print_r ($page_info);
} catch (FacebookApiException $e) {
echo $e->getMessage();
}
if( !empty($accessToken) ) {
$args = array(
'access_token' => $accessToken,
'message' => "Catch phrase!"
);
$facebook->api("/$pageID/feed","post",$args);
} else {
// Handle error
}
UPDATE
I found that if I echoed the output of getAccessToken() the result was the app ID and the secret separated by an | - is this what I should be receiving? Seems odd to me since all of the other tokens I have seen are random and much longer.
ANY help at all would be appreciated, I have wasted so much time on this so far. It just seems to work for everyone else.
UPDATE 2
Hi Warren! Looks like you're new around these parts, welcome! Thanks for your research into this, do I need to save these tokens into a DB table and check to see if they are expired every time I try to post? I am ONLY posting to a Page as the Page, apparently this requires the Page access_token rather than what I am assuming is the USER access_token. I believe I also read somewhere that the Page access token never expires, although it changes if I refresh the Graph API Explorer page or request a new user token. Very puzzling.. do not know if I even need to deal with getting new tokens in this app or just use a Page access_token that appears to work?
Also just looking at the base_facebook.php file and the following function:
/**
* Returns the access token that should be used for logged out
* users when no authorization code is available.
*
* #return string The application access token, useful for gathering
* public information about users and applications.
*/
protected function getApplicationAccessToken() {
return $this->appId.'|'.$this->appSecret;
}
Shows what you are experiencing the function setExtendedAccessToken() calls getAccessToken() which calls the function above to do the following inside setExtendedAccessToken:
$access_token_response = $this->_oauthRequest(
$this->getUrl('graph', '/oauth/access_token'),
$params = array(
'client_id' => $this->getAppId(),
'client_secret' => $this->getAppSecret(),
'grant_type' => 'fb_exchange_token',
'fb_exchange_token' => $this->getAccessToken(),
)
);
the return of this function is then {"error":{"message":"No user access token specified","type":"OAuthException","code":1}} but because there is no access_token the function just returns false
the fb_exchange_token can not be the app id and app secret combined.
I have done some testing and what I have found out is if you get the user to login, you can get there access token. If you pass this token into setAccessToken then run setExtendedToken. If you then save the toke by running getAccessToken you can use this token later when the user is logged out.
$facebook->setAccessToken($facebook->getAccessToken());
$facebook->setExtendedAccessToken();
$access_token = $facebook->getAccessToken(); // save this for later use
You need to get the user to login to ask them for permission to get access to there account. If you need to get access to a facebook page make sure they are an admin and ask for the manage_page permission.
Hope this helps
From what I have found so far the extended token that is returned when the user is logged in does not expire as you do not get back a unix timestamp so you would have no way of knowing when it expires.
This is what I have done in my application.
Request the user to login to facebook and except the access permissions. Use getAccessToken to get the current access token. With this I pass into getExtendedAccessToken then run getAccessToken again to finally get the extended access token which I store in a database for later use.
$facebook = new Facebook(array(
'appId' => 'YOURAPPID',
'secret' => 'YOURSECRET',
));
$params = array(
'scope'=>'publish_stream,manage_pages'
);
$loginUrl = $facebook->getLoginUrl($params); // Use this to request them to login in then when they are do the following you will need them to return to your app
$facebook = new Facebook(array(
'appId' => 'YOURAPPID',
'secret' => 'YOURSECRET',
));
$facebook->setAccessToken($facebook->getAccessToken());
$facebook->setExtendedAccessToken();
$access_token = $facebook->getAccessToken(); // store $access_token for later use

Categories