How to pass the facebook response object to php object? - php

When the user successes to login facebook, there is a response object in the javascript. How can I pass this object to PHP by using post or other methods?
window.fbAsyncInit = function() {
FB.init({
appId: '12345788', // App ID
channelUrl: /channel.html', // Channel File
status: true, // check login status
cookie: true, // enable cookies to allow the server to access the session
xfbml: true // parse XFBML
});
// Additional init code here
FB.getLoginStatus(function(response) {
if (response.status === 'connected') {
// connected
var uid = response.authResponse.userID;
var accessToken = response.authResponse.accessToken;
} else if (response.status === 'not_authorized') {
// not_authorized
} else {
// not_logged_in
}
});

Related

Facebook Javascript SDK Login - POST Response to PHP

The code below is Facebook's "Login for the Web with the JavaScript SDK", which will send the browser's email address and name to the client-side javascript.
But how do I get the email and name POSted to a PHP file on my website server, so I can log the user in using PHP?
function statusChangeCallback(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() {
FB.api('/me', {fields: 'email,name'},function(response) {
document.getElementById('status').innerHTML = 'Thanks for logging in again, ' + JSON.stringify(response) + '!<br/><img src="https://graph.facebook.com/'+response.id+'/picture?width=300" />';
});
}
$(document).ready(function() {
$.ajaxSetup({ cache: true });
$.getScript('//connect.facebook.net/en_US/sdk.js', function(){
FB.init({
appId: '211867502496511',
cookie: true, // enable cookies to allow the server to access the session
xfbml: true, // parse social plugins on this page
version: 'v2.5' // or v2.0, v2.1, v2.2, v2.3
});
FB.getLoginStatus(function(response) {
statusChangeCallback(response);
});
});
});
function doalog(){
FB.login(function(response){
statusChangeCallback(response);
});
}
You can use the workhorse of manual networking in client side JavaScript: the XMLHttpRequest.
Basically this is an object that allows you to manually communicate with your server. You can use it in conjunction with a FormData object to POST the data do your server. The request you send can be handled like any other form POST request.
Once you have the email and name you can do this.
var name = theMethodYouUseToGetTheName();
var email = theMethodYouUseToGetTheEmail();
var request = new XMLHttpRequest();
request.onReadyStateChanged = function() {
if (request.readyState == 4) {
if (request.status == 200) {
// your request has been sent and you might have a response
} else {
// there has been an error
}
}
}
var formData = new FormData();
formData.append("name", name);
formData.append("email", email);
request.open("POST", "http://yourwebsite.com/your/php/file.php", true);
request.send(formData);
Then on your server you can access the POST data like normal using
$userName = $_POST["name"];
$userEmail = $_POST["email"];

save email, country, ..., full name from facebook to database with login with facebook

<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({
appId : 'myappid',
channelUrl : '//www.mywebsite.com/channel.html',
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
// Here we subscribe to the auth.authResponseChange JavaScript event. This event is fired
// for any authentication related change, such as login, logout or session refresh. This means that
// whenever someone who was previously logged out tries to log in again, the correct case below
// will be handled.
FB.Event.subscribe('auth.authResponseChange', function(response) {
// Here we specify what we do with the response anytime this event occurs.
if (response.status === 'connected') {
// The response object is returned with a status field that lets the app know the current
// login status of the person. In this case, we're handling the situation where they
// have logged in to the app.
// testAPI();
FB.login(function(response) {
if (response.session == 'connected' && response.scope) {
FB.api('/me', function(response) {
window.location = "http://www.mywebsite.com/checkloginfb.php?email=" + response.email;
}
);
}
} , {scope: 'email'});
} else if (response.status === 'not_authorized') {
// In this case, the person is logged into Facebook, but not into the app, so we call
// FB.login() to prompt them to do so.
// In real-life usage, you wouldn't want to immediately prompt someone to login
// like this, for two reasons:
// (1) JavaScript created popup windows are blocked by most browsers unless they
// result from direct interaction from people using the app (such as a mouse click)
// (2) it is a bad experience to be continually prompted to login upon page load.
// FB.login();
FB.login(function(response) {
if (response.session == 'connected' && response.scope) {
FB.api('/me', function(response) {
window.location = "http://www.mywebsite.com/checkloginfb.php?email=" + response.email;
}
);
}
} , {scope: 'email'});
} else {
// In this case, the person is not logged into Facebook, so we call the login()
// function to prompt them to do so. Note that at this stage there is no indication
// of whether they are logged into the app. If they aren't then they'll see the Login
// dialog right after they log in to Facebook.
// The same caveats as above apply to the FB.login() call here.
FB.login(function(response) {
if (response.session == 'connected' && response.scope) {
FB.api('/me', function(response) {
window.location = "http://www.mywebsite.com/checkloginfb.php?email=" + response.email;
}
);
}
} , {scope: 'email'});
}
});
};
// 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/en_US/all.js";
ref.parentNode.insertBefore(js, ref);
}(document));
// Here we run a very simple test of the Graph API after login is successful.
// This testAPI() function is only called in those cases.
function testAPI() {
console.log('Welcome! Fetching your information.... ');
FB.api('/me', function(response) {
console.log('Good to see you, ' + response.name + '.');
});
}
</script>
I want to give my users the option to login with facebook, but I do not know why it does not work. I get infinitly popups. This is my first time doing this and I just can not understand me. I want to get the email, country, profile picture and full name of the user so I can add it to database.
Any help is appriciated.
Thanks
You are trying to login the user even if the user is already connected. This creates the infinite loop cycles.
// Here we specify what we do with the response anytime this event occurs.
if (response.status === 'connected') {
// The response object is returned with a status field that lets the app know the current
// login status of the person. In this case, we're handling the situation where they
// have logged in to the app.
// testAPI();
FB.login(function(response) {
if (response.session == 'connected' && response.scope) {
FB.api('/me', function(response) {
window.location = "http://www.mywebsite.com/checkloginfb.php?email=" + response.email;
}
);
}
} , {scope: 'email'});
}
I would recommend separating, FB.Event.subscribe('auth.authResponseChange', function(){} from FB.Login(function(){}, {}).
The auth.authResponseChange will fire anytime the user's authentication status has changed, while the FB.Login attempts to get the user's permission and authorize the application etc.

webtechnick Facebook plugin autologin issue

I am using webtechnick Facebook plugin and have successfully integrated it with my PHP site. Login and logout are working fine, but I am facing an issue when I login into Facebook in one tab and my website in other tab.
In this case my website retrieves the Facebook data automatically without clicking the Facebook login button in my login page. The website should retrieve the Facebook data only if I click the Facebook login button in my login page. How can I resolve this?
Here is my code in FacebookHelper.php:
public function init($options = null, $reload = true) {
$options = array_merge(array(
'perms' => 'email'
), (array)$options);
if ($appId = FacebookInfo::getConfig('appId')) {
$init = '<div id="fb-root"></div>';
$init .= $this->Html->scriptBlock("
window.fbAsyncInit = function() {
FB.init({
appId : '$appId', // App ID
channelURL : '../../Vendor/channel.php', // Channel File
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
oauth : true, // enable OAuth 2.0
xfbml : true // parse XFBML
});
// Checks whether the user is logged in
FB.getLoginStatus(function(response) {
if (response.authResponse) {
// logged in and connected user, someone you know
// alert('You are connected');
} else {
// no user session available, someone you dont know
// alert('You are disconnected');
}
});
FB.Event.subscribe('auth.authResponseChange', function(response) {
if (response.authResponse) {
// the user has just logged in
// alert('You just logged in facebook from somewhere');
} else {
// the user has just logged out
// alert('You just logged out from faceboook');
}
});
// Other javascript code goes here!
};
// logs the user in the application and facebook
function login(redirection){
FB.login(function (response) {
if(response.authResponse) {
// user is logged in
// console.log('Welcome!');
if(redirection != null && redirection != ''){
top.location.href = redirection;
}
} else {
// user could not log in
console.log('User cancelled login or did not fully authorize.');
}
}, {scope: '" . $options['perms'] . "'});
}
// logs the user out of the application and facebook
function logout(redirection){
FB.logout(function(response) {
// user is logged out
// redirection if any
if(redirection != null && redirection != ''){
top.location.href = redirection;
}
});
}
// Load the SDK Asynchronously
(function() {
var e = document.createElement('script'); e.async = true;
e.src = document.location.protocol
+ '//connect.facebook.net/".$this->locale."/all.js';
document.getElementById('fb-root').appendChild(e);
}());");
return $init;
} else {
return "<span class='error'>No Facebook configuration detected. Please add the facebook configuration file to your config folder.</span>";
}
}
Login page (login.ctp):
<?php
echo $this->Facebook->html();
echo $this->Facebook->login(array('id'=>'facebookbut','img' => 'facebooklogin.png','redirect' =>'/'));
echo $this->Facebook->init();
?>

Request dialog appears but request is not being sent

I m trying to send app request using "apprequest" dialog
using following code
but in this the request dialog appears
but requests are not sent
var inviteFriends;
window.fbAsyncInit = function() {
FB.init({
appId : '112312312312321',
status : true,
channelUrl : '//mysite.com/include/fb/channel.php',
cookie : true,
frictionlessRequests : true
});
// Additional initialization code here
FB.getLoginStatus(function(response) {
if (response.status === 'connected') {
// the user is logged in and connected to your
// app, and response.authResponse supplies
// the user's ID, a valid access token, a signed
// request, and the time the access token
// and signed request each expire
console.log('authorized');
FB.api('/me', function(response) {
console.log(response.name);
});
inviteFriends=function(){
var l="";
FB.api('/me/friends',function(response){
console.warn(response.data.length);
for (var i=0; i<20;i++){
//alert(o.id);
l=l+','+response.data[i].id;
}
console.log(l);
FB.ui({method: 'apprequests',
message: 'Hey send me a pic usign picinchat.com in fb chat!',
to: l
}, function(response){
console.log(response.toSource());
});
}
});
}
inviteFriends();

facebook apprequests : An error occurred. Please try again later

i'm using this code to send app requests to users in my facebook application
<script src="https://connect.facebook.net/en_US/all.js"></script>
<script type="text/javascript">
window.fbAsyncInit = function() {
FB.init({
appId: '39764546513545342',
status: true,
cookie: true,
oauth: true
});
};
function invitetoevent(rid)
{
FB.ui({
method: 'apprequests',
message: 'i\'ll see you in this event.',
title: 'Lets Go!.',
filters: ['app_users'],
max_recipients: 25,
},
function (response) {
if (response.request && response.to)
{
//actions
}
else
{
//alert('canceled');
}
});
}
Looks like the way you are using filter is wrong.
DEMO
PS: Assuming your callback function is correct
well it doesn't make any sense but this code works fine.
i removed the facebook script loading from the previous page and used this code.
window.fbAsyncInit = function() {
FB.init({
appId : '397334655643214', // App ID
channelUrl : '//www.itradegame.com/channel.html', // Channel File
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});

Categories