To post to facebook fan page, using a php script which is called by a cronjob, im using the following code, which worked yesterday while testing, it is no longer working.
include_once("../facebooksdk/src/facebook.php");
$facebook = new Facebook(array(
'appId' => 'XX',
'secret' => 'XX',
));
// Get User ID
$user = $facebook->getUser();
if ($user) {
try {
$page_id = 'XX';
$page_info = $facebook->api("/".$page_id."?fields=access_token");
if( !empty($page_info['access_token']) ) {
$args = array(
'access_token' => $page_info['access_token'],
'message' => "Welcome to TuneHub!"
);
$post_id = $facebook->api("/".$page_id."/feed","post",$args);
}
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
}
I cant figure out why it would work temporarily, then the following day when the code has been added to the live site, its no longer working (on the test or live site, it isnt working)
is there an API change that is killing the function?
or is there something I am doing wrong with the code that flagged Facebook to prevent it from posting?
(the code may have changed slightly from the script i had which was working, as ive been fiddling around with it to try and find the issue)
see
https://developers.facebook.com/docs/reference/api/page/#posts
Check your access token it may be expired, you need to have a valid access token with rights to post on wall, try getting the updated access token and try
Related
When I run this code, and my cookies have been cleared and I am not logged into facebook. It directs me to facebook and I log in but when it brings me back to my page it is the same, where as it should be show me profile pic and so on...
I seem to have narrowed down the problem of the return statement of the $user because it returns a 0. I have stared at this code for a long time and I havent found what I am doing wrong.
What do i need to change to get it so that When i return from logging in from facebook it will show the profile pic and so on...
<?php
require_once 'libs/facebook.php';
require 'connections/connection.php';
// Create our Application instance (replace this with your appId and secret).
$facebook = new Facebook(array(
'appId' => 'xxxxxxxxxxxxx',
'secret' => 'xxxxxxxxxxxxxxxx',
));
// Get User ID
$user = $facebook->getUser();
echo $user;
if ($user) {
try {
// Proceed knowing you have a logged in user who's authenticated.
$user_profile = $facebook->api('/me');
echo $user;
} 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();
$logoutUrl = $facebook->getLogoutUrl(array('next' => ($fbconfig['baseurl'] . 'logout.php')));
} else {
$statusUrl = $facebook->getLoginStatusUrl();
$loginUrl = $facebook->getLoginUrl(array(
'scope' => 'user_about_me',
'scope' => 'read_friendlists'
));
}
?>
Not to worry my friend, you are not doing anything wrong. I'm having same issue with my DEMO application which was running alright till yesterday.
I'm sure you are having issue with getting access token as well. I think issue is with PHP SDK only.So probably will be fixed in some time.
SOLUTION : This worked for me after trying for many solutions for this issue.
In base_facebook.php file, find the makeRequest() method and check for following Line.
$opts = self::$CURL_OPTS;
Immediately following it, add this line
$opts[CURLOPT_SSL_VERIFYPEER] = false;
More details can be found here - http://net.tutsplus.com/tutorials/php/how-to-authenticate-your-users-with-facebook-connect/
This question already has answers here:
Why is Facebook PHP SDK getUser always returning 0?
(26 answers)
Closed 8 years ago.
i spent all day searching for an answer.. but it seems that nothing can fix it.
i guess every version had a different issue...
well it's pretty simple, i have this code:
<?php
include_once("facebook.php"); //include facebook SDK
######### edit details ##########
$appId = '****'; //Facebook App ID
$appSecret = '****'; // Facebook App Secret
##################################
//Call Facebook API
$facebook = new Facebook(array(
'appId' => $appId,
'secret' => $appSecret,
'cookie' => true
));
$fbuser = $facebook->getUser();
if ($fbuser) {
// Do Something
}
else{
//Show login button for guest users
$loginUrl = $facebook->getLoginUrl(array('redirect_uri'=>$homeurl,'scope'=>$fbPermissions));
echo '<img src="images/facebook-login.png" border="0">';
}
?>
i get 0 in get user every time.
when i go to "login on facebook" and im not logged in, i get facebook login screen.
when i go to "login on facebook" and im logged in, facebook redirect me to my page and i get 0 in get user again.
i'm tring to run it on my localhost, maybe thats the problem?
hope someone can help..
thx
I had a similar problem using the same simple login script. I tried almost anything but nothing helped. (the weird thing was that the day before everything was working fine).
So started debugging the "base_facebook.php" and found that the function getAccessTokenFromCode failed without an exception (silently).
It turned out that the response of _oauthRequest gave an error message reply instead of the expected token reply:
$access_token_response =
$this->_oauthRequest(
$this->getUrl('graph', '/oauth/access_token'),
$params = array ('client_id' => $this->getAppId(),
'client_secret' => $this->getAppSecret(),
'redirect_uri' => $redirect_uri,
'code' => $code));
So by adding echo $access_token_response; directly after this function a found my problem.
The response error was that my app was configured as a Native/Desktop app.
After I changed it to Internet the getUser(); gave the correct user id.
I hope this helps.
Try this, it's a piece of code a classmate of mine wrote because I was struggling with FB login aswell. Worked for me.
<?php
session_start();
require_once 'facebook/facebook.php';
$facebook = new Facebook(array(
'appId' => '3525325', <- fake appID ofcourse, enter your own
'secret' => 'fauuf983f9f', <- fake secret, enter your own
));
$user = $facebook->getUser();
if ($user) {
try {
$_fb['user'] = $facebook->api('/me');
} catch (FacebookApiException $e) {
error_log($e);
$_fb['user'] = null;
}
}
if ($user)
{
$_fb['logouturl'] = $facebook->getLogoutUrl();
$_fb['authed'] = true;
echo '<h1>Logged in</h1>';
echo 'Fbid: '.$user;
echo "<br /><br /><pre>";
print_r($_fb['user']);
echo "</pre>";
}
else
{
$_fb['loginurl'] = $facebook->getLoginUrl(array('scope' => 'email'));
$_fb['authed'] = false;
echo 'Login with Facebook';
}
?>
<html>
<head>
<title>Login</title>
</head>
<body>
</body>
</html>
Hope it's of use to you. Good luck :) Facebook login caused me a lot of irritation :p
Documentation says:
"redirect_uri - (optional) The URL to redirect the user to once the login/authorization process is complete. The user will be redirected to the URL on both login success and failure, so you must check the error parameters in the URL as described in the authentication documentation. If this property is not specified, the user will be redirected to the current URL (i.e. the URL of the page where this method was called, typically the current URL in the user's browser)."
So there is a method to catch if user refused autnentication/permissions, but link to corresponding documentation doesnt exist anymore (https://developers.facebook.com/docs/authentication/).
For the simplicity, redirect_uri is same address as a starting php file, and the php code is as simple as:
require 'facebook.php';
$facebook = new Facebook(array(
'appId' => 'X',
'secret' => 'Y',
));
$user = $facebook->getUser();
if ($user) {
try {
$user_profile = $facebook->api('/me');
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
}
if (!$user) {
$params = array(
'scope' => 'read_stream, friends_likes',
'redirect_uri' => 'http://myapp.com/app'
);
$loginUrl = $facebook->getLoginUrl($params);
}
Anybody knows how to catch that information?
You can do following to check the permissions:
$permissions = $facebook->api("/me/permissions");
if( array_key_exists('publish_stream', $permissions['data'][0]) ) {
// Permission is granted!
// Do the related task
$post_id = $facebook->api('/me/feed', 'post', array('message'=>'Hello World!'));
} else {
// We don't have the permission
// Alert the user or ask for the permission!
header( "Location: " . $facebook->getLoginUrl(array("scope" => "publish_stream")) );
}
It should be noted that in the newest PHP facebook SDK, there is no method ->api. There also seems to be an issue using this check (sometimes) to get permissions. When using the older SDK, sometimes (randomly by user it seemed) some users were getting "OAuthException: (#412) User has not installed the application" even though a check on the FB access token debugger showed proper permissions. After I updated to new SDK, and figured out the new way to get a simple data list of permissions, everything worked again.
It took me a lot of digging in the FB website to find this solution, so I paste it here to hopefully save somebody else a few hours. They real life saver was my discovery of the getDecodedBody method (a very hard to find trick in FB docs). My example just checks for publish_actions.
$fb = new Facebook\Facebook([
'app_id' => your_app_id,
'app_secret' => your_secret,
'default_graph_version' => 'v2.2',
]);
$badperms=true; //start by assume bad permissions
try {
$response = $fb->get('/me/permissions', $at);
$perms = $response->getDecodedBody();
if($badperms){
foreach($perms['data'] AS $perm){
if($perm['permission']=='publish_actions' && $perm['status']=='granted') $badperms=false;
}
}
} catch(Facebook\Exceptions\FacebookResponseException $e) {
log("MSG-received facebook Response exception!! ".$e->getMessage());
} catch(Facebook\Exceptions\FacebookSDKException $e) {
log("MSG-received facebook SDK exception!! ".$e->getMessage());
}
if($badperms) {
//do something like reflow auth
}
I just had the same issue, I didn't know how to treat the cancel action (both in facebook php api and google oauth2).
The solution is much easier than expected.
The response in case of permission not accepted (at all) comes with at least one parameter/variable: error in the URL.
In facebook that response looks like:
error=access_denied&error_code=200&error_description=Permissions+error&error_reason=user_denied
for google you only get the
error=access_denied
but it should be enough.
I'm just checking if error is set and if it's set I am redirecting the response to my login page.
I hope it will help someone because it's really not documented this step.
By the way:
version of facebook API: v5
version of google API oAuth2: 2.0 (i think - google doc is really a mess when it comes to finding the latest versions)
I have been reading the Facebook documentation and I must be missing something, as I just cant understand how to get the access token for a page without actually logging in first. I am trying to create a PHP function using the PHP facebook API so that when I add new stories or tutorials on my site, my site's apps can then automatically post as the page a blurb about them on myy facebook page.
I have this function working but only when I get the access token from the Graph API Explorer, though the access tokens expire in about an hour. I can't seem to figure out how to programatically obtain the access_token for the page and query for a new one each time from within my PHP scripts so they don't expire and do not require user interaction.
function post_to_facebook($title, $message, $link, $picture) {
require '../facebook/src/facebook.php';
$page_token = 'xxx';
$page_id = 'xx';
$facebook = new Facebook(array(
'appId' => '<app_id>',
'secret' => '<app_secret>',
'cookie' => false,
));
$facebook->setAccessToken($page_token);
try {
$ret_obj = $facebook->api('/'.$page_id.'/feed', 'POST', array(
'caption' => $title,
'link' => $link,
'message' => $message,
'picture' => $picture
));
} catch(FacebookApiException $e) {
error_log($e->getType());
error_log($e->getMessage());
return false;
}
return true;
}
Can someone explain how I can go about retrieving the access token without manually having to look it up via graph api explorer or having a user login?
It's not possible.
The only correct (and legal) way to achieve the access token is with user interaction (through login process).
I'm tired of digging through tons of tutorials/documentations which don't help me at all.
What I have now (everything is placed inside admin control panel):
If user is logged on correct account (administrator of page with granted rights), everything works fine, post on page is posted as impersonated site.
If he is logged on other account, nothing happens. Site redirects him to his wall.
If he isn't logged on any account, he's redirected to facebook login - if he logs onto correct account, he returns to acp (it's bad solution, because it'll clear his form)
I want to achieve:
If logged in, everything as it was
Else popup with login to specific (correct) account
At the moment I'm using only PHP, but solution with JS is permitted.
My code:
<?php
/*(...)*/
$facebook = new Facebook(array(
'appId' => $apiid,
'secret' => $secret,
'cookie' => true,
));
$session = $facebook->getSession();
$me = null;
if ($session) {
try {
$uid = $facebook->getUser();
$me = $facebook->api('/me');
} catch (FacebookApiException $e) {
error_log($e);
}
if($me) {
//In order to post to the page later on we need to generate an Access Token for that page, to do this we get me-accounts in the following api call
$accounts = $facebook->api('/me/accounts');
//Loop through the array off accounts to find the page with a matching ID to the one we need
foreach($accounts['data'] as $account){
if($account['id'] == PAGEID){
$ACCESS_TOKEN = $account['access_token'];
}
}
}
$message=$data['facebook_text'];
$attachment = array(
'message' => $data['facebook_text'],
'name' => $data['name'],
'description' => '',
'link'=>$someurl,
'access_token' => $ACCESS_TOKEN
);
if($image_url != NULL) $attachment['picture'] = $image_url;
try {
if($facebook->api('/PAGEID/feed', 'post', $attachment))
{
//other stuff
}
} catch (FacebookApiException $e) {
error_log($e);
//other stuff
}
}
else
{
$login_url = $facebook->getLoginUrl();
header("Location: $login_url");
exit;
}
/* (...) */
?>
Solution can't redirect anywhere, because it's inside form, so all data'll be lost.
I'm not really sure I understand what you want to do here, but this is what I use in a similar situation:
$session = $this->get_admin_session_of_page ($page_id);
$session = unserialize ($session);
$facebook->setSession ($session, false);
In the facebook php SDK there is a method to manually set the session, setSession. I save the page admin user session in DB with serialize, with the offline access and manage pages permission. Then when you need some admin privileges for the application you just unserialize it, and then use setSession. The second parameter is set to FALSE, so that this session is not saved in a cookie and logout the current user.
This way it's not important who is logged in, the work is always done as an admin of the page. I think this is safe to use in an automated script, for example to upload a user photo in a page album.
Of course, you must use caution with this if it gets more involved then that, or implement your own security.