First time access after facebook authentication - facebook

Is there any way that when user authenticate my app through Enhanced Auth Dialog, and gets redirected to canvas page, my canvas page knows its his first time visit?

Your may get the user id from facebook after the user redirected to canvas page:
Here is the example:
require_once("facebook.php");
$config = array();
$config[‘appId’] = 'YOUR_APP_ID';
$config[‘secret’] = 'YOUR_APP_SECRET';
$config[‘fileUpload’] = false; // optional
$facebook = new Facebook($config);
$app->user_id = $facebook->getUser();
After you obtain the user_id, you may save it in your database so that you can know whether the user is first time visit.

The previous answer is correct and here is the code I use to check if they are a new user or a returning user. Then I insert them into the database if they are new.
// Get the app User ID
$user = $facebook->getUser();
$seeif = mysql_num_rows(mysql_query("SELECT id FROM users WHERE fbid='$user' LIMIT 1"));
if ( $seeif == "1" ) {
// already exists
} else {
// insert new user
mysql_query("INSERT INTO users (fbid) VALUES('$user' ) ")
or die(mysql_error());
}

While the previous answers are correct, this might be more useful to you in the long run building your application.
Remember this relies on you having an open database connection as well as the facebook php sdk
// this brings back more info print_r($user)
$user = $facebook->api('/me');
$exists = mysql_num_rows(mysql_query("SELECT id FROM users WHERE fbid='" . $user['id'] . "'));
if ( $exists > 0) {
// already exists
} else {
// insert new user
mysql_query("INSERT INTO users (fbid) VALUES('" . $user['id'] . "' ) ") or die(mysql_error());
// do something else (post to timeline?)
// look up facebook feed for more info on posting
try {
// Post Message to feed.
$facebook->api('/me/feed', 'POST', $msg);
} catch (FacebookApiException $e) {
error_log($e);
}
}

Related

login with facebook, facebook give me other id

i try to do a login with facebook, i build this code:
<?php
ob_start();
include("facebook_constants.php"); // in this file i have appid and appsecretid
$users = $facebook->getUser();
if ($users!="") {
try {
$user_profile = $facebook->api('/me','GET');
$logoutUrl = $facebook->getLogoutUrl();
$fuserid=$user_profile["id"]; // give me the id of the user
$fusername=$user_profile["name"]; // give me the name of the user
$femail=$user_profile["email"]; // give me the email of the user
$fusernamenew = str_replace(' ', '', $fusername); // change the name to username (omer lol = omerlol)
$newtoken=base64_encode($fuserid."::".$fusernamenew."::".$femail); // data to token
$itsme = $this->haimz->DB->num_rows("SELECT id FROM users WHERE fbid = ?haimz?", $fuserid); // if have user with that id = login , if not goto register page
if($itsme > 0){
echo "goto login page";
}
else{
echo "goto register page";
exit;
}
} catch (FacebookApiException $e) {
$users = null;
}
}
?>
the $fuserid give me other userid but the $fusername and $femail give me the correct .
its not the userid of the user.
its other userid.
https://developers.facebook.com/docs/apps/changelog
To better protect people's information, when people log into a version of your app that has been upgraded to use Graph API v2.0, Facebook will now issue an app-scoped ID rather than that person's orginal ID. However, for users that have previously logged into your app, the user ID will not change.
You don´t get the "real" ID of a user anymore, for privacy reasons. You only get an App Scoped ID that is unique in the App only. You can still use it to identify the user when he returns to your App with the App Scoped ID, it will only be different in another App.
You can also map App Scoped IDs between different Apps with the Business Mapping API, if needed: https://developers.facebook.com/docs/apps/for-business

Permissions error when posting to a group I administer

My app is able to post to several pages successfully, but when I try to post to a group:
$page_id = MY_GROUP_ID;
$page_access_token = "";
$result = $fb->api("/me/accounts");
$page_access_token = "";
// loop trough all your pages and find the right one
if( !empty($result['data']) )
{
foreach($result["data"] as $page)
{
if($page["id"] == $page_id)
{
$page_access_token = $page["access_token"];
break;
}
}
} else {
echo "AN ERROR OCCURED: could not get the access_token. Please verify the page ID ".$page_id." exists.";
}
// set the facebook active facebook access token as the one we just fetch
$fb->setAccessToken($page_access_token);
// Now try to post on page's wall
try{
$message = array(
'message' => "Test message",
'description' => "Test Description",
'link' => "http://example.org"
);
$result = $fb->api('/'.$page_id.'/feed','POST',$message);
if($result){
echo 'Successfully posted to Facebook Wall...';
}
}catch(FacebookApiException $e){
echo $e->getMessage();
}
}else{
$fbloginurl = $fb->getLoginUrl(array('redirect-uri'=>$returnurl, 'scope'=>$permissions));
echo 'Login with Facebook';
}
I get
(#200) Permissions error
If I go here: https://www.facebook.com/settings?tab=applications, I can see my app and permissions it has. I do not see anything in the list pertaining to groups.
I've logged out and was prompted to log in with the script (above), but am not being prompted to edit/add app permissions. I cannot find any app related settings under Group Settings for the group I have.
I remember seeing the app permissions page a year ago when I first made the app, but short of deleting the current and recreating, is there a way to simply edit existing permissions to add my group to the app? I am not seeing any group permissions when I click on the app under the app settings page (right above).

upload photos got by fql query on my server

Hello guys i'm trying to understand how to upload the image from facebook.
function for do fql query. Is useful for future occasions.
<?php
// connection facebook api key...
function fb_fql($fql) {
$this->ci =& get_instance();
// Get User Details
$this->ci->load->model('facebook_model');
$this->ci->load->library('user');
// $fb_id = $this->ci->user->get_facebook_id($this->ci->session->userdata('user_id'));
// User is found
// Get Facebook User profile
$user_profile = $this->ci->facebook->getUser();
$result = false;
if ($user_profile) { // if profile exist
try{
$accessToken = $this->ci->facebook->getAccessToken();
$fb_id = $this->ci->facebook->api('/me?access_token='.$accessToken);
if( isset($user_profile) )
{
$fql_run = array(
'method' => 'fql.query',
'query' => $fql,
);
$result = $this->ci->facebook->api($fql_run); // run fql
} else { $result = false; }
}catch(FacebookApiException $e){
$result = null;
}
}
return $result;
}
?>
Here i get the photos by this query and the result of the array show correctly 10 photos of facebook. Now i have to upload it on my server but how can i do that?
<?php
// fql query
$fql = "SELECT pid
FROM photo
WHERE aid IN (
SELECT aid
FROM album
WHERE owner=me() LIMIT 10
) ";
// run query
$photos = $this->facebook_action->fb_fql($fql);
if ($photos != false) {
foreach ($photos as $photo) {
echo print_r($photos); // show the array with the data taken
// here i would like upload the photos got from the query.
}
} else {
echo "no photo";
}
?>
You will need to get the src or src_big field from the photo table and then download this using CURL, file_put_contents or similar. There are quite a few StackOverflow answers for grabbing an image and saving it to a file - e.g Saving image from PHP URL
SELECT src_big FROM photo
WHERE aid IN (SELECT aid FROM album WHERE owner=me() LIMIT 10)
Since you will be downloading user's data to your own server, I would advise you to check that your application does not violate the Facebook Platform Policy.

how can I get a facebook Page access token from a users access token using php?

I am trying to get a page access token starting out with just a users access token stored in my database and a page id. So far I have not been using the facebook.php instead just using php's curl_* functions. So far I can send posts to the page (with a hard coded page id) but I want to impersonate the page when doing so.
Can I do this easily without facebook.php, that would be nice as it might save me from feeling like I should rewrite what I've done so far. If not, then how would I get the page access token from the facebook object - remember so far at least I don't store user ids or page ids in my db, just user access tokens and of course my app id and secret.
I've been looking at the example for getting page access tokens but I find it not quite what I need as it gets a user object and in so doing seems to force the user to login to facebook each time, but I stored the user access token to avoid exactly that from happening.
Do I need more permissions than manage_page and publish_stream? I tried adding offline_access but it doesn't seem available anymore (roadmap mentions this).
here is some of my code from my most recent attempt which uses the facebook.php file:
// try using facebook.php
require_once 'src/facebook.php';
// Create our Application instance
$facebook = new Facebook(array(
'appId' => $FB_APP_ID, // $FB_APP_ID hardcoded earlier
'secret' => $FB_APP_SECRET, // $FB_APP_SECRET hardcoded earlier
));
$facebook->setAccessToken($FB_ACCESS_TOKEN );
//got user access token $FB_ACCESS_TOKEN from database
// Get User ID -- why?
$user = $facebook->getUser();
//------ get PAGE access token
$attachment_1 = array(
'access_token' => $FB_ACCESS_TOKEN
);
$result = $facebook->api("/me/accounts", $attachment_1);
foreach($result["data"] as $page) {
if($page["id"] == $page_id) {// $page_id hardcoded earlier
$page_access_token = $page["access_token"];
break;
}
}
echo '<br/>'.__FILE__.' '.__FUNCTION__.' '.__LINE__.' $result= ' ;
var_dump($result); //this prints: array(1) { ["data"]=> array(0) { } }
$facebook->setAccessToken($page_access_token );
// Get User ID, why - re-init with new token maybe?
$user = $facebook->getUser();
//------ write to page wall
try {
$attachment = array(
'access_token' => $page_access_token,
'link' => $postLink,
'message'=> $postMessage
);
$result = $facebook->api('/me/feed','POST', $attachment);
echo '<br/>'.__FILE__.' '.__FUNCTION__.' '.__LINE__.' $result= ' ;
var_dump($result);
} catch(Exception $e) {
echo '<br/>'.__FILE__.' '.__FUNCTION__.' '.__LINE__.' $e= ' ;
var_dump($e); /*this gives : "An active access token must
be used to query information about the
current user." */
}
die;
Thanks
PS: I hardcoded the user id and started calling
$result = $facebook->api("/$user_id/accounts", $attachment_1);
and I still get an empty result.
PPS: The Graph API Explorer does not show my fan pages either even though my account is set as the Manager. My attempts to post work but show as being from my account rather than from the page.
PPPS: made a little progress by adding permissions on the graph explorer page to get an access token that way but that doesn't help as I need to the the access token programmatically. When a user with many fan pages logs in to my site I want to show them the list of their facebook fan pages to choose from. In practice aren't the permissions just granted on the app?
PPPPS: the list of permissions on my app now stands at : email, user_about_me, publish_actions
and
Extended Permissions:
manage_pages, publish_stream, create_note, status_update, share_item
do I need more? when I try now I still fail to get anything from the call to:
$facebook->api("/$user_id/accounts", $attachment_1);
Px5S: DOH!!! I see now that I was neglecting to add the manage_pages permissions to my call for a user access token when my scripts first get one and store it in the DB. But when I reuse that new access token I still get the error : "An active access token must be used to query information about the current user." So, can't such tokens be reused? Aren't they long term? will read more stuff...
Here is my functioning code, still messy but seems to work, note the scopes on the first $dialog_url, and please feel free to mock my code or even suggest improvements :
function doWallPost($postName='',$postMessage='',$postLink='',$postCaption='',$postDescription=''){
global $FB_APP_ID, $FB_APP_SECRET;
$APP_RETURN_URL=((substr($_SERVER['SERVER_PROTOCOL'],0,4)=="HTTP")?"http://":"https://").$_SERVER['HTTP_HOST'].$_SERVER['SCRIPT_NAME'].'?returnurl=1';
$code = $_REQUEST["code"];
$FB_ACCESS_TOKEN = getFaceBookAccessToken( );
$FB_ACCESS_TOKEN_OLD = $FB_ACCESS_TOKEN;
//if no code ot facebook access token get one
if( empty($code) && empty($FB_ACCESS_TOKEN) && $_REQUEST["returnurl"] != '1')
{
// if( $_REQUEST["returnurl"] == '1') die;
$dialog_url = "http://www.facebook.com/dialog/oauth?client_id=".$FB_APP_ID."&redirect_uri=".$APP_RETURN_URL."&scope=publish_stream,manage_pages";
header("Location:$dialog_url");
}
if( empty($FB_ACCESS_TOKEN) ){
if($_REQUEST['error_code'] == '200'){
return null;
}else if (!empty($code)){
$token_url = "https://graph.facebook.com/oauth/access_token?client_id=".$FB_APP_ID."&redirect_uri=".urlencode($APP_RETURN_URL)."&client_secret=".$FB_APP_SECRET."&code=".$code;
$access_token = file_get_contents($token_url);
$param1=explode("&",$access_token);
$param2=explode("=",$param1[0]);
$FB_ACCESS_TOKEN=$param2[1];
}else{
return null;
}
}
if(!empty($FB_ACCESS_TOKEN) && $FB_ACCESS_TOKEN_OLD != $FB_ACCESS_TOKEN) {
setFaceBookAccessToken( $FB_ACCESS_TOKEN);
}
$_SESSION['FB_ACCESS_TOKEN'] = $FB_ACCESS_TOKEN;
$page_name = '';
$page_id = getFaceBookPageId(); //from db
if(empty($page_id ) ) return null;
//in case there are multiple page_ids separated by commas
if(stripos($page_id, ',') !== false ){
$page_ids = explode(',', $page_id) ;// = substr($page_id, 0, stripos($page_id, ','));
}
$result = null;
foreach($page_ids as $page_id){
$page_id = trim($page_id);
if( !empty($FB_ACCESS_TOKEN)){
//get page_id
require_once 'src/facebook.php';
// Create our Application instance (replace this with your appId and secret).
$facebook = new Facebook(array(
'appId' => $FB_APP_ID,
'secret' => $FB_APP_SECRET
));
$facebook->setAccessToken($FB_ACCESS_TOKEN );
//------ get PAGE access token
$page_access_token ='';
$attachment_1 = array(
'access_token' => $FB_ACCESS_TOKEN
);
$result = $facebook->api("/me/accounts", $attachment_1);
if(count($result["data"])==0) {
return null;
}
foreach($result["data"] as $page) {
if($page["id"] == $page_id) {
$page_access_token = $page["access_token"];
break;
}
}
//------ write to page wall
try {
$attachment = array(
'access_token' => $page_access_token,
'link' => $postLink,
'message'=> $postMessage
);
$result = $facebook->api('/me/feed','POST', $attachment);
} catch(Exception $e) {
return null;
}
} //end if( !empty($FB_ACCESS_TOKEN))
}//end foreach
return $result; }
Now, I wonder if I can send the same message to several pages at once ...
Yup, just by looping over the ids, see above, it now supports multiple page ids.
And unless someone wants to contribute to the code - there's lots of ways it can be improved - I'm done.

Error message when trying to request permissions after user denies request (using Facebook PHP SDK)

I'm using the PHP Facebook SDK (v.3.1.1) for building my Facebook app.
At some point in my flow I need the user to accept my app. I'm using the following code:
// Is there an error? Redirect to explain permissions page
if(!empty($_GET['error'])) {
$redirectUrl = APP_FACEBOOK_PAGE;
require_once(ABSOLUTE_DOCUMENTROOT_PATH.'do_redirect.inc.php');
die();
}
// Prepare app
$facebook = new Facebook(array(
'appId' => APP_ID,
'secret' => APP_SECRET,
'cookie'=> true
));
$facebookId = $facebook->getUser();
// Changed user?
if((!empty($_SESSION['facebookAuth']['facebookId']) && $_SESSION['facebookAuth'] ['facebookId'] != $facebookId)) {
$facebook->setAccessToken('');
$_SESSION['facebookAuth']['facebookId'] = $facebookId;
$redirectUrl = getRequestPermissionsUrl($facebook);
require_once(ABSOLUTE_DOCUMENTROOT_PATH.'do_redirect.inc.php');
die();
}
// No access token? Re-acquire it!
if($facebook->getAccessToken() == '') {
$redirectUrl = getRequestPermissionsUrl($facebook);
require_once(ABSOLUTE_DOCUMENTROOT_PATH.'do_redirect.inc.php');
die();
}
// Let's see if we have an active session
if(!empty($_SESSION['facebookAuth']['facebookId']) && !empty($_SESSION['facebookAuth'] ['facebookUserObject'])){
$facebookId = $_SESSION['facebookAuth']['facebookId'];
$facebookUserObject = $_SESSION['facebookAuth']['facebookUserObject'];
}else{
$facebookId = $facebook->getUser();
if ($facebookId) {
try {
$facebookUserObject = $facebook->api('/me');
// Put them in session so we can re-use them
$_SESSION['facebookAuth']['facebookId'] = $facebookId;
$_SESSION['facebookAuth']['facebookUserObject'] = $facebookUserObject;
} catch (FacebookApiException $e) {
error_log($e);
}
}
}
// If no facebookId -> check permissions anyway
if(empty($facebookId)) {
$redirectUrl = getRequestPermissionsUrl($facebook);
require_once(ABSOLUTE_DOCUMENTROOT_PATH.'do_redirect.inc.php');
die();
}
My function 'getRequestPermissionsUrl' calls for the getLoginUrl:
return $redirectUrl = $facebookObject->getLoginUrl(array('canvas'=>1,'fbconnect'=>0,'redirect_uri'=>$returnUrl,'scope'=>'publish_stream,email,user_likes'));
the file 'do_redirect.inc.php' does a js-redirect:
top.location.href = '$redirectUrl';
So, with that in mind let's take a look at the first part.
This code gets included again after the user has denied the permission and the page reloads. In that case $_GET['error'] is filled and we'll be redirected to another php-file in the app - a file that does not include the code I posted but has nothing to do with permissions or stuff at all. In that other file is a link to the page that needs permission again - the code above gets loaded again but when trying to request permissions I'm getting the error 'something went wrong and we're trying to fix it' on a Facebook page.
I've tried evertyhing from destroying sessions to setting the accestoken empty to... you name it. I'm quite out of ideas now so I'd be glad if somebody of you guys have any suggestions. Any help would be greatly appreciated.
Thanks in advance!
I just saw a newer question asking the same thing - Sorry, something went wrong after cancel application connexion on SDK 3.0
There is a currently open bug in Facebook's bug tracker about this