Installing one application by another - facebook-graph-api

I am trying to check with my application if one application is installed on specific fan page and if it is not installed I want to install it..
for some reason i am unable to get the page access tokens.
I am able to get the user access tokens and user id, but the page access token returns "Exception" "Unknown fields: access_token".
What is wrong here?
I am using this resources:
http://developers.facebook.com/docs/reference/api/page/#tabs
https://developers.facebook.com/docs/authentication/
<html>
<head>
</head>
<body>
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({
appId : '188474844587139',
status : true,
cookie : true,
xfbml : true,
oauth : true,
});
FB.getLoginStatus(function(response) {
if (response.status === 'connected') {
var uid = response.authResponse.userID;
var userAccessToken = response.authResponse.accessToken;
console.log("User Access Token: "+userAccessToken);
console.log("User ID: "+uid);
// get page access token
FB.api('https://graph.facebook.com/'+uid+'/accounts?access_token='+userAccessToken, function(response) {
console.log(response);
var pageAccessToken = 'Need to get from the response...';
// get information if user got this app
FB.api("https://graph.facebook.com/102561956524622/tabs/353470634682630?access_token="+pageAccessToken,
function(data) {
console.log(data);
});
// install the app
var params = {};
params['app_id'] = '353470634682630';
FB.api('https://graph.facebook.com/102561956524622/tabs'+pageAccessToken, 'post', params, function(response) {
if (!response || response.error) {
console.log("Error: "+response);
} else {
console.log("Ok: "+response);
}
});
});
} else if (response.status === 'not_authorized') {
console.log("the user is logged in to Facebook, but not connected to the app.");
} else {
console.log("the user isn't even logged in to Facebook.");
}
});
};
(function(d){
var js, id = 'facebook-jssdk'; if (d.getElementById(id)) {return;}
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "//connect.facebook.net/en_US/all.js";
d.getElementsByTagName('head')[0].appendChild(js);
}(document));
</script>
</body>
</html>

I managed to solve this issue if any one care this is the code
One of reasons it didn't work was because I used the full address "http://graph.facebook.com..." and as you can see in the code I am using the
FB.api function which is adding this address automatically.
Another reason is that I used the user access token to get information about the application instead of the page access token.
I was also having problem to install the application because I needed to send the page access token as well.
P.S: Don't forget that you need manage_pages permission.
<script>
window.fbAsyncInit = function() {
FB.init({
appId : '188474844587139',
status : true,
cookie : true,
xfbml : true,
oauth : true,
});
FB.getLoginStatus(function(response) {
if (response.status === 'connected') {
var uid = response.authResponse.userID;
console.log(response.authResponse);
var userAccessToken = response.authResponse.accessToken;
var pageId = '102561956524622';
var appId = '353470634682630';
console.log("User Access Token: "+userAccessToken);
console.log("User ID: "+uid);
// get page access token
FB.api('/'+pageId+'?fields=access_token='+userAccessToken, function(response) {
var pageAccessToken = response.access_token;
// get information if user got this app
FB.api('/'+pageId+'/tabs/'+appId+'?access_token='+pageAccessToken,
function(data) {
if (data.data.length < 1) {
console.log("Not installed, Installing...");
// install the app
var params = {};
params['app_id'] = appId;
FB.api('/'+pageId+'/tabs?access_token='+pageAccessToken, 'post', params, function(response) {
if (!response || response.error) {
console.log("Error Installing:");
console.log(response);
} else {
console.log("Installed :)");
console.log(response);
}
});
}
else {
console.log("Already installed.");
}
});
});
} else if (response.status === 'not_authorized') {
console.log("the user is logged in to Facebook, but not connected to the app.");
} else {
console.log("the user isn't even logged in to Facebook.");
}
});
};
(function(d){
var js, id = 'facebook-jssdk'; if (d.getElementById(id)) {return;}
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "//connect.facebook.net/en_US/all.js";
d.getElementsByTagName('head')[0].appendChild(js);
}(document));

Related

create event on facebook via graph api or javascript sdk

