Facebook JavaScript helper with PHP SDK suddenly stopped working - php

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.

Related

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/

Getting posts, FacebookResponse contains an empty body

I'm trying to get posts from my Facebook page, where I'm is logged now, like this:
try {
$response = $fb->get('/me/posts', $accessToken->getValue);
} 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;
}
var_dump($response->getDecodedBody());
getDecodedBody returns
array (size=1) 'data' =>
array (size=0)
empty
Or like this
$json_object = file_get_contents('https://graph.facebook.com/me/posts?&access_token=' . $accessToken->getValue());
$posts = json_decode($json_object);
var_dump($posts);
and I getting the same result.
Update:
I have created access token using javascript
window.onload = function() {
FB.login(function(response) {
if (response.authResponse) {
//alert('You are logged in & cookie set!');
// Now you can redirect the user or do an AJAX request to
// a PHP script that grabs the signed request from the cookie.
location.href = 'http://localhost/FB/js-login.php';
} else {
alert('User cancelled login or did not fully authorize.');
}
});
return false;
};
window.fbAsyncInit = function() {
FB.init({
appId: '123450723574945',
cookie: true, // This is important, it's not enabled by default
version: 'v2.2'
});
};
(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'));
And got it in php
$helper = $fb->getJavaScriptHelper();
$accessToken = $helper->getAccessToken();
var_dump($accessToken) result:
object(Facebook\Authentication\AccessToken)[13]
protected 'value' =>
string 'EAABrvUukr0EBAH8yuJpQkhdkZCZBW' (length=207)
protected 'expiresAt' =>
object(DateTime)[15]
public 'date' => string '2017-06-08 16:00:00.000000' (length=26)
public 'timezone_type' => int 3
public 'timezone' => string 'UTC' (length=3)
As I can see, expiresAt property conrains date less then now, but I don't have any errors messages.

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.

Facebook JS SDK does not set cookie?

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.

Some users can't login with Facebook

I have a strange issue regarding my website. The problem is that I have implemented a Facebook login which seems to be working correctly. BUT it happens that for some users it simply does not work. It does not give any error message, simply redirects to the same page where the Facebook-login button was clicked. So my user clicks the login button on my page and no pop-up no error message, just gets back to the login page.
It has happened only once that my client has received the following error message: "Ex code: 100 Ex msg: This authorization code has been used."
I don't know what could cause the problem as it is quite strange for me that basically it works for some people and not for others...
I don't really know what other information should I post but if someone requests more info I can provide them. I'm using Facebook JS SDK with PHP SDK.
update 1:
relevant part in login.php:
<script>
// This is called with the results from from FB.getLoginStatus().
function statusChangeCallback(response) {
if (response.status === 'connected') {
// Logged into your app and Facebook.
testAPI();
} else if (response.status === 'not_authorized') {
// The person is logged into Facebook, but not your app.
$('#fb-login-auth').show();
$('#fb-login-not-auth').remove();
} 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.';
$('#fb-login-not-auth').remove();
$('#fb-login-auth').show();
}
}
function checkLoginState() {
FB.getLoginStatus(function(response) {
statusChangeCallback(response);
});
}
window.fbAsyncInit = function() {
FB.init({
appId: <?php echo FB_APP_ID; ?>,
cookie : true,// enable cookies to allow the server to access the session
xfbml: true,// parse social plugins on this page
version: 'v2.2' // use version 2.2
});
FB.getLoginStatus(function(response) {
statusChangeCallback(response);
});
FB.Event.subscribe('auth.login', function(response) {
//TODO replace absolute link withr elative one for FB
window.location = '/projects/salty/main/users/fblogin';
});
};
// 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/hu_HU/sdk.js";
fjs.parentNode.insertBefore(js, fjs);
} (document, 'script', 'facebook-jssdk'));
function testAPI() {
console.log('Welcome!Fetching your information.... ');
FB.api('/me', function(response) {
console.log('Successful login for: ' + response.name);
$('#fb-login-auth').remove();
$('#fb-login-not-auth').show();
$('.fb_iframe_widget').remove();
});
}
</script>
...
echo $this->Html->link('<i class="fa fa-facebook"></i>Login with FB',
array('action' => 'fblogin'),
array('id' => 'fb-login-not-auth',
'escape' => false));
fblogin.php:
<h1 class="center">Facebook login</h1>
<div id="fb-root"></div>
<script>
$(document).ready(function(){
$('._4z_f').click();
});
window.fbAsyncInit = function() {
FB.init({
appId: <?php echo FB_APP_ID; ?>,
cookie : true,
xfbml: true,
version: 'v2.2'
});
FB.login(function (response) {
if (response.status === "connected") {
var uID = response.authResponse.userID;
console.log(uID);
FB.api('/me', function (response) {});
} else if (response.status === "not_authorized") {
//authCancelled. redirect
}
},
{
scope: 'user_location,user_likes'
});
};//closes window.fbAsynInit
// Load the SDK asynchronously
(function(d){
var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
if (d.getElementById(id)) {return;}
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "//connect.facebook.net/hu_HU/all.js";
ref.parentNode.insertBefore(js, ref);
}(document));
</script>
<h1 id="redirecting">Redirecting</h1>
<fb:login-button scope="public_profile,email" onlogin="checkLoginState();">
</fb:login-button>
The relevant controller action for fblogin:
public function fblogin() {
if ($this->Auth->loggedIn()) {
return $this->redirect($this->Auth->redirectUrl());
}
\Facebook\FacebookSession::setDefaultApplication(FB_APP_ID, FB_APP_SECRET);
$fbHelper = new \Facebook\FacebookJavaScriptLoginHelper();
try {
$session = $fbHelper->getSession();
} catch(Facebook\FacebookRequestException $ex) {
echo "Ex code: " . $ex->getCode();
echo "Ex msg: " . $ex->getMessage();
return $this->redirect(array('action' => 'login'));
// When Facebook returns an error
} catch(\Exception $ex) {
echo "Ex code: " . $ex->getCode();
echo "Ex msg: " . $ex->getMessage();
return $this->redirect(array('action' => 'login'));
// When validation fails or other local issues
}
if ($session) {
$access_token = $session->getToken();
$appsecret_proof = hash_hmac('sha256', $access_token, FB_APP_SECRET);
$request = new \Facebook\FacebookRequest($session, 'GET', '/me?fields=id,name,first_name,middle_name,last_name,email', array("appsecret_proof" => $appsecret_proof));
$response = $request->execute();
$user = $response->getGraphObject(\Facebook\GraphUser::className());
$checkPermissions = new \Facebook\FacebookRequest($session, 'GET', '/me/permissions', array("appsecret_proof" => $appsecret_proof));
$checkResponse = $checkPermissions->execute();
$permissionsObject = $checkResponse->getGraphObject(\Facebook\GraphUser::className());
$permissions = json_decode(json_encode($permissionsObject->asArray()), true);
$isEmailPermissionGiven = true;
foreach($permissions as $permission) {
if ($permission['permission'] == 'email'
&& $permission['status'] == 'declined') {
$isEmailPermissionGiven = false;
}
}
$fbUser = array();
$fbUser['User']['username'] = $user->getName();
$fbUser['User']['last_name'] = $user->getFirstName()." ".$user->getMiddleName();
...
$this->Auth->login($user['User']);
}
}
Thanks in advance,
Zoltan

Categories