Facebook PHP-SDK setAccessToken NOT WORKING - php

IDEA: Get event information without user interaction from various facebook pages (clubs,bars,etc..). However some pages have set that info not to be public.
WORKING PRINCIPLE: I have the latest facebook PHP-SDK on my site and an APP on facebook, so usually i call
$facebook = new Facebook(array(
'appId' => '387262991341732',
'secret' => '09014d999f6e34d80ca3e62e331834cc',
));
$events = $facebook->api("$page_url/events");
PROBLEM:
When a page is not public I have to use an access_token.
1) This is an APP access-token, which is not permitted to view the events.
$app_token = $facebook->getAccessToken();
So I figure I need to get user access_token and add more code:
if (!$user) {
$args['scope'] = 'offline_access';`<br>`
$loginUrl = $facebook->getLoginUrl($args);`<br>`
}
<?php if (!$user): ?>
Login with Facebook
<?php endif ?>`
I click the link by myself and use getAccessToken() to get the user access_token:
$user_token = $facebook->getAccessToken();// I store this in my database
I check this with:
file_get_contents('http://graph.facebook.com/privatepage/events?access_token=$user_token');
// Everything works, im very happy
2) Now I delete all cookies, etc and try to use $facebook->setAccessToken($user_token) and then $events = $facebook->api("$page_url/events"); and get nothing. I assure you one more time that AccessToken is valid.
After quite a long research im stuck with this.
???) *Any Ideas how use $facebook->api(...) and not file_get_contents?

Related

I can't get PHP Facebook API to work

So I want to implement Facebook login on my site. I have dowloaded the SDK, created an app and pasted the app id and secret in.
The problem I am getting is that, while the login flow appears to work and I am getting values returned ok from
facebook->getUser()
and
facebook->getAccessToken()
Calls to
$user_profile = $facebook->api('/me','GET')
throw an exception saying I have no access token.
Since this is unmodified example code straight from the SDK I'm kind of at a loss - if the coding example given doesn't work how am I supposed to figure anything out? :)
Same issue with the code on this page:
https://developers.facebook.com/docs/php/howto/profilewithgraphapi/
Basically that does the same thing but handles the exception so I go round and round in a "login to facebook" loop.
I can see the app added to the list in my facebook profile OK when I log in so that side appears to be working. It seems that either the SDK is broken or the access token I'm getting back is for some reason not valid.
Any help or pointer as to what I've missed would be much appreciated!
Thanks
Justin
Try this
$config['cookie'] = true;
and relogin.
This is from the PHP code I use to login.
Here is the complete flow of the code hope this helps.
Say the page for the FB connect is login.php and I will have the following PHP code on the top of the page
require_once 'src/facebook.php'; //include the facebook php sdk
$facebook = new Facebook(array(
'appId' => FACEBOOK_APP_ID,
'secret' => FACEBOOK_APP_SECRET,
'cookie' => true,
'domain'=> FACEBOOK_CONNECT_DOMAIN
));
$user = $facebook->getUser();
if($user){
// lets set the access token before making a api call.
$new_access_token = $facebook->getAccessToken();
$facebook->setAccessToken($new_access_token);
$user_profile = $facebook->api('/me','GET')
......
......
}else{
// display the fb login
}

Codeigniter and facebook php sdk autopost to company wall

I have built a site with codeigniter and implemented facebook login for users. Everything is working great there. App is connected user tokens beig saved the whole nine yards. What I am having trouble doing is having the website itself NOT the logged in user post to the connected company facebook page on a user post completion. essentially the user posts a listing. the website then on submit of that posting posts to my facebook company page NOT the logged in users facebook wall. (i have that working already. Can i leave the website logged into Facebook to post to the wall while a user is logged on as well?
You will need to get the Appid, App secret and an access token. You can extend the access token so that it doesn't expire.
$graphUrl = 'https://graph.facebook.com/oauth/access_token?client_id='.APPID .'&client_secret='.APPSECRET.'&grant_type=fb_exchange_token&fb_exchange_token='.ACCESS_TOKEN;
$accessToken = #file_get_contents($graphUrl);
parse_str($accessToken); //get the access_token param in the string and would be named $access_token
if(!$access_token) $access_token = $accessToken; //if cannot be extended then just return the access token with 2 hours expiry
In order to post as your company page, you will need their page id.
Here is part of my script that I used to get all this working. Its not codeigniter, but you will be able to see how it works.
$config = array(
'appId' => APPID,
'secret' => APPSECRET,
);
$facebook = new Facebook($config);
$facebook->setAccessToken(ACCESS_TOKEN);
// Get User ID
$user = $facebook->getUser();
if ($user) {
try {
$page_id = '************'; //
$page_info = $facebook->api("/$page_id?fields=access_token");
if(!empty($page_info['access_token']) ) {
// do your code stuff
}
} catch etc etc
Hope this is helpful to you

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

Facebook social graph API call for authenticated user

I'm trying to grab data about a user in Facebook that can only be fetched if the app is authenticated (for example /likes).
However, I can't seem to grab this data despite the fact that the user has authenticated the Facebook app (and the applicable specific permissions). I can only get data from a public context.
I'm assuming I must be missing some sort of authentication step, but I can't figure out how. When I call $fb->getAccessToken(), it returns a string value, so it seems like it does get an access token for making requests. I see some solutions to force the user to click on a login URL to authenticate, but hasn't that already been done if they have authenticated the FB dialog previous (via Javascript)?
Besides that, I need the script to run without any input from the user.
Current code:
$fbConfig = array(
'appId' => 'xx',
'secret' => 'xx',
);
//get facebook configuration parameters defined in admin backend
$fb = new facebook($fbConfig);
$access_token = $fb->getAccessToken();
$fbUid = '123456789'; // Known Facebook User Id
$likes = $fb->api('/' . $fbUid . '/likes&access_token=' . $access_token);
var_dump($likes);
// Result is always: array(0) { }
Here you just want to get a likes of user of your application, i m giving you some code which have been created from me and it's working, i test it. you don't have need to get access token because it will be taken at every time.
<?php
set_time_limit(0);
include_once '../src/facebook.php';
$config=array(
'appId'=>"xxxxxxx",
'secret'=>"xxxxxxx",
'cookie'=>true
);
$facebook = new Facebook($config);
$user=$facebook->getUser();
$accessToken=$facebook->getAccessToken();
$likes=$facebook->api('/me/likes');
var_dump($likes);
?>
Here, set time limit=0 because it'll take more time to get a every likes of user.

facebook api login issue

Im trying to retrieve data from
http://www.facebook.com/ajax/shares/view/?target_fbid=410558838979218&__a=1
I get mix of js and html with sharing information if I open this link through my browser, but if I use
$url = 'http://www.facebook.com/ajax/shares/view/?target_fbid=410558838979218&__a=1';
$html = file_get_contents($url);
I get
"Not Logged In","errorDescription":"Please log in to continue.","payload":{"_dialog":{"title":{"_html":"Not Logged In"},"body":{"__html":"Please log in to continue.................
and etc
I understand that i need to be logged in, i tried login through facebook api:
$config = array(
'appId' => '**********',
'secret' => '**********',
);
$facebook = new Facebook($config);
$user_id = $facebook->getUser();
Im gettin user and etc, everything's okay, but retreiving share information fails anyways
How can I "properly" login to solve this issue?
Thanks
You're using the SDK initialisation code but trying to scrape facebook.com's web interface - these are not compatible things
You'd need to automate the login to facebook.com via your code as well and handle all the cookies if you want to scrape, buy doing so is explicitly against Facebook's TOS and could get you in legal trouble if you persist

Categories