How get albums pictures, friends count by Facebook graph API? - facebook

I am using facebook graph SDK to access facebook user's album pictures, profile picture, friends count and other basic information of user. But it is doing strange things, it is showing albums of only of API account owner's account, instead of showing of any user login by facebook.
I am using following code, please someone help me and guide where I am going wrong.
Thank you very much.
include_once(BASE_DIR.'/utils/facebook/autoload.php');
$fb = new Facebook\Facebook(array(
'app_id' => $fb_app_id,
'app_secret' => $fb_app_secret,
));
$helper = $fb->getRedirectLoginHelper();
foreach ($_SESSION as $k=>$v) {
if(strpos($k, "FBRLH_")!==FALSE) {
if(!setcookie($k, $v)) {
} else {
$_COOKIE[$k]=$v;
}
}
}
$permissions = array('email', 'user_photos', 'user_friends', 'read_custom_friendlists', 'user_status');
$loginUrl = htmlspecialchars($helper->getLoginUrl(SITE_URL . '/sign-up.php?do=fb', $permissions));
$_SESSION['fui'] = array();
foreach ($_COOKIE as $k=>$v) {
if(strpos($k, "FBRLH_")!==FALSE) {
$_SESSION[$k]=$v;
}
}
if( isset($_GET['do']) && $_GET['do'] == 'fb' ){
foreach ($_COOKIE as $k=>$v) {
if(strpos($k, "FBRLH_")!==FALSE) {
$_SESSION[$k]=$v;
}
}
try {
$accessToken = $helper->getAccessToken();
$response = $fb->get('/me?fields=id,name,email,first_name,last_name,albums', $accessToken);
$fb_user_info = $response->getGraphUser();
$fb_first_name = $fb_user_info->getProperty('first_name');
$fb_last_name = $fb_user_info->getProperty('last_name');
$fb_user_id = $fb_user_info->getProperty('id');
$fb_user_email = $fb_user_info->getProperty('email');
$albums = $fb->get('/me/albums', $accessToken)->getGraphEdge()->asArray();
$user_friends = $fb->get('/me/friends?fields=id,name,gender', $accessToken)->getGraphEdge();
$user_fb_photos = array();
foreach( $albums as $album_id => $album_data ){
$user_fb_photos[$album_data['id']]['name'] = $album_data['name'];
$fbPictures = $fb->get("/".$album_data['id']."/photos?fields=picture&limit=12", $accessToken)->getGraphEdge()->asArray();
$user_fb_photos[$album_data['id']]['data'] = $fbPictures;
}
}
}

Read about Login Review in the docs: https://developers.facebook.com/docs/facebook-login/review
Most permissions only work for users with a role in the App. If you want to go public with your App, you have to send those permission in for review. You should actually get a very visible red warning about that when authorizing with an App Admin/Developer.

Related

Facebook OAuth Issue with CakePHP 2.9

