I have some problem to setup application on facebook, ok what is exactly problems?
Im load script
<script src="http://connect.facebook.net/en_US/all.js"></script>
And this
$(document).ready(function () {
// Pocetak callbacks funkicja
$("#oceni_fbPrijatelje").click(function() {
$("#sidecenter ,#sidedesno,#sidelevo").addClass("fb_over");
FB.init({
appId : 'xxxxxxxxx959971',
});
// 1. User se loguje i uzimamo neke informacija sa FB-a
FB.login(function(response) {
if(response.authResponse) {
accessToken = response.authResponse.accessToken;
signedRequest = response.authResponse.signedRequest;
// 2. Uzimamo informacija za logovane usere
FB.api('/me', function(response) {
facebook_id = response.id;
$.cookie("facebook_id", facebook_id);
// 3. Konacno iskace jebeni popup
FB.ui({
method: 'apprequests',
message: response.name + ' želi da vidi tvoje fotke na xxxxx.',
max_recipients: 10,
exclude_ids: [], // ovo nisam siguran dal radi :( ako radi dobro je.
title: 'Izaberi prijatelje i pozovi na xxxxx' ,
}, requestCallback);
} );
function requestCallback(response) {
// Handle callback here
$("#sidecenter ,#sidedesno,#sidelevo").removeClass("fb_over");
}
}
});
});
});
And popup is loaded fine on my site
So users can send invite to friends from my site on facebook.. but when users receive request on facebook simple this notification always is appers on their profil, you can click accept and facebook redirect to app url but request is still there simple cant accept this..
In the app option on facebook im setup
Canvas URL: http://mysite.com
So application will load my home page , but all works very strange and dont know why Application request always is stay on users profil...
You need to delete those requests.
According to Facebook:
It is the Developers' responsibility to delete a Request once it has
been accepted. For more information on how to delete a Request, please
see the Deleting Requests documentation.
When someone accept an invite he goes to app and the request id is added to the url. You can catch it from there and send a delete request.
$request_ids = explode(',', $_REQUEST['request_ids']);
function build_full_request_id($request_id, $user_id) {
return $request_id . '_' . $user_id;
}
foreach ($request_ids as $request_id) {
$full_request_id = build_full_request_id($request_id, $user_id);
$delete_success = $facebook->api("/$full_request_id",'DELETE');
}
You can find the full code and more information on deleting requests here:
http://developers.facebook.com/docs/requests/#deleting
Related
I am working an an Ionic app where I implement native Facebook login (followed this tutorial -> https://ionicthemes.com/tutorials/about/native-facebook-login-with-ionic-framework). As you can see the Facebook data now gets stored in local storage. I need to save this data in my MySql database.
I got this to work without any issues. Now I want to store the Facebook user data to my MySql database.
Basically I am not sure where to place my http request to pass the data along to my database or how to even do it code wise.
I should mention that I have a backend already setup (which is coded with bootstrap, html, css, js php and mysql).
So the url for my users would be this: http://www.xxxxx.com/user.php
Part of my controller code:
app.controller('LoginCtrl', function($scope, $state, $q, UserService, $ionicLoading) {
// This is the success callback from the login method
var fbLoginSuccess = function(response) {
if (!response.authResponse){
fbLoginError("Cannot find the authResponse");
return;
}
var authResponse = response.authResponse;
getFacebookProfileInfo(authResponse)
.then(function(profileInfo) {
// For the purpose of this example I will store user data on local storage
UserService.setUser({
authResponse: authResponse,
userID: profileInfo.id,
name: profileInfo.name,
email: profileInfo.email,
picture : "http://graph.facebook.com/" + authResponse.userID + "/picture?type=large"
});
$ionicLoading.hide();
$state.go('app.dashboard');
}, function(fail){
// Fail get profile info
console.log('profile info fail', fail);
});
};
// This is the fail callback from the login method
var fbLoginError = function(error){
console.log('fbLoginError', error);
$ionicLoading.hide();
};
// This method is to get the user profile info from the facebook api
var getFacebookProfileInfo = function (authResponse) {
var info = $q.defer();
facebookConnectPlugin.api('/me?fields=email,name&access_token=' + authResponse.accessToken, null,
function (response) {
console.log('logging facebook response',response);
info.resolve(response);
},
function (response) {
console.log(response);
info.reject(response);
}
);
return info.promise;
};
//This method is executed when the user press the "Login with facebook" button
$scope.facebookSignIn = function() {
facebookConnectPlugin.getLoginStatus(function(success){
if(success.status === 'connected'){
// The user is logged in and has authenticated 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('getLoginStatus', success.status);
// Check if we have our user saved
var user = UserService.getUser('facebook');
if(!user.userID){
getFacebookProfileInfo(success.authResponse)
.then(function(profileInfo) {
// For the purpose of this example I will store user data on local storage
UserService.setUser({
authResponse: success.authResponse,
userID: profileInfo.id,
name: profileInfo.name,
email: profileInfo.email,
picture : "http://graph.facebook.com/" + success.authResponse.userID + "/picture?type=large"
});
$state.go('app.dashboard');
}, function(fail){
// Fail get profile info
console.log('profile info fail', fail);
});
}else{
$state.go('app.dashboard');
}
} else {
// If (success.status === 'not_authorized') the user is logged in to Facebook,
// but has not authenticated your app
// Else the person is not logged into Facebook,
// so we're not sure if they are logged into this app or not.
console.log('getLoginStatus', success.status);
$ionicLoading.show({
template: 'Logging in...'
});
// Ask the permissions you need. You can learn more about
// FB permissions here: https://developers.facebook.com/docs/facebook-login/permissions/v2.4
facebookConnectPlugin.login(['email', 'public_profile'], fbLoginSuccess, fbLoginError);
}
});
};
})
My service.js code (local storage)
angular.module('Challenger.services', [])
.service('UserService', function() {
// For the purpose of this example I will store user data on ionic local storage but you should save it on a database
var setUser = function(user_data) {
window.localStorage.starter_facebook_user = JSON.stringify(user_data);
};
var getUser = function(){
return JSON.parse(window.localStorage.starter_facebook_user || '{}');
};
return {
getUser: getUser,
setUser: setUser
};
});
My recommendation is to simply use a JSON ajax PUT or POST from JavaScript. For example, assuming a backend host of example.com
Add a CSP to the Ionic HTML such as:
<meta http-equiv="Content-Security-Policy" content="default-src http://example.com; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline' 'unsafe-eval'">
Add the domain to the whitelist in the Cordova config.xml:
<access origin="http://example.com" />
Then you can call PHP from JavaScript with ajax in your angular controller (I used jQuery here but you can use any JavaScript ajax library):
var data = {
authResponse: authResponse,
userID: profileInfo.id,
name: profileInfo.name,
email: profileInfo.email,
picture : "http://graph.facebook.com/" + authResponse.userID + "/picture?type=large"
};
$.post( "http://example.com/login.php", data, function(returnData, status) {
console.log('PHP returned HTTP status code', status);
});
Finally, on the PHP side — e.g. login.php — access the post data with $_POST['userId'], $_POST['email'], etc.
I guess that you have all your codes ready, but just not sure where is the best place to locate your codes. There is nice linker where has clear instruction about how to layout your php project structure: http://davidshariff.com/blog/php-project-structure/, hope this can give a kind of help.
<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.
I’m new to PHP and tying to set up a page as so users can login using Facebook PHP SDK and JavaScript SDK. I keep getting the fallowing error and I don’t seem to be able to find a solution.
I saw a similar post in here but I couldn’t give solution to the error.
Parse error: syntax error, unexpected T_STRING, expecting ',' or ';' in /homepages/9/d321009915/htdocs/kno_login/login.php on line 2
Here is my code:
<?php
echo '<div id='fb-root'></div>';
require_once("facebook.php");
$config = array();
$config['appId'] = 'some id';
$config['secret'] = 'something here';
$facebook = new Facebook($config);
?>
<script>
window.fbAsyncInit = function() {
FB.init({
appId : '293441190799565', // App ID
channelUrl : '//www.reyesmotion.com/kno_login/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
});
// 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();
} 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();
} 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();
}
});
};
// 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>
<!--
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.
Learn more about options for the login button plugin:
/docs/reference/plugins/login/ -->
<?php
echo '<fb:login-button show-faces="true" width="200" max-rows="1"></fb:login-button>';
?>
Just change the outer single quotes to double
echo "<div id='fb-root'></div>";
I have the following code that would get ur friends list using graph api
function getFriendsList(){
$response = $this->api('/me/friends');
return $response;
}
This returns friends id and name. using graph api
I then execute this code in my joomla module:
$fbClient = JFBConnectFacebookLibrary::getInstance();
$fbUserId = $fbClient->getUserId(TRUE);
//If FB User
if($fbUserId){
$f_list = $fbClient->getFriendsList();
after i get the array i display the firends picture
foreach ($f_list as $friend) {
for($i = 0; $i < count($friend); $i++)
{
echo '<img src="http://graph.facebook.com/'.$friend[$i]['id'].'/picture"><br/>';
}
}
}
This would create the profile photos of my friends.
My question is how do i create an onlick even so that when i click the photo i can send an individual facebook app request. ???
Sending Facebook app requests are not available via the graph api. You can use the app requests javascript dialog to send the request though, you would just need to specify the user's id in the "to" property as detailed in the documentation.
Sample function:
<script>
FB.init({ appId: '**appId**', status: true, cookie: true, xfbml : true });
function sendRequest(to) {
FB.ui({method: 'apprequests', to: to, message: 'You should learn more about this awesome site.', data: 'tracking information for the user'});
return false;
}
</script>
Then just wire an onclick for each image to something like onclick="return sendRequest('**friendId**');"
I had same problem. Though it is very late for answering question, it will help somebody. That's why answering this question.
Instead you can call this function in javascript:
it will give you all friends with photos. Also group of friends who are currently using same app. You can send request to any of them.
function sendRequestViaMultiFriendSelector() {
FB.ui({
method: 'apprequests',
message: "You should learn more about this awesome site."
});
}
I have created a small application , basically a quiz application ( I am about to launch that in a free web hosting website). I want to integrate that with Facebook. But there are mainly 2 issues.
I want the application to be used only by FB users who are member of a particular group (Its a closed group) which i created.
As soon as the quiz is over , the final score should be posted in the group wall.
PS: By integrate i mean , They can only begin the test when they signup using Facebook.
Any other ideas are welcomed.
There are quite a few things you'll need to do. Assuming you're using the FB JS SDK, you'll need to use the following...
Request the publish_stream and user_groups extended permissions via FB.login
Post to the group wall via FB.api, eg... FB.api('/GROUP_ID/feed', 'post', { message: 'yay someone completed the quiz' }, function(response) { alert(response); });
Partial example using FB JS SDK (group checking unimplemented)...
<a onclick="postToGroupWall()">Post msg to group wall</a>
<script>
window.fbAsyncInit = function()
{
FB.init({
appId : 'APP_ID',
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true , // parse XFBML
oauth : true // Enable oauth authentication
});
FB.login(function(response)
{
if (response.authResponse)
{
alert('Logged in!');
// Check if user is in group using opengraph call (/me/groups) via FB.api
// Do that here...
}
else
{
alert('Not logged in - do something');
}
}, { scope : 'publish_stream,user_groups' });
};
window.postToGroupWall = function()
{
var opts = {
message : 'Yay I just completed the quiz',
name : '',
link : 'http://www....',
description : 'Description here',
picture : 'http://domain.com/pic.jpg'
};
FB.api('/GROUP_ID/feed', 'post', opts, function(response)
{
if (!response || response.error)
{
alert('Posting error occured');
}
else
{
alert('Success - Post ID: ' + response.id);
}
});
};
</script>
<!-- FACEBOOK -->
<div id="fb-root"></div>
<script>
(function() {
var e = document.createElement('script');
// replacing with an older version until FB fixes the cancel-login bug
e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
//e.src = 'scripts/all.js';
e.async = true;
document.getElementById('fb-root').appendChild(e);
}());
</script>
<!-- END-OF-FACEBOOK -->
Everything you need to do with facebook (including, but not limited to, the exact requirements you have explained)can be achieved using Facebook Connect API. It is very comprehensive and I can't explain how you would do the whole thing in this answer. This is a good place to start:
http://developers.facebook.com/docs/reference/api/