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,
Related
i'm creating a login system using salt and password two columns but it's not working my code of action
public function indexAction() {
$form = new Admin_Form_Login();
$request = $this->getRequest();
if ($request->isPost()) {
if ($form->isValid($request->getPost())) {
if ($this->_process($form->getValues())) {
// We're authenticated! Redirect to the home page
$this->_helper->redirector('', 'dashboard');
} else {
echo 'Password is wrong';
}
}
}
$this->view->form = $form;
}
protected function _process($values) {
// Get our authentication adapter and check credentials
$adapter = $this->_getAuthAdapter();
$adapter->setIdentity($values['email']);
$adapter->setCredential($values['password']);
$auth = Zend_Auth::getInstance();
$result = $auth->authenticate($adapter);
if ($result->isValid()) {
$user = $adapter->getResultRowObject();
$auth->getStorage()->write($user);
return true;
}
return false;
}
protected function _getAuthAdapter() {
$dbAdapter = Zend_Db_Table::getDefaultAdapter();
$authAdapter = new Zend_Auth_Adapter_DbTable($dbAdapter);
$authAdapter->setTableName('eg_user_login')
->setIdentityColumn('email')
->setCredentialColumn('password')
->setCredentialTreatment("MD5(CONCAT(? , salt))");
return $authAdapter;
}
and code of registration action is
$regForm = new Admin_Form_Register();
$this->view->form = $regForm;
if ($this->getRequest()->isPost()) {
if ($regForm->isValid($this->_request->getPost())) {
$values = $regForm->getValues($this->_request->getPost());
$pass = $values['pass1'];
$salt = sha1($pass);
$password = MD5($salt . $pass);
$data = array(
'f_name' => $values['fname'],
'l_name' => $values['lname'],
'gender' => $values['gender'],
'email' => $values['email'],
'contact' => $values['contact'],
'password' => $password,
'salt' => $salt,
'created_on' => date("d-m-y"),
'user_role' => $values['userrole'],
'status' => 0
);
$db = new Admin_Model_Userreg();
$db->insert($data);
}
}
it is displaying any error,i think problem in encryption and decryption in password.
login page is not redirecting to dashboard and not storing the user instance .... please help me. thank you.
i am create a Facebook application. I am try to post users wall.But i do not get any response
php code
$user = $facebook->getUser();
if($user == 0) {
$login_url = $facebook->getLoginUrl($params = array('scope' => "publish_stream"));
echo ("<script> top.location.href='".$login_url."'</script>");
} else { $token=$facebook->getAccessToken();
try {
params = array(
'message' => "Hurray! This works :)",
'name' => "This is my title",
'caption' => "My Caption",
'description' => "Some Description...",
'link' => "http://stackoverflow.com",
'picture' => "http://i.imgur.com/VUBz8.png",
);
$post = $facebook->api("/me/feed","POST",$params);
}
catch (FacebookApiException $e) {
$result = $e->getResult();
}
}
i can't post the content into user's wall .Please help me any one to debug the code
Try this, I posted successfully on my FB using the following:
$user = $facebook->getUser();
if($user == 0) {
//$login_url = $facebook->getLoginUrl($params = array('scope' => "publish_stream"));
//echo ("<script> top.location.href='".$login_url."'</script>");
} else { $token=$facebook->getAccessToken();
try {
$post = $facebook->api("/me/feed","POST",array(
'message' => "Hurray! This works :)",
'name' => "This is my title",
'caption' => "My Caption",
'description' => "Some Description...",
'link' => "http://stackoverflow.com",
'picture' => "http://i.imgur.com/VUBz8.png"
));
}
catch (FacebookApiException $e) {
$result = $e->getResult();
}
}
If you haven't already, remember to include the facebook.php api and your code class initialization
$facebook = new Facebook(array(
'appId' => APP_ID,
'secret' => APP_SECRET,
'cookie' => true
));
try post with php curl. if works your facebook class using rest api. Rest api deleted recently.
$user = $facebook->getUser();
if($user == 0) {
$login_url = $facebook->getLoginUrl($params = array('scope' => "publish_stream"));
echo ("<script> top.location.href='".$login_url."'</script>");
} else { $token=$facebook->getAccessToken();
try {
$params = array(
'access_token' => $token,
'message' => "Hurray! This works :)",
'name' => "This is my title",
'caption' => "My Caption",
'description' => "Some Description...",
'link' => "http://stackoverflow.com",
'picture' => "http://i.imgur.com/VUBz8.png",
);
$url = 'https://graph.facebook.com/'.$user.'/feed';
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_URL => $url,
CURLOPT_POSTFIELDS => $params,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_VERBOSE => true
));
$result = curl_exec($ch);
print_r($result);
curl_close($ch);
}
catch (FacebookApiException $e) {
$result = $e->getResult();
}
}
in your code params is not a $params.
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'];
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;
}
?>
I'm new in FB and having a problem.
I want to put an application in Facebook and already have a website and database. The application could be displayed in Facebook no matter whether the user logged in or not. In order to show the application only to the logged in user, I add some code:
if (!$session){
$url = $facebook->getLoginUrl(array(
'cavas' => 1,
'fbconnet' => 0
));
echo "<script type='text/javascript'>top.location.href = '$url';</script>";
}
else {
try {
$uid = $facebook->getUser();
$me = $facebook->api('/me');
} catch (FacebookApiException $e){
error_log($e);
}
}
But when a user logs in and redirects to my site, the page didn't successfully load. How can I solve it?
(The old code is written like below and runs well except for the login problem:
if ($session){
try {
$uid = $facebook->getUser();
$me = $facebook->api('/me');
} catch (FacebookApiException $e){
error_log($e);
}
}
Use next and it's canvas not cavas:
if (!$session){
$url = $facebook->getLoginUrl(array(
'canvas' => 1,
'next' => 'http://apps.facebook.com/CANVAS_NAME',
'fbconnet' => 0
));
echo "<script type='text/javascript'>top.location.href = '$url';</script>";
}
else {
try {
$uid = $facebook->getUser();
$me = $facebook->api('/me');
} catch (FacebookApiException $e){
error_log($e);
}
}