Facebook Connect and Codeigniter - HTTP/1.0 400 Bad Request - facebook

i'm struggling really hard to implement Facebook connect into my codeigniter application - I have one issue right now. After downloading the PHP SDK from here: https://github.com/facebook/php-sdk/ I copied the /src files into my CI libraries (as everyone do : )).
Now I want to authenticate my users using this method:
https://developers.facebook.com/docs/authentication/server-side/
My controller is here (I think the problem is at the end, but pasted full file, cause i'm not sure):
<?php
class Fb25 extends CI_Controller {
function index()
{
$app_id = "MY APP ID";
$app_secret = "MY SECRET KEY";
$site_url = "http://devlocalhost.com/";
$this->load->library('facebook',array('appId' => $app_id, 'secret' => $app_secret));
$user = $this->facebook->getUser();
$data['user'] = $user;
if($user){
$data['user_profile'] = $this->facebook->api('/me');
$user_profile = $data['user_profile'];
} else{
$user = NULL;
}
if($user){
// Get logout URL
$data['logoutUrl'] = $this->facebook->getLogoutUrl(array(
'next' => 'http://devlocalhost.com/', // URL to which to redirect the user after logging out
));
}else{
// Get login URL
$data['loginUrl'] = $this->facebook->getLoginUrl(array(
'scope' => 'email', // Permissions to request from the user
'redirect_uri' => 'http://devlocalhost.com/fb25/good', // URL to redirect the user to once the login/authorization process is complete.
));
}
if($user){
// Save your method calls into an array
$data['queries'] = array(
array('method' => 'GET', 'relative_url' => '/'.$user),
array('method' => 'GET', 'relative_url' => '/'.$user.'/home?limit=50'),
array('method' => 'GET', 'relative_url' => '/'.$user.'/friends'),
array('method' => 'GET', 'relative_url' => '/'.$user.'/photos?limit=6'),
);
// POST your queries to the batch endpoint on the graph.
$batchResponse = $facebook->api('?batch='.json_encode($queries), 'POST');
//Return values are indexed in order of the original array, content is in ['body'] as a JSON
//string. Decode for use as a PHP array.
$data['user_info'] = json_decode($batchResponse[0]['body'], TRUE);
$data['feed'] = json_decode($batchResponse[1]['body'], TRUE);
$data['friends_list'] = json_decode($batchResponse[2]['body'], TRUE);
$data['photos'] = json_decode($batchResponse[3]['body'], TRUE);
}
echo 'user_info: '.$data['user_info'];
print_r($data);
$this->load->view('fb25_view', $data);
}
public function good(){
$app_id = "MY APP ID";
$app_secret = "MY SECRET KEY";
$site_url = "http://devlocalhost.com/";
echo '<br/><br/>SESJA:<br/>';
print_r($_SESSION);
echo '<br/><br/>GET:<br/>';
print_r($_GET);
echo '<br/><br/>REQUEST:<br/>';
print_r($_REQUEST);
echo '<br/><br/>najs<br/><br/>';
session_start();
$code = $_GET["code"];
//######IMO PROBLEM IS SOMEWHERE HERE:
$token_url = "https://graph.facebook.com/oauth/access_token?"
. "client_id=" . $app_id . "&redirect_uri=" . urlencode($my_url)
. "&client_secret=" . $app_secret . "&code=" . $code;
$response = file_get_contents($token_url);
$params = null;
parse_str($response, $params);
$graph_url = "https://graph.facebook.com/me?access_token="
. $params['access_token'];
$user = json_decode(file_get_contents($graph_url));
echo("Hello " . $user->name);
}
}
?>
My problem is: I'm pressing the login button and gets into facebook to authenticate myself, clicking "go to app" and want to go back into my website - it says:
Message: file_get_contents(https://graph.facebook.com/oauth/access_token? client_id=487560264592073&redirect_uri=http%3A%2F%2Fdevlocalhost.com%2F&client_secret=mysecretcode&code=AQAgnmNWwDub9yaRB6Vf73gg8Xvwo8KhIM077lB67_bu1Z3rAvyk3Ckl54qK7hh9o3VkG0rFIBTfRXwtrSBFVWEpqYfm1o7e5CQg3jVctq-EE1ZxWrgWrfesLpQ2oF3wlmEMb5o6ORobGmibT06kqe5f2N0ch4kSYBJ4SiTcdV-612fGOJHGcipeyU_GJJ0Jvsg)
[function.file-get-contents]: failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request
UPDATE
Look here, please:
I added function into your controller:
public function link(){
$fb_usr = $this->fb_connect->user;
$firstname = $fb_usr['first_name'];
$my_url="http://devlocal.pl";
echo 'user_id';
$token_url = "https://graph.facebook.com/oauth/access_token?"
. "client_id=myclientid&redirect_uri=" . urlencode($my_url)
. "&client_secret=mysecretcode&code=" . $_GET['code'];
redirect($token_url);
}
To get my access token - without access token I can't get my username..
I made your loginbyfacebook function redirecting into link function. And it doesn't show the fb username.
When I'm redirecting to my token_url It shows:
{
"error": {
"message": "Error validating verification code.",
"type": "OAuthException",
"code": 100
}
}

Follow these steps:
1.Put the facebook php sdk in library folder
2.create facebook config with app detail
3.Inherit facebook class in fb_connect
4.add these function in controller then it will work like charm.
fb_connect.php
<?php
include(APPPATH.'libraries/facebook/facebook.php');
class Fb_connect extends Facebook{
//declare public variables
public $user = NULL;
public $user_id = FALSE;
public $fb = FALSE;
public $fbSession = FALSE;
public $appkey = 0;
//constructor method.
public function __construct()
{
$CI = & get_instance();
$CI->config->load("facebook",TRUE);
$config = $CI->config->item('facebook');
parent::__construct($config);
$this->user_id = $this->getUser(); // New code
$me = null;
if ($this->user_id) {
try {
$me = $this->api('/me');
$this->user = $me;
} catch (FacebookApiException $e) {
error_log($e);
}
}
}
} // end class
Controller function
function loginByFacebook(){
$this->load->library('fb_connect');
$param = array(
'scope' =>'email,user_location,user_birthday,offline_access',
'redirect_uri' => base_url()
);
redirect($this->fb_connect->getLoginUrl($param));
}
function facebook() {
if (!$this->fb_connect->user_id) {
} else {
$fb_uid = $this->fb_connect->user_id;
$fb_usr = $this->fb_connect->user;
$firstname = $fb_usr['first_name'];
}
}
In this way
$fb_usr = $this->fb_connect->user;
$firstname = $fb_usr['first_name'];

Related

Testing app on localhost, getting the posts by user id returns an empty array

My code:
$fb = new Facebook\Facebook([
'app_id'=>$clientId,
'app_secret'=>$clientSecret,
'default_graph_version' => 'v2.9',
]);
$uid = 'my_uid';
try {
$response = $fb->get('/'.$uid.'/posts', $clientId.'|'.$clientSecret);
} catch(Facebook\Exceptions\FacebookResponseException $e) {
echo $e->getMessage();
exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
echo $e->getMessage();
exit;
}
var_dump($response->getDecodedBody());
$uid is ID of my own facebook page, there is have the posts.
App domain in the settings is localhost, site URL http://localhost/FB.
Output of var_dump:
object(stdClass)[10] public 'data' =>
array (size=0)
empty

Facebook php sdk not saving logged in user

Facebook redirect back with a token but user is still null or 0
$settings = $this->social_model->get_facebook_settings();
// Create our Application instance (replace this with your appId and secret).
$facebook = new Facebook(array(
'appId' => $settings[0]['value'],
'secret' => $settings[1]['value'],
));
// GET CURRENT USER
$user = $facebook->getUser();
if ($user) {
try {
// Proceed knowing you have a logged in user who's authenticated.
$user_profile = $facebook->api('/me');
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
}
// CHECKS IF NOT LOGIN
if($user == 0){
$params = array(
'scope' => 'publish_stream,publish_actions,manage_pages,status_update,offline_access',
'redirect_uri' => site_url('admin/social/add_facebook')
);
$loginUrl = $facebook->getLoginUrl($params);
echo "<script> window.location = '$loginUrl';</script>";
}else{
$user_accounts = $facebook->api('/me/accounts');
foreach ($user_accounts['data'] as $key => $value) {
$this->social_model->insert_facebook_page($value['name'],$value['access_token'],$value['id']);
}
}
I was able to fix it. I edited the class file and replace $_REQUEST with $_GET. Added CURLOPT_SSL_VERIFYPEER => false,

call getUserAccessToken() return error

I am using facebook app that can publish message on users wall , My Error Message :
Fatal error: Call to protected method BaseFacebook::getUserAccessToken() from context '' in /home/tillaf/public_html/facebook/login_facebook2.php on line 61
My file :
<?php
require_once("facebook.php");
#session_start();
$app_id = "********";
$app_secret = "*********";
$my_url = "http://t.****.net/**/login.php/";
///
$config = array();
$config['appId'] = '408682199198463';
$config['secret'] = 'd5b3c0ddfbd673dd94494f28524c1a84';
$config['fileUpload'] = false; // optional
$facebook = new Facebook($config);
///
////
////
$code = $_REQUEST["code"];
if(empty($code)) {
$_SESSION['state'] = md5(uniqid(rand(), TRUE)); // CSRF protection
$dialog_url = "https://www.facebook.com/dialog/oauth?client_id="
. $app_id . "&redirect_uri=" . urlencode($my_url) . "&state="
. $_SESSION['state'] . "&scope=user_birthday,read_stream,publish_stream,email,user_status,offline_access";
echo("<script> top.location.href='" . $dialog_url . "'</script>");
}
else{
$user_id = $facebook->getUser();
echo $user_id;
echo "<br/>";
////////// Get Access Token
/*
$app_token_url = "https://graph.facebook.com/oauth/access_token?"
. "client_id=" . $app_id
. "&client_secret=" . $app_secret
. "&grant_type=client_credentials";
$response = file_get_contents($app_token_url);
$params = null;
parse_str($response, $params);
echo("This app's access token is: " . $params['access_token']);
*/
///-------------
$user_access_token = $facebook->getUserAccessToken();
////////
////// Start publish on wall
//$facebook->getAccessTokenFromCode($_GET['code']);
$message='ssss';
$link='http://www.google.com';
$name='Samilox';
$caption='s';
$description='Descrption...';
$facebook->api("/me/feed",'POST',
array( 'access_token' =>$user_access_token,
'message' => 'Hello World!',
'link' => 'www.example.com'
)
);
///
}
?>
Sorry For Code :) because i am trying many solutions before i post this question .
Please Can anyone help ?
Thanks in advance
I fixed it use :
//// Add AccessToken for curren session
function getAccessToken() {
if ($this->accessToken !== null) {
return $this->accessToken;
}
$this->setAccessToken($this->getApplicationAccessToken());
$user_access_token = $this->getUserAccessToken();
if ($user_access_token) {
$this->setAccessToken($user_access_token);
}
return $this->accessToken;
}
function getApplicationAccessToken() {
return $this->appId.'|'.$this->appSecret;
}
////

how to keep fb app inside a page tab while authentication (oauth 2)?

Small problem here
I want to make a small fb app which show different views for page admin and users, page admin can add html to the app and include the app in their page (somewhat like the old fbml app).
but the problem is when i'm authenticating the app it is jumping from page tab to its app page.
i need to acces the following things
[page] => stdClass Object
(
[id] => FAN_PAGE_ID
[liked] => 1
[admin] =>
)
for this i need to be in fb page tab while authenticating. How ? :(
i am posting my current code here.
please help me.
ob_start();
$app_id = "----------";
$app_secret = "-----------------";
include_once 'src/facebook.php';
$my_url = "http://apps.facebook.com/-----beta/index.php";
$facebook = new Facebook(array(
'appId' => $app_id,
'secret' => $app_secret,
));
session_start();
$code = $_REQUEST["code"];
//echo $code . "</br>";
if(empty($code)) {
$_SESSION['state'] = md5(uniqid(rand(), TRUE)); //CSRF protection
$dialog_url = "https://www.facebook.com/dialog/oauth?client_id=" . $app_id . "&display=popup&scope=manage_pages,email&redirect_uri=" . urlencode($my_url) . "&state=" . $_SESSION['state'];
echo("<script> top.location.href='" . $dialog_url . "'</script>");
}
if($_REQUEST['state'] == $_SESSION['state']) {
$token_url = "https://graph.facebook.com/oauth/access_token?" . "client_id=" . $app_id . "&redirect_uri=" . urlencode($my_url) . "&client_secret=" . $app_secret . "&code=" . $code;
$response = file_get_contents($token_url);
$params = null;
parse_str($response, $params);
$graph_url = "https://graph.facebook.com/me?access_token=" . $params['access_token'];
$user = json_decode(file_get_contents($graph_url));
//echo $_REQUEST['signed_request'];echo "<hr>";
//var_dump($user);
$signedRequest = $facebook->getSignedRequest();
$appData = array();
if (!empty($signedRequest) && !empty($signedRequest['page'])) {
$appData = json_decode($signedRequest['page'], true);
}
var_dump($appData); echo "<hr>";
var_dump(parse_signed_request($_REQUEST['signed_request'] , $app_secret));
echo("<hr>Hello " . $user->name);
}
else {
echo("The state does not match. You may be a victim of CSRF.");
}
function parse_signed_request($signed_request, $secret) {
list($encoded_sig, $payload) = explode('.', $signed_request, 2);
// decode the data
$sig = base64_url_decode($encoded_sig);
$data = json_decode(base64_url_decode($payload), true);
if (strtoupper($data['algorithm']) !== 'HMAC-SHA256') {
error_log('Unknown algorithm. Expected HMAC-SHA256');
return null;
}
// check sig
$expected_sig = hash_hmac('sha256', $payload, $secret, $raw = true);
if ($sig !== $expected_sig) {
error_log('Bad Signed JSON signature!');
return null;
}
return $data;
}
function base64_url_decode($input) {
return base64_decode(strtr($input, '-_', '+/'));
}
I am using this script in the tab:
function parse_signed_request($signed_request, $secret) {
list($encoded_sig, $payload) = explode('.', $signed_request, 2);
$sig = base64_url_decode($encoded_sig);
$data = json_decode(base64_url_decode($payload), true);
if (strtoupper($data['algorithm']) !== 'HMAC-SHA256') {
return null;
}
$expected_sig = hash_hmac('sha256', $payload, $secret, $raw = true);
if ($sig !== $expected_sig) {
return null;
}
return $data;
}
function base64_url_decode($input) {
return base64_decode(strtr($input, '-_', '+/'));
}
$signed_request = $_REQUEST['signed_request'];
$secret = $app_secret;
$getdata = parse_signed_request($signed_request, $secret);
$fanpage = $getdata['page'];
$page_id = $fanpage['id']; // GET THE PAGE ID
$is_fan = $fanpage['liked']; // 0 if its not fan, 1 if its fan
$is_admin = $fanpage['admin']; //1 if user is admin of page. 0 if not
if($page_id){
//if app is tab
if($is_admin){
//if user is admin
}
if($is_fan){
//I am fan
}else{
// I am not a fan
}
}

php-sdk 3.1.1 can't get $facebook->api('/me') for test user and no authorization request displays

When I use the following code, $user_profile = $facebook->api('/me'); will show the info for me, the admin user, but when I switch to a test user the permissions dialog never displays for the test user to add the app and $user_profile doesn't get defined.
I can't seem to find one example of code that seems to do everything properly in terms of making sure the app is authorized and the user is authenticated. I see from the old FB developer forums that a lot of people seem to be having the same issue with the newer procedures.
Here's the code:
<?php
$appId = "myid";
$secret = "mysecret";
$canvasurl = "http://www.example.com/myappname/";
$canvas = "http://apps.facebook.com/myappname/";
$scope = "user_website,email,publish_stream,user_birthday,user_location,user_work_history,user_about_me,user_hometown,manage_pages,offline_access";
require_once "facebook.php";
$facebook = new facebook(array(
'appId' => $appId,
'secret' => $secret
)
);
$user = $facebook->getUser();
if ($user) {
try {
$user_profile = $facebook->api('/me');
}
catch (FacebookApiException $e) {
$user = null;
}
if (!$user) {
$loginUrl = $facebook->getLoginUrl(
array(
'scope' => $scope,
'redirect_uri' => $canvas
)
);
echo <<<LU
<script type="text/javascript">
top.location.href = $loginUrl;
</script>
LU;
}
}
print_r($user_profile);
?>
Thanks.
I will post my code
<?php
$fbconfig['appid' ] = "";
$fbconfig['secret'] = "";
$fbconfig['baseUrl'] = "";
$fbconfig['appBaseUrl'] = "";
$user = null;
try{
include_once "src/facebook.php";
}
catch(Exception $o){
echo '<pre>';
print_r($o);
echo '</pre>';
}
$facebook = new Facebook(array(
'appId' => $fbconfig['appid'],
'secret' => $fbconfig['secret'],
'cookie' => true,
));
//Facebook Authentication part
$user = $facebook->getUser();
$loginUrl = $facebook->getLoginUrl(
array(
'canvas' => 1,
'fbconnect' => 0,
'scope' => 'user_status,publish_stream,user_photos'
)
);
if ($user) {
try {
$user_profile = $facebook->api('/me');
} catch (FacebookApiException $e) {
$user = null;
}
}
if (!$user) {
echo "<script type='text/javascript'>top.location.href = '$loginUrl';</script>";
exit;
}
?>