I want a "create event facebook popup" with preconfigured parameters.
I have bit of coding as below but i am really confused how we can go further.
My Code below
<script>
window.fbAsyncInit = function() {
FB.init({
appId : '<appid>',
xfbml : true,
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'));
</script>
<span> Create Event </span>
<script>
function callEvent() {
FB.getLoginStatus(function(response) {
if (response.status === 'connected') {
console.log('Logged in.');
var accessToken = response.authResponse.accessToken;
alert(accessToken);
FB.api('/me/events?access_token=' + accessToken, 'post',
{
name: "Test event",
start_time: Math.round(new Date().getTime()/1000.0)
},
function(retVal) {}
);
}
else {
console.log('initiate FB login...');
FB.login();
}
});
}
</script>
Can someone help with code? Thanks in advance.
You cannot create events via the Graph API.
Source: https://developers.facebook.com/docs/graph-api/reference/v2.3/event#publish
Specifically, about user events:
Creating
You can't perform this operation on this endpoint.
Source: https://developers.facebook.com/docs/graph-api/reference/user/events

Facebook login disable automatic redirection

I'm using facebook login functionality, it works well and the redirection is done automatically when i'm connected on Facebook, but Im trying now to do the redirection only if the user clicks on the button facebook login, here is my code :
Thanks for your help.
Ps: Sorry for my bad english
<button id="fb_login_button"
onclick="FB.login(function(){ /* this is a callback function */ },
{scope: 'email,user_birthday,read_stream'});
return false;" class="button button-facelogin" > Via Facebook
</button>
<script>
window.fbAsyncInit = function() {
FB.init({
appId : 'XXXXXXXXXXXXX', // App ID
channelUrl : '//WEBSITE/index.php', // 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.
top.location = window.location = "REDIRECTION URL"
if (response.status === 'connected' && $GLOBALS["disconected"]=== "false") {
// 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>
you can split your code in two files :
Index.php
<button id="fb_login_button" onclick="location.href='facebookLoginPage.php" class="button button-facelogin" > Via Facebook
</button>
facebookLoginPage.php
<script>
FB.login(function(){ /* this is a callback function */ },{scope: 'email,user_birthday,read_stream'});
window.fbAsyncInit = function() {
FB.init({
appId : 'XXXXXXXXXXXXX', // App ID
channelUrl : '//WEBSITE/index.php', // Channel File
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
FB.Event.subscribe('auth.authResponseChange', function(response) {
top.location = window.location = "REDIRECTION URL"
if (response.status === 'connected' && $GLOBALS["disconected"]=== "false") {
testAPI();
} else if (response.status === 'not_authorized') {
FB.login();
} else {
FB.login();
}
});
};
(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));
function testAPI() {
console.log('Welcome! Fetching your information.... ');
FB.api('/me', function(response) {
console.log('Good to see you, ' + response.name + '.');
});
}
</script>

facebook like button only showing up for my account not for other users

I am creating an fb app , I just want to navigate to next page if the user already liked my page and for not liked user only onclick of like it will go to the next page . this code is working fine for my account but not for others . Can you please help me out .
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({
appId : '657165490961669',
channelUrl : 'https://www.facebook.com/cypiyow',
status : true,
cookie : true,
xfbml : true
});
FB.getLoginStatus(function(response) {
var page_id = "228530813943529";
if (response && response.authResponse) {
var user_id = response.authResponse.userID;
var fql_query = "SELECT uid FROM page_fan WHERE page_id = "+page_id+"and uid="+user_id;
FB.Data.query(fql_query).wait(function(rows) {
if (rows.length == 1 && rows[0].uid == user_id) {
window.location = "email_form.php";
} else {
FB.Event.subscribe('edge.create',
function(response) {
window.location = "email_form.php";
}
);
}
});
} else {
//error message
}
});
};
(function(d){
var js, id = 'facebook-jssdk'; if (d.getElementById(id)) {return;}
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "//connect.facebook.net/en_US/all.js";
d.getElementsByTagName('head')[0].appendChild(js);
}(document));
</script>
in your app's settings in the facebook developer area, is this app in sandbox mode? that would cause it to only be available to you, if that is what you mean when you say it is only working for you. you would need to add some testers in your app settings or move out of sandbox mode

facebook authentication to auto popup instead click button

I've tried the fowlling code
https://developers.facebook.com/blog/post/2011/07/21/updated-javascript-sdk-and-oauth-2-0-roadmap/
It works to authenticate
now i want to auto popup once page is loaded instead of having people click ont he button again
I edited and was able to trigger the autopopup , but that only works if i keep the button
How can i remove the button and still have it work?
this is what i've done:
<!DOCTYPE html>
<html xmlns:fb="https://www.facebook.com/2008/fbml">
<head>
<title>
New JavaScript SDK
</title>
</head>
<body>
<div id="fb-root"></div>
<h2>Updated JS SDK example</h2><br />
<div id="user-info"></div>
<p><button id="fb-auth">Login</button></p>
<script>
window.fbAsyncInit = function() {
FB.init({ appId: 'xxx',
status: true,
cookie: true,
xfbml: true,
oauth: true});
function updateButton(response) {
var button = document.getElementById('fb-auth');
if (response.authResponse) {
//user is already logged in and connected
var userInfo = document.getElementById('user-info');
FB.api('/me', function(response) {
userInfo.innerHTML = '<img src="https://graph.facebook.com/'
+ response.id + '/picture">' + response.name;
button.innerHTML = 'Logout';
});
button.onclick = function() {
FB.logout(function(response) {
var userInfo = document.getElementById('user-info');
userInfo.innerHTML="";
});
};
} else {
//user is not connected to your app or logged out
//button.innerHTML = 'Login';
// button.onclick = function() {
FB.login(function(response) {
if (response.authResponse) {
FB.api('/me', function(response) {
var userInfo = document.getElementById('user-info');
userInfo.innerHTML =
'<img src="https://graph.facebook.com/'
+ response.id + '/picture" style="margin-right:5px"/>'
+ response.name;
});
} else {
//user cancelled login or did not grant authorization
}
}, {scope:'email'});
}
//}
}
// run once with current status and whenever the status changes
FB.getLoginStatus(updateButton);
FB.Event.subscribe('auth.statusChange', updateButton);
};
(function() {
var e = document.createElement('script'); e.async = true;
e.src = document.location.protocol
+ '//connect.facebook.net/en_US/all.js';
document.getElementById('fb-root').appendChild(e);
}());
</script>
</body>
</html>
<script>
(function() {
var e = document.createElement('script'); e.async = true;
e.src = document.location.protocol
+ '//connect.facebook.net/en_US/all.js';
document.getElementById('fb-root').appendChild(e);
}());
window.fbAsyncInit = function() {
FB.init({ appId: 'xxx',
status: true,
cookie: true,
xfbml: true,
oauth: true});
fbLoginStatus();
});
function fbLoginStatus()
{
FB.getLoginStatus(function(response) {
console.log(response);
if (response.status === 'connected') {
access_token = FB.getAuthResponse()['accessToken'];
myinfo();
} else {
fblogin();
}
});
}
function fblogin()
{
FB.login(function(response) {
if (response.authResponse) {
console.log(response);
access_token = FB.getAuthResponse()['accessToken'];
myinfo();
} else {
console.log('User cancelled login or did not fully authorize.');
}
}, {scope: 'email'});
}
function myinfo()
{
FB.api('/me', function(response) {
userid = response.id ;
alert(userid);
user_name = response.name;
alert(user_name);
});
}
</script>
Try this code, it will work exactly what you want.
Here's the code. I think the above code should work too.
<script>
window.fbAsyncInit = function(){
FB.init({
appId: '1486670758257443',
status: true,
cookie: true,
xfbml: true,
oauth: true,
version : 'v2.1'
});
fbLoginStatus();
};
(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 fbLoginStatus(){
FB.getLoginStatus(function(response) {
console.log(response);
if (response.status === 'connected') {
var access_token = FB.getAuthResponse()['accessToken'];
console.log(access_token);
} else {
fblogin();
}
});
}
function fblogin(){
FB.login(function(response) {
if (response.authResponse) {
var access_token = FB.getAuthResponse()['accessToken'];
console.log(access_token);
} else {
console.log('Authorization failed.');
}
},{ //permissions
scope: 'email'
});
}
</script>
and one thing to mention that, according to facebook doc, the popup should be opened by click event. Here's what they're saying.
Calling FB.login results in the JS SDK attempting to open a popup window. As such, this method should only be called after a user click event, otherwise the popup window will be blocked by most browsers.

Returning FB.getLoginStatus from a function

I can't figure out why fb_login_status_response is returning "Uncaught ReferenceError: fb_login_status is not defined" in the console when I run the following script (relevant snippet only) rather than returning a valid FB.getLoginStatus. Any ideas/feedback would be much appreciated. Thanks!
<script>
function load_fb(){
window.fbAsyncInit = function() {
FB.init({
appId : '251975954634982', // App ID
//channelURL : '//WWW.YOUR_DOMAIN.COM/channel.html', // 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
}); // closes FB.init
fb_login_status = FB.getLoginStatus(function(response){
console.log("FB.getLoginStatus: ", response.status);
// NOTE - the line above does log an accurate response.status in the console!
response.status;
// NOTE - I've tried putting the return statement here, but that doesn't work.
});
};
return fb_login_status; // NOTE - this return statement is what generates the "Uncaught ReferenceError:..." in console
}
// Load FB SDK Asynchronously
(function(d){
var js, id = 'facebook-jssdk'; if (d.getElementById(id)) {return;}
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "//connect.facebook.net/en_US/all.js";
d.getElementsByTagName('head')[0].appendChild(js);
}(document));
$(document).ready(function(){
sb_session_status = checkIfSignedIn();
if (sb_session_status == "valid"){
$(".loggedIn").css("display","block");
// Block of code for logged-in users goes here
}
else{
fb_login_status_response = load_fb();
console.log("fb_login_status_response: ", fb_login_status_response);
// NOTE - else clause here to check if user signed-in via facebook
}
});
</script>
Since the FB.getLoginStatus() call is async (not syncronous), then you will need to pass in a callback function to your checkIfSignedIn() function so it can be ran. See: https://developers.facebook.com/docs/reference/javascript/FB.getLoginStatus/
var checkIfSignedIn = function(callbackFn) {
FB.getLoginStatus(function(response){
console.log("FB.getLoginStatus: ", response.status);
if($.isFunction(callbackFn)) {
callbackFn(response.status=="connected" ? "valid" : "other");
}
});
};
$(document).ready(function() {
checkIfSignedIn(function(sb_session_status){
if (sb_session_status == "valid"){
// DO SOMETHING with the logged in user
$(".loggedIn").css("display","block");
} else {
// DO SOMETHING to get the user logged in
}
});
});