Facebook JS SDK does not set cookie? - php

I use code from up-to-date FB developers page. In JS SDK I can login, get access token, make api calls etc.
PHP SDK getJavaScriptHelper() returns empty for access token.
I have checked for fbsr_{app_id} cookie and it is not there. I tried to create my own test cookie with JS and retrive and it is set and I can access it from PHP so it is not browser problem.
I have set cookie: true, in JS SDK, I use latest PHP SKD v5 and Graph Api v2.8(The same is set in my developers dashboard).
I use CodeIgniter on wamp server localhost.
I can not think or find anything else, have spent all day on this one. Any help would be appreciated!
code:
<html>
<body>
<script src="https://code.jquery.com/jquery-1.9.1.min.js"></script>
<p>Log In with the JavaScript SDK</p>
<script>
logInWithFacebook = function() {
FB.login(function(response) {
if (response.authResponse) {
console.log('You are logged in & cookie set!');
console.log(response);
// Now you can redirect the user or do an AJAX request to
// a PHP script that grabs the signed request from the cookie.
$.get('<?php echo base_url() ?>index.php/test_facebook/js_login', function(resp){
console.log('Get response' + resp);
});
} else {
console.log('User cancelled login or did not fully authorize.');
}
});
return false;
};
window.fbAsyncInit = function() {
FB.init({
appId: '{app-id}',
cookie: true,
version: 'v2.8'
});
};
(function(d, s, id){
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) {return;}
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_US/sdk.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
</script>
</body>
</html>
and test_facebook/js_login :
<?php
class Test_facebook extends CI_Controller {
public function __construct()
{
parent::__construct();
}
public function index()
{
$this->load->view('test_facebook');
}
public function js_login(){
# /js-login.php
require_once( 'vendor/autoload.php' );
$fb = new Facebook\Facebook([
'app_id' => '{app-id}',
'app_secret' => '{app-secret}',
'default_graph_version' => 'v2.8',
]);
$helper = $fb->getJavaScriptHelper();
try {
$accessToken = $helper->getAccessToken();
} catch(Facebook\Exceptions\FacebookResponseException $e) {
// When Graph returns an error
echo 'Graph returned an error: ' . $e->getMessage();
exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
// When validation fails or other local issues
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
if (! isset($accessToken)) {
echo 'No cookie set or no OAuth data could be obtained from cookie.';
exit;
}
// Logged in
echo '<h3>Access Token</h3>';
var_dump($accessToken->getValue());
}
}
UPDATE
I countinued looking for solution I found this in FB devs page about Server IP Whitelist. I listed http://localhost:8383/test4/index.php/test_facebook/js_login but still returning No cookie set or no OAuth data could be obtained from cookie.

Related

Facebook JavaScript helper with PHP SDK suddenly stopped working

I had this code and it was working without any issue. Suddenly this code stopped working. I followed several answers on Stack Overflow and even added a redirect URL in getaccesstoken. Then also I am getting an empty access token. I have updated the PHP SDK to the latest from GitHub.
<?php
ob_start();
session_start();
require_once( 'Facebook/autoload.php' );
$fb = new \Facebook\Facebook([
'app_id' => 'xxxxxx',
'app_secret' => 'xxxxxxxx',
'graph_api_version' => 'v7.0',
]);
$helper = $fb->getJavaScriptHelper();
try {
// $accessToken = $helper->getAccessToken(); // This code is outdated in recent version. we need to give call back url
$accessToken = $helper->getAccessToken('https://xxxxxxx.com/redirect_url.php');
echo '2222';
echo $accessToken;
}
catch(\Facebook\Exceptions\FacebookResponseException $e) {
// When Graph returns an error
echo 'Graph returned an error: ' . $e->getMessage();
exit;
}
catch(\Facebook\Exceptions\FacebookSDKException $e) {
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
if (! isset($accessToken)) {
echo 'nope, no token.';
exit;
}
Here is the JavaScript part:
<script>
logInWithFacebook = function() {
FB.login(function(response) {
if (response.authResponse) {
window.location.href = "https://xxxxxx.com/redirect_url.php";
}
else {
}
}, {scope: 'pages_show_list'});
return false;
};
window.fbAsyncInit = function() {
FB.init({
appId: 'xxxxxxxx',
cookie: true,
xfbml : true,
version: 'v7.0'
});
};
(function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) {
return;
}
js = d.createElement(s); js.id = id;
js.src = "https://connect.facebook.net/en_US/sdk.js";
fjs.parentNode.insertBefore(js, fjs);
}
(document, 'script', 'facebook-jssdk'));
FB.getLoginStatus(function(response) {
if (response.status === 'connected') {
var accessToken = response.authResponse.accessToken;
}
}
);
</script>
I get this output always:
222 nope, no token.
I want to get the accesstoken to perform some other task.
I had the same problem and resolved it by adding status:true to the FB.Init() options.

Login with facebook: where to get access token

I have 'app-id' and 'app-secret' but I am unable to find it that where can I get access token.
Here is code I'am using:
$fb = new Facebook\Facebook([
'app_id' => '{app-id}',
'app_secret' => '{app-secret}',
'default_graph_version' => 'v2.10',
]);
try {
// Returns a `Facebook\FacebookResponse` object
$response = $fb->get('/me?fields=id,name', '{access-token}');
} catch(Facebook\Exceptions\FacebookResponseException $e) {
echo 'Graph returned an error: ' . $e->getMessage();
exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
$user = $response->getGraphUser();
echo 'Name: ' . $user['name'];
// OR
// echo 'Name: ' . $user->getName();
official documentation
Same question is asked here but no answer there, only link of documentation is there and in that documentation there is no mention that where to get access-token.
PS: I am trying to get user information using php.
Edit: I've also tried to achieve it without access-token like this $response = $fb->get('/me?fields=id,name'); but no luck yet.
<a href="JavaScript:void(0);" onClick="FacebookLogin(); return false;">
<img src="images/fb-login.png" class="img-responsive"/>
<span>Facebook</span>
</a>
<script src="http://connect.facebook.net/en_US/all.js"></script>
<script>
window.fbAsyncInit = function () {
FB.init({
appId: '',
cookie: true,
xfbml: true,
version: 'v2.7'
});
};
(function (d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s);
js.id = id;
js.src = "//connect.facebook.net/en_US/sdk.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
function FacebookLogin() {
FB.login(function (response) {
if (response.authResponse) {
console.log('Welcome! Fetching your information.... ');
FB.api('/me?scope=email&fields=last_name,first_name,email,gender', function (response) {
console.debug(response);
});
} else {
console.log('User cancelled login or did not fully authorize.');
}
});
}
</script>
Please go to your app and follow below steps.
Open https://developers.facebook.com and click on "tools" then click on "Graph API".
For more information please refer below link
https://www.slickremix.com/facebook-60-day-user-access-token-generator/

FB access token is empty without any FB exception thrown from PHP SDK v5

I am using modified example from Facebook developers page. My JS:
window.fbAsyncInit = function() {
FB.init({
appId : '{xxx}',
cookie : true,
xfbml : true,
version : 'v2.8'
});
FB.getLoginStatus(function(response) {
statusChangeCallback(response);
});
};
// Load the SDK asynchronously
(function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_GB/sdk.js#xfbml=1&version=v2.8&appId=xxx";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
function statusChangeCallback(response) {
console.log('statusChangeCallback');
console.log(response);
if (response.status === 'connected') {
testAPI();
} else if (response.status === 'not_authorized') {
document.getElementById('status').innerHTML = 'Please log ' +
'into this app.';
} else {
document.getElementById('status').innerHTML = 'Please log ' +
'into Facebook.';
}
}
function checkLoginState() {
FB.getLoginStatus(function(response) {
statusChangeCallback(response);
});
}
function testAPI() {
console.log('Welcome! Fetching your information.... ');
FB.api('/me', {fields: 'id,name,email'}, function(response) {
console.log('Successful login for: ' + response.name);
console.log('Here is email: ' + response.email);
document.getElementById('status').innerHTML ='Thanks for logging in, ' + response.name + '!';
});
$.get(baseurl + 'index.php/auth/fb_login', function(response){
console.log(response);
});
}
$(document).ready(function(){
$('body').on('click', '.fb-login', function(){
FB.login(function(response){
statusChangeCallback(response);
}, {scope: 'public_profile,email'});
});
});
Basic idea is that after successful login I display response object in console and run testAPI() which makes API call and displays name and email in console. After that I added ajax call to auth/fb_login:
function fb_login(){
require_once( 'vendor/autoload.php' );
$fb = new Facebook\Facebook([
'app_id' => $this->config->item('app_id', 'tank_auth'),
'app_secret' => $this->config->item('app_secret', 'tank_auth'),
'default_graph_version' => $this->config->item('default_graph_version', 'tank_auth')
]);
$helper = $fb->getJavaScriptHelper();
try {
$accessToken = $helper->getAccessToken();
} catch(Facebook\Exceptions\FacebookSDKException $e) {
echo $e->getMessage();
exit;
}
if ($accessToken) {
var_dump('Successfully logged in!');die();
}
var_dump(' not Successfully logged in!');die();
}
And the var_dump always dumps "not ..." without any FB exceptions.
I used facebook debug tool and it returns
Error validating access token: This may be because the user logged out or may be due to a system error.
Application ID xxx: MyAppName
User ID
xxx: Kārlis Janisels
User last installed this app via API v2.x
Issued Unknown
Expires 1480410000 (in about an hour)
Valid False
Origin Unknown
Scopes email, public_profile
So the underlining problem - I can get valid access token in browser but not in server.
If it helps - I am using codeigniter framework on wamp server localhost.

editor is not able to create instant article in facebook

I am creating a code to create instant articles on facebook using PHP SDK. I have created a login using it, and added 'public_profile,email,manage_pages,pages_show_list,pages_manage_instant_articles' permissions.
When user click on login button, it is asking for all these permissions. If user is an admin of a page and he logs in using it, he is able to create instant article on that page. But when user having an editor role of that page, tries to login, he is being asked for all these permissions, and even if he allows for all these permissions, still he is not able to create an instant article. In error log, there is a error like below:
PHP Fatal error: Uncaught Facebook\Exceptions\FacebookAuthorizationException: (#200) Requires extended permission: pages_manage_instant_articles in ../facebook-php-sdk-v4-5.0.0/src/Facebook/Exceptions/FacebookResponseException.php:120
At first time of login, editor user was asked for all permissions and he approved all, but still this error occurred. Now when he tries to again login, he is not being asked for permissions. I have checked permissions for editor role user though "/me/permissions" endpoint. In response, "email, user_friends, pages_show_list, and public_profile" permissions have status "granted", but there is no any detail about "manage_pages and pages_manage_instant_articles" permissions.
For admin role users, all code is working fine and instant article also created using PHP SDK, but this issue comes only for editor role user.
Here is code which I have tried, I have not included my app-id, app-secret, page-id and article-html here:
<?php
session_start();
$page_id = '{page-id}';
$app_id='{app-id}';
$app_secret='{app-secret}';
require_once 'testing/facebook-php-sdk-v4-5.0.0/src/Facebook/autoload.php';
if(!isset($_GET['user'])){
?>
<!DOCTYPE html>
<html>
<head>
<title>Facebook Login JavaScript Example</title>
<meta charset="UTF-8">
</head>
<body>
<script>
// This is called with the results from from FB.getLoginStatus().
function statusChangeCallback(response) {
console.log('statusChangeCallback');
console.log(response);
// The response object is returned with a status field that lets the
// app know the current login status of the person.
// Full docs on the response object can be found in the documentation
// for FB.getLoginStatus().
if (response.status === 'connected') {
// Logged into your app and Facebook.
//testAPI();
var accessToken = response.authResponse.accessToken;
console.log('access token -: '+accessToken);
location.href="instant_article.php?user=logged_in";
} else if (response.status === 'not_authorized') {
// The person is logged into Facebook, but not your app.
document.getElementById('status').innerHTML = 'Please log ' +
'into this app.';
} else {
// The person is not logged into Facebook, so we're not sure if
// they are logged into this app or not.
document.getElementById('status').innerHTML = 'Please log ' +
'into Facebook.';
}
}
// This function is called when someone finishes with the Login
// Button. See the onlogin handler attached to it in the sample
// code below.
function checkLoginState() {
FB.getLoginStatus(function(response) {
statusChangeCallback(response);
});
}
window.fbAsyncInit = function() {
FB.init({
appId : <?= $app_id ?>,
cookie : true, // enable cookies to allow the server to access the session
xfbml : true, // parse social plugins on this page
version : 'v2.6' // use graph api version 2.5
});
// Now that we've initialized the JavaScript SDK, we call
// FB.getLoginStatus(). This function gets the state of the
// person visiting this page and can return one of three states to
// the callback you provide. They can be:
//
// 1. Logged into your app ('connected')
// 2. Logged into Facebook, but not your app ('not_authorized')
// 3. Not logged into Facebook and can't tell if they are logged into
// your app or not.
//
// These three cases are handled in the callback function.
FB.getLoginStatus(function(response) {
statusChangeCallback(response);
});
};
// Load the SDK asynchronously
(function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_US/sdk.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
</script>
<!--
Below we include the Login Button social plugin. This button uses
the JavaScript SDK to present a graphical Login button that triggers
the FB.login() function when clicked.
-->
<fb:login-button scope="public_profile,email,manage_pages,pages_show_list,pages_manage_instant_articles" onlogin="checkLoginState();">
</fb:login-button>
<div id="status">
</div>
</body>
</html>
<?php
}else{
$fb = new Facebook\Facebook([
'app_id' => $app_id,
'app_secret' => $app_secret,
'default_graph_version' => 'v2.6',
'default_access_token' => $app_id.'|'.$app_secret
]);
$oAuth2Client = $fb->getOAuth2Client();
$helper = $fb->getJavaScriptHelper();
$sr = $helper->getSignedRequest();
$user_id = $sr ? $sr->getUserId() : null;
if ( $user_id ) {
try {
// Get the access token
$accessToken = $helper->getAccessToken();
$_SESSION['user_token'] = (string) $accessToken;
} catch( Facebook\Exceptions\FacebookSDKException $e ) {
// There was an error communicating with Graph
echo "SDK error: ".$e->getMessage();
unset($_SESSION['user_token']);
} catch(Facebook\Exceptions\FacebookResponseException $e) {
// When Graph returns an error
echo 'Graph returned an error: ' . $e->getMessage();
unset($_SESSION['user_token']);
}
if (! isset($accessToken)) {
echo 'No cookie set or no OAuth data could be obtained from cookie.';
unset($_SESSION['user_token']);
}else{
if($accessToken->isExpired()){
unset($_SESSION['user_token']);
echo "<script>location.href='instant_article.php'</script>";
exit;
}
}
if(!isset($_SESSION['user_token'])){
echo "<script>location.href='instant_article.php'</script>";
exit;
}
try {
// Exchanges a short-lived access token for a long-lived one
$userToken = $oAuth2Client->getLongLivedAccessToken($accessToken);
$long_token = $userToken->getValue();
} catch(Facebook\Exceptions\FacebookSDKException $e) {
// There was an error communicating with Graph
echo 'SDK error: '.$e->getMessage();
exit;
}
/*$res_perms = $fb->get('/me/permissions?access_token='.$long_token,$long_token,'','v2.6');
echo "<pre>";
print_r($res_perms);
exit;*/
$res_page = $fb->get('/'.$page_id.'?fields=access_token',$long_token,'','v2.6');
$page_info = $res_page->getDecodedBody();
$page_token = $page_info['access_token'];
$article_html = '{ html of article goes here}';
if(trim($article_html) != ""){
$page_params = array(
'access_token'=>$page_token,
'html_source'=>$article_html,
'development_mode'=>true
);
$res_article = $fb->post('/'.$page_id.'/instant_articles',$page_params,$page_token);
}
}
}
?>
It would be great if anyone can help me for this.

Facebook API: Login using JavaScript SDK then checking login state with PHP

I'm using Facebook's JavaScript SDK to bring up a Login Popup when the user clicks the Login button.
The code is, as Facebook provides in the doucmentation:
$(".loginButton").click(function(){
FB.login(function(response) {
FB.api('/me', function(response) {
console.log(response.id);
//User ID shows up so I can see that the user has accepted the app.
});
});
I can also use FB.getLoginStatus() to check that the user has indeed logged in and accepted the application.
However, now I would like to execute a function with PHP. As far as I understand, PHP has $user which is assigned the UserID after a successful login.
The problem is after the JS Login $user is still 0. I'm stuck and I can't figure out why it won't assign the correct user ID to $user
Here's my JS:
<script type="text/javascript">
window.fbAsyncInit = function() {
FB.init({
appId : '<?php echo $AppId; ?>',
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true,
channelUrl : '<?php echo $ServerPath; ?>channel.php' // custom channel
});
};
//Get Login Status
function amILoggedIn(){
var toreturn = "";
FB.getLoginStatus(function(response) {
if (response.status === 'connected') {
window.userId = response.authResponse.userID;
toreturn = "GetLoginStatus: logged in" + " " + "<?php echo $user; ?>";
} else {
toreturn = "GetLoginStatus: Logged Out";
}
console.log(toreturn);
});
};
// Load the SDK asynchronously
(function(d, s, id){
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) {return;}
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_US/all.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
var obj = {
method: 'feed',
link: 'http://www.google.com'
};
$(".loginPopupButton").click(function(){
FB.login(function(response) {
FB.api('/me', function(response) { //user-specific stuff
console.log(response.id);
});
});
});
</script>
And here's the PHP:
<?php
include_once('fbapi/facebook.php');
include_once('fbapi/Authenticated_User.php');
include_once('config.php');
// Create our Application instance.
$facebook = new Facebook(array(
'appId' => $AppId,
'secret' => $AppSecret
));
//Facebook Authentication part
$user = $facebook->getUser();
$perms = "manage_pages";
if(isset($_GET['backlink']))
$redirectUrl = urldecode($_GET['backlink']);
else
$redirectUrl = $fullserverpath;
$cancelUrl = $ServerPath."index.php?page=loginWFb";
//AA - where to go to get FB popup.
$loginUrl = $facebook->getLoginUrl(
array(
'scope' => $perms,
'redirect_uri' => $redirectUrl,
'cancel_uri' => $cancelUrl
)
);
//AA- Defining that a powerUSER is someone who's logged in
if(isset($user)){
$_SESSION['loggedIn'] = $user;
}
?>
Login with the JS SDK stores the login data in the Facebook cookies while login with the PHP SDK stores the data in the PHP session. So if you log with the JS SDK, the PHP SDK will not be aware of that.
To login with the PHP SDK using the JS SDK data, you need to call your PHP page with the signed request in the query parameter:
FB.getLoginStatus(function(response) {
if (response.status === 'connected') {
// Full redirect or ajax request according to your needs
window.location.href = 'login.php?signed_request='+response.authResponse.signedRequest;
}
});
Then $facebook->getUser() will give you the user id in your PHP code.
When initializing the Facebook object in PHP, try setting the sharedSession parameter to true:
$facebook = new Facebook(array(
'appId' => $AppId,
'secret' => $AppSecret,
'sharedSession' => true
));

Categories