Hi Guys first of all let me tell you guys that I am a newbie with CakePHP and MVC also but one of my old client requested me some favor which I took as a challenge. So If anyone can help me I will appreciate a lot.
I have a CakePHP 2.9 application where OAuth is not working properly following is the code for app/Controller/UsersController.php
public function facebookLogin(){
$this->layout = false;
App::import('Vendor', 'Facebook/facebook');
/*$facebook = new Facebook(array(
'appId' => '1867587306812489', // Facebook App ID
'secret' => '9fb41a07d3da3406dbab5861c3498764', // Facebook App Secret
'cookie' => false,
)
); */
$facebook = new Facebook(array(
'appId' => '1887387108164606', // Facebook App ID
'secret' => '8d733aa6a4501ce27fde9626429baab9', // Facebook App Secret
'cookie' => false,
)
);
$user = $facebook->getUser();
if ($user) {
try {
$user_profile = $facebook->api('/me?fields=first_name,last_name,email');
$usersArr = $this->User->find('first',array('conditions'=>array('User.email'=>$user_profile['email'],'User.social_id'=>$user_profile['id'],'User.role_id'=>0)));
$user_count = $this->User->find('first',array('conditions'=>array(),'order'=>'User.id DESC','limit'=>1));
if(empty($usersArr)){
$saveUserArr['User']['username'] = trim($user_profile['first_name']).' '.trim($user_profile['last_name']);
$saveUserArr['User']['firstname'] = $user_profile['first_name'];
$saveUserArr['User']['lastname'] = $user_profile['last_name'];
/* $user_n = $saveUserArr['User']['first_name'].'.'.$saveUserArr['User']['last_name'];
$user_cnt = $user_count['User']['id'] + 1;
$user_n = str_replace(' ','_',$user_n).'.'.$user_cnt;
$saveUserArr['User']['user_unique_id'] = $user_n; */
$saveUserArr['User']['email'] = $user_profile['email'];
$saveUserArr['User']['password'] = '123456';
$saveUserArr['User']['social_id'] = $user_profile['id'];
$saveUserArr['User']['login_from'] = 'facebook';
$saveUserArr['User']['role_id'] = 0;
$this->User->save($saveUserArr['User'],false);
}else{
$this->User->id = $usersArr['User']['id'];
$this->User->saveField('social_id', $user_profile['id']);
$this->User->saveField('login_from', 'facebook');
}
$this->request->data['User']['email'] = $user_profile['email'];
$this->request->data['User']['login_from'] = 'facebook';
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
} else {
$loginUrl = $facebook->getLoginUrl(array(
'scope' => 'email', // Permissions to request from the user
));
return $this->redirect($loginUrl);
}
}
private function deleteFacebookSession(){
Configure::write('debug', 0);
if(!$this->Session->check('Auth.User')){
foreach( $this->Session->read() as $key => $value ) {
if( strpos( $key, 'fb_' ) === 0 ) {
$this->Session->delete($key);
}
}
}
}
It throws following error:
The oauth script url is not properly configured in your fb app.
You may go to your fb app settings and look for APP DOMAIN.
Include your domain there:
If you are developing in your localhost, you may want to create a server.local rec in your hosts file so you can access your localserver as server.local.
Also, you can create test versions of the main fb app, and allows you to have a copy of your fb app that works in other environments, it is called "create test app"

Facebook app permissions when fanpage is liked

I had wanted to check if people like my fanpage so I had to create app on Facebook. I connected themselves on Facebook too. Below my code:
require_once('facebook/facebook.php');
$facebook = new Facebook(array(
'appId' => '574707409300181',
'secret' => 'xxxxxx',
'cookie' => true));
$user = $facebook->getUser();
if($user) {
try {
$our_page_id = '263807853767281'; // This should be string
$user_is_fan = false;
$likes = $facebook->api( '/me/likes?fields=id' );
foreach( $likes['data'] as $page ) {
if( $page['id'] === $our_page_id ) {
$user_is_fan = true;
echo 'YOU LIKE FANPAGE!';
}
}
}
catch (FacebookApiException $e) {
$user = null;
}
}
My question - when user press "like" button on Facebook is possible to show window with the permission's accepting of my app? I'm asking because i don't know how promote my app... Maybe is there better solution? In short words - when user likes my fanpage he have to accept permissions. :)
Thank you for reply!

Facebook Php API: RSVP users to public event

I'm trying to use the facebook php api to rsvp users to a public event.
So far I can only get it to work for users who have already been invited.
I've tried:
$path = $event_id.'/attending';
$method = 'POST';
try
{
$this->facebook->api($path, $method);
}
catch(FacebookApiException $e){}
Which does nothing.
My code as it stands is:
function rsvpEvent($event_id)
{
$fb_config = array(
'appId' => APP_ID,
'secret' => APP_SECRET,
'cookie' => true,
);
$this->load->library('facebook', $fb_config);
$me = $this->facebook->api('/me/');
$user_id = $me['id'];
$path = $event_id.'/invited/'.$user_id;
$status = $this->facebook->api($path, 'GET');
$status = $status['data'][0]['rsvp_status'];
if($status === 'not_replied')
{
$path = $event_id.'/attending';
$method = 'POST';
try
{
$this->facebook->api($path, $method);
}
catch(FacebookApiException $e){}
}
}
Has anyone got any ideas how I can get this to work?
$path = $event_id.'/attending?access_token='.$SOME_ACCESS_TOKEN;
You're not using the access token in your code, so I am uncertain of whether you skipped it when you copied it, If it's not in the code, then it may be that.
I retrieved the information here

Facebook API taggin photos work only in sandbox mode

I'm having a problem with the function of tagging the facebook API, I'll do a summary of the application that I am creating for you to have a better idea of what I need.
I am creating an application where the user selects his friends and the software produces an image with all his friends names plus each ones tags.
I succeed in all of the functions: listing friends, selecting them, generating the image and posting to the timeline. But I can not tag the people, which is an important function to the viral effect of the app.
A strange thing has happened, if I enable Sandbox Mode and select only the ADMINS or TESTERS, the code works. But if I turn off Sandbox mode and select any other friends, nothing happens with the tags.
Below I leave the code I've used.
I used the array_push function to add the IDs to the Facebook 'tags' array.
Facebook Conection:
// INSERE O HEADER
include('includes/header.php');
// CONNECT // CONFIGURAÇÕES
require('facebook_sdk/src/facebook.php');
// CONEXÃO COM O FACEBOOK
$facebook = new Facebook(array(
'appId' => 'XXXXXXXXX,
'secret' => 'XXXXXXXXXXXXXXXXXXXXXXXXXXX',
));
// PEGA SEU ID
$user = $facebook->getUser();
// FUNÇÕES QUE PEGA AS INFOS DO FACEBOOK
if ($user) {
try {
// Proceed knowing you have a logged in user who's authenticated.
$user_profile = $facebook->api('/me?fields=id,name,email,friends,photos,friends.fields(photos)');
$input = $facebook->api('/me?fields=id,name,email,friends,photos,friends.fields(photos)');
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
}
// LINK PARA LOGOUT E REDIRECT SE FOR USUARIO
if ($user) {
$logoutUrl = $facebook->getLogoutUrl();
header('Location: passo1.php');
}
?> <div class="bt-face"><img name="bt_face" id="bt_face" onMouseOver="formbaixo_ON('face');" onMouseOut="formbaixo_OFF('face');" src="images/bt-face.png" alt="Conectar no Facebook" /></div>
</div>
<!---------------- PHP / JAVA BUTTON FACEBOOK (SCOPE = PERMISSÕES) ----------------->
<div id="fb-root"></div>
<script type="text/javascript">
function fbLogin() {
FB.login(function(response) {
if (response.session) {
//user is logged in, reload page
window.location.reload(true);
} else {
// user is not logged in
}
}, { perms:'email,manage_friendlists,publish_stream,user_photos,friends_photos'} );
}
</script>
Tagging code:
if ($user) {
try {
// Proceed knowing you have a logged in user who's authenticated.
$access_token = $facebook->getAccessToken();
$timeline = $facebook->api('/me?link');
$timeline_link = $timeline['link'];
$input = $facebook->api('/me?fields=id,name,email,friends,photos,friends.fields(photos)');
//At the time of writing it is necessary to enable upload support in the Facebook SDK, you do this with the line:
$facebook->setFileUploadSupport(true);
$album = $facebook->api(array(
'query' => "SELECT object_id FROM album WHERE owner=me() AND name='Album name' AND can_upload=1",
'method' => 'fql.query',
));
if (isset($album[0]['object_id'])) $album_uid = $album[0]['object_id'];
else
{
foreach ($albums[data] as $album) {
//Test if the current album name is already in facebook
if($album[name] == 'Album name'){
$album_uid = $album[id];
}
}
if(!$album_uid){
}
}
//Upload a photo to album of ID...
$photo_details = array(
'message'=> 'Eu criei um time...'
);
$file = $url_image; //'images/teste2.gif'; //Example image file
$args_tags = array();
// RETIRA BARRAS DOS ARRAYS
$parte = explode("//", $convocados);
$conta = count($parte);
// EXIBE
$espacamento_linha = 20;
$x_convocados = 0;
$y_convocados = 0;
$array_facebook_tag = '';
for($i=0; $i < ($conta-1); $i++) {
$explode_parte = explode("-", $parte[$i]);
$nome = str_replace("_"," ", $explode_parte[0]);
$id = $explode_parte[1];
$x_jogador = $x_convocados;
$y_jogador = $y_convocados + ($i * $espacamento_linha);
array_push($args_tags, array('tag_uid' => $explode_parte[1], 'x' => $x_jogador, 'y' => $y_jogador));
}
$args = array(
'message' => 'Esse é o meu time dos sonhos. Crie o seu time ',
'image' => '#' . realpath($file),
'tags' => $args_tags,
);
$upload_photo = $facebook->api('/'.$album_uid.'/photos', 'post', $args);
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
}
Any help will be welcome, Thanks!

Facebook connect works fine but troubles inside Facebook iframe

I actually tried to find a solution but nothing and I hope I will find a solution here !
I use facebook connect in my website, everything works fine
when I am logged on facebook, I am automatically logged into my site through facebook connect, and vice versa.
Now i tried to make it a facebook application but I have the following problem:
I try to run inside the facebook iframe but unfortunately I'm not automatically logged in. sometimes it works, sometimes nothing happens , Sometimes I get this message: (Could not get the Facebook session. Your server may not Be Able Securely Facebook to connect to the user to retrieve information.)
some code im using :
include 'includes/facebook.php';
$facebook = new Facebook(array(
'appId' => $setting['facebook_appid'],
'secret' => $setting['facebook_secret'],
'cookie' => true, // enable optional cookie support
));
if ($facebook->getUser()) {
$facebook_session = 1;
try {
$fb_user = $facebook->api('/me');
} catch (FacebookApiException $e) {
error_log($e);
}
function get_facebook_cookie($app_id, $application_secret) {
$args = array();
parse_str(trim($_COOKIE['fbs_' . $app_id], '\\"'), $args);
ksort($args);
$payload = '';
foreach ($args as $key => $value) {
if ($key != 'sig') {
$payload .= $key . '=' . $value;
}
}
if (md5($payload . $application_secret) != $args['sig']) {
return null;
}
return $args;
}
$cookie = get_facebook_cookie($setting['facebook_appid'], $setting['facebook_secret']);
$open = #file_get_contents('https://graph.facebook.com/me?access_token='.$cookie['access_token']);
if ($open != FALSE) {
$fbdata = json_decode($open);
$fb_user = array();
foreach($fbdata as $key => $fbdata2) {
$fb_user[$key] = $fbdata2;
}
}
}
else {
$facebook_session = 0;
}
ps: im using of course a Secure Canvas URL
Please help !
Thanks in advance
My Facebook Connect login worked fine, but not inside the Facebook Canvas/iFrame it didn't work at all. I had to change my login method (now that facebook users have to be able to autologin in your application) and what basically worked for me was this: How to authorize Facebook app using redirect in canvas?
This is what I had before (I use CakePHP):
$params = array(
'scope' => 'email'
);
$loginUrl = $facebook->getLoginUrl($params);
$this->redirect($loginUrl);
And I changed it to this which worked quite well:
$loginUrl = $facebook->getLoginUrl(
array(
'canvas' => 1,
'fbconnect' => 0,
'req_perms' => 'publish_stream'
)
);
echo '<script>top.location="'.$loginUrl.'";</script>';
I'm not sure if that really helps you as your app seems a bit more complicated than mine, but maybe you can solve your issue with this answer or the post I linked to.