Uploading an image to a specific Facebook Album - php

I am having trouble using permissions to upload to a specific Facebook album.
I am set to an admin to a specific Facebook page, however whenever I try to upload a photo I cannot seem to get access to do it.
The error I get is:
Fatal error: Uncaught OAuthException: (#120) Invalid album id thrown
If I explore using the Graph explorer, I can see this album without any access token required.
The URL I am using is https://graph.facebook.com/albumId/photos
The album I am trying to upload is an album within a Facebook page, which I created within Facebook.
The permissions I have set are:
user_photos
friends_photos
publish_actions
manage_pages
publish_stream
photo_upload
Any help appreciated.

First, check if the user is logged in:
function getLoginStatus() {
FB.getLoginStatus(function (response) {
if (response.status === 'connected') {
// the user is logged in and connected to your
// app, and response.authResponse supplies
// the user's ID, a valid access token, a signed
// request, and the time the access token
// and signed request each expire
var uid = response.authResponse.userID;
var accessToken = response.authResponse.accessToken;
getPageAccess();
} else if (response.status === 'not_authorized') {
// the user is logged in to Facebook,
//but not connected to the app
logIn();
} else {
// the user isn't even logged in to Facebook.
logIn();
}
});
}
Then get the page access token associated to the user:
function getPageAccess() {
FB.api('/PAGE_ID?fields=access_token', function (resp) {
var pageAccessToken = resp.access_token;
});
}

This seems a common issue. If you want to impersonate Facebook Page (that is, act as page itself for uploading, posting and sharing) you have to first obtain an access token for that page:
Issue a GET Request to '/me/accounts' using user access token
Loop the result set and look for the page (pay attention to category property of each item, skip "application" as it's considered an account)
Store access token for that page.
Then (using PHP SDK):
$page = '432652662'; // Your page id
$album = '128949205'; // Your album id
$source = 'mypic.png';
$payload = array('source' => '#' . $source,
'access_token' => 'page access token');
// Upload photo for specific page and album
$sdk->api("/$page/$album/photos", 'POST', $payload);

Ok, I think I have found the solution.
If you go to https://graph.facebook.com/me/accounts
Each account will have its own access_token. When uploading an image to a Facebook page, you will need to pass that access_token as a parameter.

Related

This does not let the app post to Facebook php

I am creating a Facebook app through php. I am using the following code for users to add the app:
$config = array();
$config['appId'] = '532241193565136';
$config['secret'] = '19de17575ad3d245c8cc32f5b623e310';
$config['cookie'] = true;
$config['fileUpload'] = true; // optional
$fb = new Facebook($config);
$user = $fb->getUser();
$loginUrl = $fb->getLoginUrl(
array(
'scope' => 'publish_actions'
)
);
This should allow users to post to Facebook through the app. The problem I'm having is the Permissions popup does not allow users to select the type of Publish Permission - Public, Custom, Only Me etc. I always get This does not let the app post to Facebook
Posts are being added to the Facebook Page but obviously they are private to the user who added the post.
Not sure if I'm missing something here...
Update:
I've tried deleting the application and adding a new, did not make any difference though.
Update 2:
I've just tried using the application from an Admin User of the Page...The following permissions have not been approved for use and are not being shown to people using your app: publish_actions
Information Update:
Just in case someone stumbles on this question. Facebook's Review Guidelines states that "The review time estimate will range between 7 to 14 business days." Always important to consider these delays :)
You're missing nothing here. From v2.0 onwards, the permissions other than public_profile, email and the user_friends need to the submitted for review before you can make your app live; until then, only the testers/admin/developers of the app will be able to test app with those permissions.
Since you are the admin of your app, you can test the publishing but-
it will be visible to you or other admins/testers/developers only
you'll not see the provacy setting option because that does not makes sense
For the login submission (after your app is ready to be live) see this link.
If your submission was rejected you can post using the Feed Dialog, the Requests Dialog or the Send Dialog. Your app does not need to request the publish_actions permission for that. It's an alternative. (see the publish_actions permission reference).
function publish() {
FB.api('/<albumid>/photos', 'POST',
{"url": 'example.com/image.jpeg',
"caption": 'text'
},
function(response) {
if (!response || response.error) {
// Error trying post method - now trying a feed dialog
FB.ui({message: text,
method: 'feed',
link: 'example.com',
picture: 'example.com/image.jpeg',
caption: text,
}, function(response){
//successful feed dialog without publish_actions permission
});
} else {
//successful post with publish_actions permission
}
});
}

Retrieving Facebook FanPage insights in a cron

I'm trying to create a cron job with a php script for retrieving info about stats of a Fan Pages and I have some questions:
have I to log a user to get the access token and use the Facebook API?
Which kind of token must to use? App token? Page Token?
I've read in several posts in Stackoverflow that only the Page Access token is necessary, but I have no success:
Request: /419788471442322/?fields=access_token
Response: Unsupported get request.
This is the code
//get the app access token
$facebook->setAccessToken($facebook->getAccessToken());
//Format the api call
$fields = array('access_token');
$page_info = $facebook->getInsights($id,"",$fields);
//display the result
print_r($page_info);
public function getInsights($id, $nameapi, $fields = array(), $limit = null)
{
if (isset($fields)) $fields = implode(",",$fields);
if (isset($limit)) $limit = "&limit=".$limit;
try {
echo '/'.$id.'/'.$nameapi.'?fields='.$fields.$limit;
$fbdata = $this->facebook->api('/'.$id.'/'.$nameapi.'?fields='.$fields.$limit);
} catch (FacebookApiException $e) {
$fbdata = $e->getMessage();
}
return $fbdata;
}
By default, the App Access Token will be used and you don´t need to set it with setAccessToken.
The App Access Token is good enough for basic infos and the Page feed, but for getting access to the Insights you need a Page Access Token and that´s a bit more complicated. Actually, in a Cron Job you would need a Page Access Token that is valid forever, basic ones are only valid for 2 hours. "Extended Page Access Token" is exactly what you need.
More info about Access Tokens and how to get an Extended Page Access Token:
https://developers.facebook.com/docs/facebook-login/access-tokens/
http://www.devils-heaven.com/facebook-access-tokens/

My facebook tab app cannot post photo to page's wall when used by user NOT admin

Alright, here's what I'm facing:
I have made an app for my facebook fan page, my app is a Facebook Page Tab app.
I have added the application to my facebook page by following:
http://developers.facebook.com/docs/appsonfacebook/pagetabs/
respectively, entering:
http://www.facebook.com/dialog/pagetab?app_id=YOUR_APP_ID&next=YOUR_URL
and choosing which page to be added to.
When I have done this I did it with my Facebook Page Admin user.
I have allowed manage_pages and publish_stream and publish_actions permissions.
Here is my code:
$objFacebook = App_Utils_Facebook::getFacebook();
$user_id = $objFacebook->getUser();
$objFacebook->setFileUploadSupport(true);
if(isset($_REQUEST['pageId'])){
$arrPriv = $objFacebook->api("/".$_REQUEST['pageId']."/", array('fields'=>'access_token'));
$link = 'http://link/here/'.$this->objAnunt->id;
}
$privacy = json_encode(array('value'=>'SELF'));
if(isset($arrPriv['access_token'])){
$access_token = $arrPriv['access_token'];
}else{
$access_token = $objFacebook->api("/".$_REQUEST['pageId']."/", array('fields'=>'access_token'));
}
if($user_id){
try{
$ret=$objFacebook->api("/".$arrPriv['id']."/photos",'POST',array(
'source'=>'#link/to/pic.jpg',
'message'=>$strTitle.'
For more details click here '.$link,
'access_token'=>$access_token,
'privacy'=>$privacy
)
);
unlink('link/to/pic.jpg');
}catch(FacebookApiException $e) {
echo $e;
}
}else{
$permissions = $objFacebook->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: " . $objFacebook->getLoginUrl(array("scope" => "publish_stream, manage_pages")) );
}
}
So I repeat myself, I want to allow the average user to access my application and THE PAGE ITSELF to post on it's own wall.
Can I do it? If not are there any alternatives.
Thank you for your time and patience to help me figure this out!
As far as I know, you do not need the manage_pages permission to post to a page.
Please see this documentation.
Making an API call to /{page_id}/feed using a valid user access_token should be enough to post to a page's feed.
As mentioned in the comments, Facebook probably doesn't allow a common user to upload photos to a page's albums. You'll need an access_token from an admin of that page (ensuring that the manage_pages permission is granted), retrive the page access token, and upload photos that way.
That page access token should be good for the life of the user access token.

Re-Authenitcating a facebook user once logged in

Given that a Facebook user has logged in at some point in your Facebookapp (using fb.login) and that user has been saved in the database. How can you let the user re-authenticate with you app again after the accesstoken has expired (fb.api('/me') fails).
The signed request holds the user id, but how do you log in the user from there?
I'm using the PHP sdk and I basicly check with FB.api('/me') right in the beginning to either direct to a welcome page or the users page. But FB return false in some cases, usually after a day or 2. So I started to think it was because of the Accesstoken has expired. I have no clue how to re-authenticate, I only have knowledge that the user id still resides in the signed request.
Put following code in your javascript...it will open login popup if user is not logged in
FB.getLoginStatus(function(response) {
if (response.authResponse) {
fbUserId = response.authResponse.userID;
token = response.authResponse.accessToken;
} else {
FB.login(function(response) {
if (response.authResponse) {
fbUserId = response.authResponse.userID;
token = response.authResponse.accessToken;
}
else {
console.log('User cancelled login or did not fully authorize.');
}
});
}
},true);
Use the Javascript SDK to prompt the user to login via Facebook:
https://developers.facebook.com/docs/reference/javascript/FB.login/
Alternatively, you could try storing the code returned by Facebook during server-side auth and use it to request a new token when the user returns.

How do you get the email using facebook api?

I'm using this code but I can't figure out how to get the email from the user. I know you must get special permission from the user but I don't know how.
I can get the public data from the user but that's not what I even need. The only thing I need is the email.
I guess it's something with this line:
$me = $facebook->api('/me');
I have read the documentation but I still don't know how I can get the email. How do I get the email from the user loggin in on my website with the facebook api?
You first need to request an extended permission "Email" from the user. You can do this using FB JS SDK by calling FB.login(), or PHP FB SDK by redirecting the browser by calling getLoginUrl().
FB JS SDK: FB.login method
FB.login(function(response) {
if (response.session) {
if (response.perms) {
// user is logged in and granted some permissions.
// perms is a comma separated list of granted permissions
} else {
// user is logged in, but did not grant any permissions
}
} else {
// user is not logged in
}
}, {perms:'email'});
FB PHP SDK method:
$login_url = $Facebook->getLoginUrl(array(
'canvas' => 1,
'fbconnect' => 0,
'req_perms' => 'email'
));
echo '<script type="text/javascript">top.location.href = "'.$login_url.'";</script>';
exit();
Once you have the required permission, you can then call this in your PHP:
$me = $facebook->api('/me?fields=email');

Categories