I have created 2 facebook apps, hosted in the same external domain. I have installed these two apps in a facebook page of mine and in both apps i am running the following php code at the beginning:
session_start();
// added in v4.0.0
require_once 'autoload.php';
use Facebook\FacebookSession;
use Facebook\FacebookRedirectLoginHelper;
use Facebook\FacebookRequest;
use Facebook\FacebookResponse;
use Facebook\FacebookSDKException;
use Facebook\FacebookRequestException;
use Facebook\FacebookAuthorizationException;
use Facebook\GraphObject;
use Facebook\Entities\AccessToken;
use Facebook\HttpClients\FacebookCurlHttpClient;
use Facebook\HttpClients\FacebookHttpable;
// start session
// init app with app id and secret
FacebookSession::setDefaultApplication( 'xxx','yyy' );
// login helper with redirect_uri
$helper = new FacebookRedirectLoginHelper('https://apps.facebook.com/my_namespace/' );
try
{
$session = $helper->getSessionFromRedirect();
}
catch( FacebookRequestException $ex )
{
// When Facebook returns an error
}
catch( Exception $ex )
{
// When validation fails or other local issues
}
// see if we have a session
if ( isset( $session ) )
{
// graph api request for user data
$request = new FacebookRequest( $session, 'GET', '/me' );
$response = $request->execute();
// get response
$graphObject = $response->getGraphObject();
// print data
echo '<pre>' . print_r( $graphObject, 1 ) . '</pre>';
}
else
{
// show login url
echo 'Login';
}
When I run each application, the user identity that is shownn is equal for all properties except for user id:
One app 1, i see:
Facebook\GraphObject Object
(
[backingData:protected] => Array
(
[id] => 1400416826952138
[email] => my_name#gmail.com
[first_name] => Name
[gender] => female
Etc
On app 2 I see:
Facebook\GraphObject Object
(
[backingData:protected] => Array
(
[id] => 1397126750614479
[email] => my_name#gmail.com
[first_name] => Name
[gender] => female
Etc
As i am using the same user (my account) in both apps, why are there 2 different ID for the same user account?
Thanks
Nat
Related
I have implemented google sign-in for my web app, in which I've used this library: https://metacpan.org/pod/Google::RestApi::Auth::OAuth2Client to get the code value, the access token and after that the user's information (email, name, google-id).
My problem in this implementation is that the user is prompt for consent where he needs to insert his information (email and password) and I would like to redirect the user for consent where he is able to select the accounts, and not insert his information. I don't know if my implementation, where I make the GET request, is incorrect or if it is because of the library that I use.
In front-end, I have a form which calls a route that redirects to my back-end function 'on_google_login':
sub on_google_login {
my $self = shift;
my $redirect_name = $self->get_redirect_name();
$self->session(redirect => $redirect_name);
my $google = Google::RestApi::Auth::OAuth2Client->new(
client_id => $ENV{GOOGLE_CLIENT_ID},
client_secret => $ENV{GOOGLE_SECRET},
redirect_uri => $ENV{GOOGLE_BASE_URL} . '/google_callback'
);
my $url = $google->authorize_url(
display => 'page'
);
$self->redirect_to($url);
}
And this is my callback function, where I extract the 'code' and I request the user's information using the access token.
sub on_google_callback {
my $self = shift;
my $code = $self->req->param('code');
my $google = Google::RestApi::Auth::OAuth2Client->new(
client_id => $ENV{GOOGLE_CLIENT_ID},
client_secret => $ENV{GOOGLE_SECRET},
redirect_uri => $ENV{GOOGLE_BASE_URL} . '/google_callback'
);
if (not (defined $code)) {
return $self->render(text => 'Did not connect to Google');
}
my $redirect_name = $self->session('redirect') // 'home';
delete $self->session->{'redirect'};
my $access_token = $google->access_token($code)->access_token;
my $url = $ENV{GOOGLE_ENDPOINT} . $access_token;
my $request = HTTP::Request->new(GET => $url);
my $ua = LWP::UserAgent->new();
my $info = decode_json($ua->request($request)->content);
my ($google_id, $name, $mail) = ($info->{sub}, $info->{name}, $info->{email});
if (!defined $google_id) {
return $self->render(
template => 'validation/custom_error',
title => 'Error logging in with Google',
message => 'Sorry, something went wrong when attempting to log you in ' .
'with Google. Please try again and contact us in the chat if this ' .
'persists.',
status => 400);
}
my $found_user = $self->db->resultset('User')->by_mail($mail);
if ($found_user) {
return unless validate_user_can_login($self, $found_user);
return unless set_user_data_on_login($self, $found_user);
$self->redirect_to($redirect_name);
} else {
$self->session(name => $name);
$self->session(mail => $mail);
$self->redirect_to('/register');
}
return;
}
I am using Facebook SDK with HTC Sense Token,so i want to do that requests with user auth just with the token doing like this with the token i want to send requests with use a app(using the htc sense token) i had an appid but i had no secret code to post on facebook how to get the app htc sense app secret code to post on my wall,page etc
<?php
session_start();
require_once 'facebook-php-sdk/autoload.php';
use Facebook\FacebookSession;
use Facebook\FacebookRequest;
use Facebook\GraphUser;
use Facebook\FacebookRequestException;
use Facebook\FacebookRedirectLoginHelper;
$api_key = 'FACEBOOK_APP_ID';
$api_secret = 'FACEBOOK_APP_SECRET';
$redirect_login_url = 'http://www.yoursite.com/somefolder/file.php';
/ initialize your app using your key and secret
FacebookSession::setDefaultApplication($api_key, $api_secret);
// create a helper opject which is needed to create a login URL
// the $redirect_login_url is the page a visitor will come to after login
$helper = new FacebookRedirectLoginHelper( $redirect_login_url);
// First check if this is an existing PHP session
if ( isset( $_SESSION ) && isset( $_SESSION['fb_token'] ) ) {
// create new session from the existing PHP sesson
$session = new FacebookSession( $_SESSION['fb_token'] );
try {
// validate the access_token to make sure it's still valid
if ( !$session->validate() ) $session = null;
} catch ( Exception $e ) {
// catch any exceptions and set the sesson null
$session = null;
echo 'No session: '.$e->getMessage();
}
} elseif ( empty( $session ) ) {
// the session is empty, we create a new one
try {
// the visitor is redirected from the login, let's pickup the session
$session = $helper->getSessionFromRedirect();
} catch( FacebookRequestException $e ) {
// Facebook has returned an error
echo 'Facebook (session) request error: '.$e->getMessage();
} catch( Exception $e ) {
// Any other error
echo 'Other (session) request error: '.$e->getMessage();
}
}
if ( isset( $session ) ) {
// store the session token into a PHP session
$_SESSION['fb_token'] = $session->getToken();
// and create a new Facebook session using the cururent token
// or from the new token we got after login
$session = new FacebookSession( $session->getToken() );
try {
// with this session I will post a message to my own timeline
$request = new FacebookRequest(
$session,
'POST',
'/me/feed',
array(
'link' => 'www.finalwebsites.com/facebook-api-php-tutorial/',
'message' => 'A step by step tutorial on how to use Facebook PHP SDK v4.0'
)
);
$response = $request->execute();
$graphObject = $response->getGraphObject();
// the POST response object
echo '<pre>' . print_r( $graphObject, 1 ) . '</pre>';
$msgid = $graphObject->getProperty('id');
} catch ( FacebookRequestException $e ) {
// show any error for this facebook request
echo 'Facebook (post) request error: '.$e->getMessage();
}
if ( isset ( $msgid ) ) {
// we only need to the sec. part of this ID
$parts = explode('_', $msgid);
try {
$request2 = new FacebookRequest(
$session,
'GET',
'/'.$parts[1]
);
$response2 = $request2->execute();
$graphObject2 = $response2->getGraphObject();
// the GET response object
echo '<pre>' . print_r( $graphObject2, 1 ) . '</pre>';
} catch ( FacebookRequestException $e ) {
// show any error for this facebook request
echo 'Facebook (get) request error: '.$e->getMessage();
}
}
} else {
// we need to create a new session, provide a login link
echo 'No session, please login.';
}
You need to use a Token of your own App. Not sure why you would want to use the Token of the HTC Sense App for posting, afaik it is ONLY used for spamming - because a lot of permissions are already approved for it. DonĀ“t do that, create your own authorization process for your own App: https://developers.facebook.com/docs/facebook-login
...and then go through Login Review with the additional permission: https://developers.facebook.com/docs/facebook-login/review
Trying to use/abuse/hijack another App is just wrong and definitely not allowed.
I'm new with phpsdk v4, and I'm trying to get access token for my pages.
I tried with this:
<?
include getenv('social');
use Facebook\FacebookSession;
use Facebook\FacebookRequest;
use Facebook\GraphUser;
use Facebook\FacebookRequestException;
use Facebook\FacebookSDKException;
use Facebook\FacebookRedirectLoginHelper;
use Facebook\FacebookResponse;
use Facebook\FacebookAuthorizationException;
use Facebook\GraphObject;
$access_token = $_SESSION['facebooklogged'];
$session = new FacebookSession($access_token);
And after:
$page_access_token = (new FacebookRequest( $session, 'GET', '/320330478029510?fields=access_token', array( 'fields' => 'access_token' ) ))->execute()->getGraphObject()->asArray();
print_r($page_access_token);
And:
$request = new FacebookRequest($session, 'GET', '/me/accounts?fields=name,access_token,perms');
$pageList = $request->execute()->getGraphObject()->asArray();
print_r($pageList);
Both return or id of page, or a empty array();
Array ( [id] => 320330478029510 )
Array ( )
I created $session from login page, with
$logare = new FacebookRedirectLoginHelper('https://mysite/facebook/login.php');
try{$session = $logare->getSessionFromRedirect();}catch(FacebookSDKException $e) {$session = null;}
if($session)$_SESSION['facebooklogged'] = $session->getToken();
What is wrong?
I tried with another account, another admin of page, and work with that...but with my account, still nothing ... I will delete this app from used apps, and i will try again.
I'm currently trying to integrate the lastest Facebook php sdk into a Phalcon project but I'm not having much luck.
I can get the SDK to work in a standalone project but the exact same code fails when integrated into a Phalcon project (either as a service or directly in a Controller).
The issue seems to be that the facebook redirect helper creates a "state" property which is appended to a loginUrl and then stored in a session. When a user is redirected back to my site after signing in, it checks this property against a querystring value. The state property is only generated and stored whenever you display the login url via the redirectHelpers getLoginUrl() method. Somehow, when I integrate this in Phalcon the session variable and the $_GET parameter never seem to match up. The simple example which works is as follows
// lots of requires
Facebook\FacebookSession::setDefaultApplication($appId,$secret);
$helper = new Facebook\FacebookRedirectLoginHelper('http://'.$_SERVER['HTTP_HOST'] .'/');
// see if a existing session exists
if ( isset( $_SESSION ) && isset( $_SESSION['fb_token'] ) ) {
// create new session from saved access_token
$session = new FacebookSession( $_SESSION['fb_token'] );
// validate the access_token to make sure it's still valid
try {
if ( !$session->validate() ) {
$session = null;
}
} catch ( Exception $e ) {
// catch any exceptions
$session = null;
}
} // end if isset($_SESSION)
if ( !isset( $session ) || $session === null ) {
// no session exists
try {
$session = $helper->getSessionFromRedirect();
} catch( FacebookRequestException $ex ) {
// When Facebook returns an error
// handle this better in production code
print_r( $ex );
} catch( Exception $ex ) {
// When validation fails or other local issues
// handle this better in production code
print_r( $ex );
}
}
// see if we have a session
if ( isset( $session ) ) {
// save the session
$_SESSION['fb_token'] = $session->getToken();
// create a session using saved token or the new one we generated at login
$session = new FacebookSession( $session->getToken() );
// graph api request for user data
$request = new FacebookRequest( $session, 'GET', '/me' );
$response = $request->execute();
// get response
$graphObject = $response->getGraphObject()->asArray();
// print profile data
echo '<pre>' . print_r( $graphObject, 1 ) . '</pre>';
// print logout url using session and redirect_uri (logout.php page should destroy the session)
echo 'Logout';
} else {
// show login url
echo 'Login'; // this line would generate a new state
}
When I try using this exact same code in a controller in a phalcon project (or by setting "$me" up in the $di), the state check always fails even though I'm not generating a new login url. The only other difference is that in the simple project I require all the facebook files using require_once but in the Phalcon project I use
$loader->registerNamespaces(
array(
"Facebook" => __DIR__ . '/../../vendor/facebook/php-sdk-v4/src/Facebook/'
)
);
but replacing that with the requires doesn't seem to have an effect.
Anyone got any clues?
I've got it working by using registerClasses not registerNamespaces - but using v3.2.x so not a v4.
$loader->regeisterNamespaces( /* Projects' classes */ )
->registerClasses(array(
'Facebook' => __DIR__ . '/../../vendor/facebook/php-sdk/src/facebook.php'
))
->register();
ps.: Im using composer to load FacebookSDK so I have different path than yours.
Then I'm using it in Controller ordinary without using $di,
protected function getFacebook()
{
if (!$this->facebook) {
$this->facebook = new Facebook(array(
'appId' => $this->config->social->facebook->appId,
'secret' => $this->config->social->facebook->secret,
'fileUpload' => false,
'allowSignedRequest' => false,
));
}
return $this->facebook;
}
I've worked this one out. The issue was that the browser was automatically making a request to /favicon.ico as well,as I didn't have a favicon.ico this then rendered the default indexAction again and as such this was causing the getLoginUrl() method to fire again generating a new state. The simple fix is to just create a favicon, or define the error handling route for files not there (I was just using the boilerplate from the phalcon dev tools initially)
I try to get some details from user of app, but have problem because don't know what to do with code I get after I run this code below, I get something like this:
http://myapp.com/?code=AQAPYR33UZrJpuPrAfE_lL3XPCBaw1ZcTLRl_9cYU2H77T7S3VKVz0njBt_0Jff54HfrzHW9_r-WF_-GN1VWHjEi9zNIMHZHFSEqXcTD7vbP2HKqN1DaEAealNxBNpATFb-RAFYIAZL4EqSUXLCYJ9-WvvDF5oWCUd5vAQ3TiXgPUDWml35v43fBn2xXJo1
I thought its access token but it didn't...
use CGI;
my $cgi = CGI->new;
use Net::Facebook::Oauth2;
my $fb = Net::Facebook::Oauth2->new(
application_id => 'your_application_id',
application_secret => 'your_application_secret',
callback => 'myapp.com'
);
###get authorization URL for your application
my $url = $fb->get_authorization_url(
scope => ['offline_access','publish_stream'],
display => 'page'
);
####now redirect to this url
print $cgi->redirect($url);
##once user authorizes your application facebook will send him/her back to your application
##to the callback link provided above
###in your callback block capture verifier code and get access_token
my $fb = Net::Facebook::Oauth2->new(
application_id => 'your_application_id',
application_secret => 'your_application_secret',
callback => 'http://myapp.com'
);
my $access_token = $fb->get_access_token(code => $cgi->param('code'));
###save this token in database or session
##later on your application you can use this verifier code to comunicate
##with facebook on behalf of this user
my $fb = Net::Facebook::Oauth2->new(
access_token => $access_token
);
my $info = $fb->get(
'https://graph.facebook.com/me' ##Facebook API URL
);
print $info->as_json;