I have some facebook php code that worked flawlessly before the 4/30/15 upgrade. I upgraded my code, it seems to work on certain computers but not on others. On computers that it doesn't work on I've tried multiple browsers with the same result. I am able to log into Facebook using the SDK, but it won't post anything to my page's wall. Same code, different computer, and everything works fine. Here's the code:
<?php
$facebook = new Facebook(array(
'appId' => '##########',
'secret' => '##########',
'fileUpload' => true
));
$user = $facebook->getUser();
if ($user) {
try {
$user_profile = $facebook->api('/me');
}
catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
}
if ($user) {
$logoutUrl = $facebook->getLogoutUrl(array(
'next' => ($user['baseurl'] . 'logout.php')
));
} else {
$loginUrl = $facebook->getLoginUrl(array(
'scope' => 'publish_pages , manage_pages'
));
}
$access_token = $facebook->getAccessToken();
$params = array(
'access_token' => $access_token
);
#The id of the fanpage
$fanpage = '############';
#The id of the album
$album_id = '############';
if ($user) {
$accounts = $facebook->api('/me/accounts', 'GET', $params);
foreach ($accounts['data'] as $account) {
if ($account['id'] == $fanpage || $account['name'] == $fanpage) {
$fanpage_token = $account['access_token'];
}
}
$message = 'Post this to the wall.';
$img = 'path to image.jpg';
$args = array(
'message' => $message,
'image' => '#' . $img,
'aid' => $album_id,
'no_story' => 0,
'access_token' => $fanpage_token
);
$photo = $facebook->api($album_id . '/photos', 'post', $args);
}
?>
Most permissions need to get approved by Facebook before they can be used for any user, else they only work for users with a role in the App. Check out the docs about Login Review.
You can only use publish_pages and manage_pages as App Admin/Developer/Tester without review.
If you only test with those users and it still does not work, debug the Access Token in the Debugger and see if those permissions are really authorized: https://developers.facebook.com/tools/debug/
Edit: After reading your comment, i believe you are trying to use a User Token. Use /me/accounts to get a Page Token and try again with that one. If you debug the Token, make sure the Page shows up too.
Related
I'm using the Facebook API connected script written in PHP (provided by Facebook). Everything works, it generates the login URL and redirects me back to the website when I'm logged in.
However, the $user variable seems to be undefined.
Have anyone experienced a similar problem? In the Facebook Apps statistics page I can see that the app has been used.
Update - The code:
<?php
$app_id = "xxxxxxxxxxxxxx";
$app_secret = "xxxxxxxxxxxxx";
$site_url = "http://xxx";
try{
include_once "src/facebook.php";
}catch(Exception $e){
error_log($e);
}
$facebook = new Facebook(array(
'appId' => $app_id,
'secret' => $app_secret
));
if($user = $facebook->getUser())
{
echo 'ok';
}
else
{
}
if($user){
//==================== Single query method ======================================
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;
}
//==================== Single query method ends =================================
}
if($user){
// Get logout URL
$logoutUrl = $facebook->getLogoutUrl();
}else{
// Get login URL
$loginUrl = $facebook->getLoginUrl(array(
'scope' => 'email,user_birthday,user_about_me',
'redirect_uri' => $site_url . '/auth_complete.php',
));
}
if($user){
// Proceed knowing you have a logged in user who has a valid session.
//========= Batch requests over the Facebook Graph API using the PHP-SDK ========
// Save your method calls into an array
$queries = array(
array('method' => 'GET', 'relative_url' => '/'.$user),
array('method' => 'GET', 'relative_url' => '/'.$user.'/home?limit=50'),
array('method' => 'GET', 'relative_url' => '/'.$user.'/friends'),
array('method' => 'GET', 'relative_url' => '/'.$user.'/photos?limit=6'),
);
// POST your queries to the batch endpoint on the graph.
try{
$batchResponse = $facebook->api('?batch='.json_encode($queries), 'POST');
}catch(Exception $o){
error_log($o);
}
//Return values are indexed in order of the original array, content is in ['body'] as a JSON
//string. Decode for use as a PHP array.
$user_info = json_decode($batchResponse[0]['body'], TRUE);
$feed = json_decode($batchResponse[1]['body'], TRUE);
$friends_list = json_decode($batchResponse[2]['body'], TRUE);
$photos = json_decode($batchResponse[3]['body'], TRUE);
//========= Batch requests over the Facebook Graph API using the PHP-SDK ends =====
}
?>
I'm not entirely sure why it worked, but I redirected the user to a page where the Javascript SDK is included (http://developers.facebook.com/docs/reference/javascript/), and now it's working!
The user have not authorized the app yet. Try something like this-
$user_id = $facebook->getUser();
echo $uid;
if($user_id){
try {
$user_profile = $facebook->api('/me');
} catch (FacebookApiException $e) {
error_log($e);
$user_id = null;
}
}else{
$login_url = $facebook->getLoginUrl();
echo("<br>login url=".$login_url);
};
An FB app of ours that previously worked for months is now experiencing the issue you speak of. $fb_user is now being returned undefined. =(
Update your SDK, sounds like you are hitting a certificate issue from a few weeks back.
You can find the latest version at https://github.com/facebook/facebook-php-sdk/
I finally got facebooks graph api to post messages on my fan PAGE as page
How do i get it to post large images as a post, not as a link?
'source' => $photo seems to create a thumbnail
this is what i have so far
<?php
$page_id = 'YOUR-PAGE-ID';
$message = "I'm a Page!";
$photo = "http://www.urlToMyImage.com/pic.jpg";
require '../src/facebook.php';
// Create our Application instance (replace this with your appId and secret).
$facebook = new Facebook(array(
'appId' => 'YOUR-APP-ID',
'secret' => 'YOUR-SECRET-ID',
));
$user = $facebook->getUser();
if ($user) {
try {
$page_info = $facebook->api("/$page_id/?fields=access_token");
if( !empty($page_info['access_token']) ) {
$facebook->setFileUploadSupport(true); // very important
$args = array(
'access_token' => $page_info['access_token'],
'message' => $message,
'source' => $photo
);
$post_id = $facebook->api("/$page_id/feed","post",$args);
}
} 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(array( 'next' => 'http://mydomain.com/logout_page.php' ));
} else {
$loginUrl = $facebook->getLoginUrl(array('scope'=>'manage_pages,publish_stream'));
}
?>
The problem here is that you are in actual fact not posting a photo. What you are doing is posting a link to that photo so what you see is indeed a thumbnail preview image that Facebook retrieved from that URL.
What you'll want to do is provide a full path to a file on your server prefixed with the # symbol. The topic has been discussed on the site quite a bit so I'll just point you in the direction of a canonical post dealing with uploading of images to Facebook with the PHP SDK
Upload Photo To Album with Facebook's Graph API
The code looks like this -
$facebook->setFileUploadSupport(true);
$params = array('message' => 'Photo Message');
$params['image'] = '#' . realpath($FILE_PATH);
$data = $facebook->api('/me/photos', 'post', $params);
I have an app which has been running for a while which has only requested some account information for login purposes. Now I want to use it to publish to the stream. I have added publish_stream to the req_perms but, it still doesn't ask for that permission.
Am I missing something?
<?php
# CREATE FACEBOOK BUTTON
$facebook = new Facebook(array(
'appId' => FACEBOOKAPPID,
'secret' => FACEBOOKSECRET,
'cookie' => false,
));
$fb_session = $facebook->getUser();
$fb_me = null;
// Session based API call.
if ($fb_session) {
try {
$fb_uid = $fb_session;
$fb_me = $facebook->api('/me');
$fb_me['photo'] = 'http://graph.facebook.com/'.$fb_uid.'/picture?type=large';
$_SESSION['login_api'] = 1;
$_SESSION['login_api_details'] = $fb_me;
$_SESSION['login_api_user_id'] = $fb_uid;
# WE ARE GOOD TO GO, LETS GET THE ACCESS TOKEN
$_SESSION['access_token'] = $facebook->getAccessToken();
#header_redirect(SITEURL.'/login');
} catch (FacebookApiException $e) {
error_log($e);
}
}
else{
# LOGIN URL FOR FACE BOOK & request extra stuff
$fb_login_url = $facebook->getLoginUrl(array('req_perms'=>'publish_stream,email,user_about_me,user_birthday,user_website'));
header_redirect($fb_login_url);
}
?>
Try this in your else
$params = array(
'canvas' => 1,
'scope' => 'publish_stream,email,user_about_me,user_birthday,user_website',
'fbconnect' => 1,
'redirect_uri' => 'https://apps.facebook.com/YOURAPP',
);
$fb_login_url = $facebook->getLoginUrl($params);
header_redirect($fb_login_url);
Nothing gets posted to the wall, execution gets out of try after $result = $facebook->api('/me/feed/','post',$attachment); statement, any idea whats broken.
$facebook = new Facebook(array(
'appId' => 'xxxxxxxxxxxx',
'secret' => 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
));
// Get User ID
$user = $facebook->getUser();
if ($user) {
try {
// Get the user profile data you have permission to view
$user_profile = $facebook->api('/me');
$uid = $facebook->getUser();
$url = $facebook->getLoginUrl(array(
'canvas' => 1,
'fbconnect' => 0,
'req_perms' => 'email,publish_stream,status_update,user_birthday,user_location,user_work_history'));
$attachment = array
(
'access_token'=>$facebook->getAccessToken(),
'message' => 'I had a question: should I write a PHP facebook app that actually worked?',
'name' => 'I Asked Bert',
'caption' => 'Bert replied:',
'link' => 'http://apps.facebook.com/askbert/',
'description' => 'NO',
'picture' => 'http://www.facebookanswers.co.uk/img/misc/question.jpg'
);
echo "Test 1";
$result = $facebook->api('/me/feed/','post',$attachment);
echo "Test 2";
$_SESSION['userID'] = $uid;
} catch (FacebookApiException $e) {
$user = null;
}
} else {
die('Somethign Strange just happened <script>top.location.href="'.$facebook->getLoginUrl().'";</script>');
}
Test 1 is printed but not Test 2.
You said you were looking for updated documentation, did you check Facebook PHP-SDK FAQ?
Specifically,
How to authorize and have any of the following permissions?
How to post on a wall?
After you create an Application instance get your $user first
$user = $facebook->getUser();
From here, following the instructions from "How to authorize and have any of the following permissions?" using the scope
$par = array();
$par['scope'] = "publish_stream";
Check the user state to see which login/logout method is required passing the publish_stream permission
if ($user) {
$logoutUrl = $facebook->getLogoutUrl();
} else {
$loginUrl = $facebook->getLoginUrl($par);
}
Then place the attachment as explained in "How to post on a wall?"
if ($user) {
$attachment = array('message' => 'this is my message',
'name' => 'This is my demo Facebook application!',
'caption' => "Caption of the Post",
'link' => 'http://mylink.com/ ',
'description' => 'this is a description',
'picture' => 'http://mysite.com/pic.gif ',
'actions' => array(array('name' => 'Get Search',
'link' => 'http://www.google.com/ '))
);
try {
// Proceed knowing you have a user who is logged in and authenticated
$result = $facebook->api('/me/feed/','post',$attachment);
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
}
As explained in the example app, put in a try/catch block to see what data is available depending on whether the user is logged in or not when making API calls.
A call such as
$cocacola = $facebook->api('/cocacola');
Will always work since it is publicly available.
Here are a couple of notes:
You are using the new PHP-SDK so don't use req_perms use scope instead
Put your /me/feed post call inside the try
You don't need to call getUser() twice, the user id is already in the $user
The user id will be already in the session, with key that looks like: fb_XXXXXXX_user_id where XXXXXXX is your app id
session already started..
below code surely works: even if you dont have permission it will try to get them
$facebook = new Facebook(array(
'appId' => 'xxxxxxxxxxxxxxxxxx',
'secret' => 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
));
$user = $facebook->getUser();
$user_profile = $facebook->api('/me');
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!'));
$post_id = $facebook->api('/me/feed', 'post', $attachment);
} else {
// We don't have the permission
// Alert the user or ask for the permission!
echo "Click Below to Enter!";
header( "Location: " . $facebook->getLoginUrl(array("scope" => "publish_stream")) );
}
*Warning
as of sept 5 2011 this is working, but i saw on fb documentation they are changing method to poste on users wall and are discouraging use of publish stream. but its working for now
I have developed a Facebook application that runs inside an iframe in the Facebook canvas. For it to work properly I request extended permissions from the user. If the user hasn't authorized the application I send him/her to a login page with the getLoginUrl() method in the PHP SDK.
It works, but it's not pretty. The method sends the user to a landing page before the authentication page. It looks like this:
When I click "Go to Facebook.com" I see the actual page for permission requests (I also get right to the permissions page if I print the url, copy it and enter it into a new browser window). How do I make Facebook skip this step when I do the redirect from an Iframe?
My code looks like this (using CodeIgniter and Facebook PHP SDK):
$this->facebook = new Facebook(array(
'appId' => '{MY_APP_ID}',
'secret' => '{MY_SECRET}',
'cookie' => TRUE,
'domain' => $_SERVER['SERVER_NAME']
));
$this->facebook->getSession();
try {
$this->me = $this->facebook->api('/me');
}
catch (FacebookApiException $e) {
$this->me = NULL;
}
if ( is_null($this->me) ) {
redirect($this->facebook->getLoginUrl(array(
'req_perms' => 'offline_access,read_stream,publish_stream,user_photos,user_videos,read_friendlists',
'next' => $this->config->item('base_url').'fblogin.php?redirect_uri='.$this->uri->uri_string()
)));
}
I think you need to redirect the parent frame (i.e. _top) rather than the iFrame itself?
The way I do it is set up an INDEX.PHP file with the following
//if user is logged in and session is valid.
if ($fbme){
//fql query example using legacy method call and passing
parameter
try{
$fql = "select name, hometown_location, sex,
pic_square from user where uid=" .
$uid;
$param = array(
'method' => 'fql.query',
'query' => $fql,
'callback' => 'http://apps.facebook.com/yoursite/'
);
$fqlResult = $facebook->api($param);
}
catch(Exception $o){
d($o);
}
}
Then point your canvas url to http://yoursite.com/INDEX.php
The callback url in the above code which will be in INDEX.PHP sets where to look after permissions are granted.
FBMain.php looks like this
//set application urls here
$fbconfig['http://www.yoursite.com/iframeapp/YOURMAINPAGE.php/']
= "http://www.tyoursite.com/YOURMAINPAGE.php/";
$fbconfig['http://apps.facebook.com/CANVASBASEURL']
= "http://apps.facebook.com/CANVASBASEURL";
$uid = null; //facebook user id
try{
include_once "facebook.php";
}
catch(Exception $o){
echo '<pre>';
print_r($o);
echo '</pre>';
}
// Create our Application instance.
$facebook = new Facebook(array(
'appId' => $fbconfig['APPID'],
'secret' => $fbconfig['SECRET'],
'cookie' => true,
));
//Facebook Authentication part
$session = $facebook->getSession();
$loginUrl = $facebook->getLoginUrl(
array(
'canvas' => 1,
'fbconnect' => 0,
'req_perms'=>'email,publish_stream,status_update,user_birthday,user_location'
)
);
$fbme = null;
if (!$session) {
echo "<script type='text/javascript'>top.location.href
= '$loginUrl';";
exit;
}
else {
try {
$uid = $facebook->getUser();
$fbme = $facebook->api('/me');
} catch (FacebookApiException $e) {
echo "<script type='text/javascript'>top.location.href
= '$loginUrl';";
exit;
}
}
function d($d){
echo '<pre>';
print_r($d);
echo '</pre>';
} ?>
Hope its a little clearer. It took me a while to figure it out, but I got there, thought I would help.