API Key Error in Facebook Connect (javascript sdk) - javascript

I am trying to implement Facebook Connect on a website. I am trying to work with Javascript SDK of Facebok. I am new to it and unfortunately most of links provided in Facebook WIKI are out of date... Returning 404 not found. Anyway I added this code before the ending </body>:
<script src="http://static.ak.fbcdn.net/connect.php/js/FB.Share" type="text/javascript"></script>
<div id="fb-root"></div>
<script src="http://static.ak.connect.facebook.com/js/api_lib/v0.4/FeatureLoader.js.php" type="text/javascript"> </script>
<script src="http://connect.facebook.net/en_US/all.js"></script>
<script>
FB.init({
appId : '12344', // my real app id is here
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : false // parse XFBML
});
FB.login(function(response) {
if (response.session) {
if (response.perms) {
alert('user is logged in and granted some permissions');
// user is logged in and granted some permissions.
// perms is a comma separated list of granted permissions
} else {
alert('user is logged in, but did not grant any permissions');
// user is logged in, but did not grant any permissions
}
} else {
alert('user is not logged in');
// user is not logged in
}
}, {perms:'email'});
</script>
And I have a login button at some other place (much before the above scripts) in the same page rendered with:
<fb:login-button v="2">Connect with Facebook</fb:login-button>
This button renders as a normal fb connect button and clicking it opens a new popup window as it normally should. Problem is that it shows 'invalid api key specified' error. On inspecting address bar of popup, I see that api_key=undefined is passed to it :(
Any idea about this? I am trying to fix this for last 5 hours now... Please help me found out why correct API key is not being passed to popup window.
Thanks in advance.

I'm doing the same thing, and i found an example that is very simple to implement and understand (here thay use jQuery, but you can do the same without libraries):
<body>
<div>
<button id="login">Login</button>
<button id="disconnect">Disconnect</button>
</div>
<div id="user-info" style="display: none;"></div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<div id="fb-root"></div>
<script src="http://connect.facebook.net/en_US/all.js"></script>
<script>
// initialize the library with the API key
FB.init({ appId : '12344' });
// fetch the status on load
FB.getLoginStatus(handleSessionResponse);
$('#login').bind('click', function() {
FB.login(handleSessionResponse);
});
$('#disconnect').bind('click', function() {
FB.api({ method: 'Auth.revokeAuthorization' }, function(response) {
clearDisplay();
});
});
// no user, clear display
function clearDisplay() {
$('#user-info').hide('fast');
}
// handle a session response from any of the auth related calls
function handleSessionResponse(response) {
// if we dont have a session, just hide the user info
if (!response.session) {
clearDisplay();
return;
}
// if we have a session, query for the user's profile picture and name
FB.api(
{
method: 'fql.query',
query: 'SELECT name, pic FROM profile WHERE id=' + FB.getSession().uid
},
function(response) {
var user = response[0];
$('#user-info').html('<img src="' + user.pic + '">' + user.name).show('fast');
}
);
}
</script>
</body>
Look here for the entire code, and here you can find other resource.

I had set my facebook connect address to have www and I was accessing my test site with non www, when I switched to the www version fb connect worked fine.

You need to set the canvas post-authorize url, and make sure that the base canvas url is a prefix of the post-authorize url.

Related

how to read device token (parse.com) with phonegap/javascript iOS

I'm developing an app for iOS with Phonegap and I'm using parse.com for push notification with iOS SDK included with Xcode. In my app users can login and I need to know the device token of the users to send to them single push notification, I know how to send the device token with the user/password during log in but I don't know how to read it, I don't know if there is any way directly with Phonegap or if I need to read it with C and then pass to Javascript with a variable.
EDIT: I'm trying to use Malloc's solution, and i have this problem. i installed plugin via CLI but i don't understand how to use it. I create a sample page
<html>
<head>
</head>
<body>
<script type="text/javascript> parsePlugin.getInstallationId(function(id) { document.write(id); }, function(e) { alert('error'); });
</script>
</body>
</html>
but of course i obtain a white page because this code don't print anything.
What i need to do if i want to assign installationid to a javascript variable?
thanks
UPDATE 2
Now I have this code in my sample page
<html>
<head>
</head>
<body>
<script type="text/javascript">
var appId = p3Z10Nj2GdmfuxCX1a9liu5VlPadbvgW********;
var clientKey = lFRl93OEDM0bFTVOKaA1iIXV4vuWS3S9********;
//
parsePlugin.initialize(
appId,
clientKey,
function() {
// The parse plugin is initialized correctly, query the installation id
parsePlugin.getInstallationId(
function(id) {
// Installation id is correctly queried
console.log('The installation id is: '+id);
},
function(e) {
alert('An error has occured while querying the installation id of your device');
});
},
function(e) {
alert('An error has occured while initializing the parse plugin');
});
</script>
</body>
</html>
UPDATE 3
<html>
<head>
</head>
<body>
<script type="text/javascript">
$(window).load(function() {
var appId = p3Z10Nj2gm8siK;
var clientKey = lFRl93OEDM0bFTVOKaA1iIXV4vu;
//
parsePlugin.initialize(
appId,
clientKey,
function() {
// The parse plugin is initialized correctly, query the installation id
parsePlugin.getInstallationId(
function(id) {
// Installation id is correctly queried
console.log('The installation id is: '+id);
},
function(e) {
alert('An error has occured while querying the installation id of your device');
});
},
function(e) {
alert('An error has occured while initializing the parse plugin');
});
}
</script>
</body>
</html>
What you need is the device related installation id. You may need to use a plugin for this.
The plugin I have used, and which worked as expected, can be found here.
After installing it with the CLI, you just call the parsePlugin.getInstallationId function which will return the installation id for your device.
Keep in mind that you will get ONE installation id per device but that doesn't mean that you have always only one. Since you may run the app on more than a device, each one has his installation id.
Update:
The plugin should be initialized before calling getInstallationId:
$(window).load(function() {
var appId = YOUR_APP_ID;
var clientKey = YOUR_KEY_CLIENT;
//
parsePlugin.initialize(
appId,
clientKey,
function() {
// The parse plugin is initialized correctly, query the installation id
parsePlugin.getInstallationId(
function(id) {
// Installation id is correctly queried
console.log('The installation id is: '+id);
},
function(e) {
alert('An error has occured while querying the installation id of your device');
});
},
function(e) {
alert('An error has occured while initializing the parse plugin');
});
}
You should be using a plugin as others pointed out, here is another plugin that does the same job.
https://github.com/ccsoft/cordova-parse
PS: I am the author of the plugin.

PHP & Javascript Asynchronous permissions Authentication - Facebook API's

What would I need to do to allow asynchronous login/authentication (permissions) between an external site for mobiles and a facebook tab app.
I essentially need one system that does both desktop/mobile.
Example
Case 1 (Mobile/external access) - Logs in using Javascript using login and works fine app works perfectly. - This works the way it's supposed to which is great!
case 2(Facebook user - tab app) - Logs in and gains permissions through PHP SDK onviously the user is already logged in. My problem is javascript knows the user is logged in but still asks the user to login for the permissions they've already given.
TLDR: Why won't Javascript pickup the Auth cookie from the PHP SDK and recognise the user has the correct permissions from PHP? This login flow is fine when the user has logged in via mobile or externally to the app. I've tried them seperately and they work fine just won't work together.
I've seen it working the other way around but I want JS only or PHP>JS NOT JS>PHP.
*Edit
window.fbAsyncInit = function()
{
FB.init({
appId : 'APP_ID_HERE', // 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
oauth : true // enable OAuth 2.0
});
my event handlers for login/logout and likes goes here.
(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 fblogin()
{
FB.login(function(response)
{
},
{ scope: 'email, user_likes' }
);
}
function createRequestObject() {
var obj;
var browser = navigator.appName;
if(browser == "Microsoft Internet Explorer")
{
obj = new ActiveXObject("Microsoft.XMLHTTP");
}
else
{
obj = new XMLHttpRequest();
}
return obj;
}
Login for mobile/desktop works great it's picking up the scope but when I use the following code to setup the tab app, the permissions won't transfer to the javascript session.
PHP Code (which works):
<?php
require_once 'src/facebook.php'; // get facebook sdk
$facebook = new Facebook(array(
'appId' => 'APP ID HERE',
'secret' => 'APP SECRET HERE'
));
$user = $facebook->getUser();
$location = "". $facebook->getLoginUrl(array('scope' => 'email, user_likes'));
// check if we have valid user
if ($user) {
try {
// Proceed knowing you have a logged in user who's authenticated.
$permissions = $facebook->api('/me/permissions', 'get', array('access_token'=>$access_token));
} catch (FacebookApiException $e) {
$fb_user_id = NULL;
// seems we don't have enough permissions
// we use javascript to redirect user instead of header() due to Facebook bug
print '<script language="javascript" type="text/javascript"> top.location.href="' . $location .'"; </script>';
// kill the code so nothing else will happen before user gives us permissions
echo $e->getMessage();
die();
}
} else {
// seems our user hasn't logged in, redirect user to a FB login page
print '<script language="javascript" type="text/javascript"> top.location.href="'. $location .'"; </script>';
// kill the code so nothing else will happen before user gives us permissions
die();
}
// at this point we have an logged in user who has given permissions to our APP
// Facebook opens canvas page (which is the mobile/external page) but doesn't transfer permissions.
PHP works great it transfers the user to the mobile (canvas) page with login/like button. How do I get PHP to pass the perms to my canvas where my mobile/desktop site is?
*EDIT 2:
HTML/PHP:
<div class="container">
<div id="fb-root"></div>
<div id="facebook-div">
<fb:login-button autologoutlink="true" scope="email,user_likes" size="large"></fb:login-button>
<div id="facebook-right" class="fb-like" data-href="https://www.facebook.com/154456204613952" data-width="90" data-layout="button_count" data-show-faces="false" data-send="false"></div>
</div>
//Rest of the code here
Managed to resolve it thanks for your help!
After the PHP instantiated I didn't include the Canvas php file after the user was authenticated... I've been pulling my hair out for months trying to resolve this! This authentication gets passed to Javascript which deals with everything!
This means that both PHP and Javascript calls are able to work within the same application.

Facebook JavaScript API - Login failure in Chrome

The below code is from the official Facebook developer pages, and works in FF and Safari, and sometimes in Chrome — but more often not in Chrome.
On Snow Leopard with the latest Chrome, I click the login button and see a little flicker as the FB login dialog opens and closes. If, in my FB account, I remove and re-add the app, I get asked for permissions, but the auth.authResponseChange event never seems to fire.
Does anyone know if this is a bug, or where I might find a solution that doesn't require me to manually poll the server?
Is this a product of Google+ vs. Facebook?!
<html>
<head></head>
<body>
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({
appId : $APP_ID$, // App ID from the app dashboard
channelUrl : $channelUrl$, // Channel file for x-domain comms
status : true, // Check Facebook Login status
cookie : true,
oauth : true,
xfbml : true // Look for social plugins on the page
});
// 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) {
console.log('auth.authResponseChange fired');
// 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/ -->
<!-- scope='publish_stream,read_stream' -->
<fb:login-button show-faces="true" width="200" max-rows="1"></fb:login-button>
</body>
</html>
Go into chrome settings - advanced settings; Under privacy click "content settings". See if the "Block 3rd party cookies and site data" is checked.
I'm having a similar issue where in chrome the js-sdk will give me the momentary fb popup, but doesnt actually seem to log the user in or recognize the user being logged in/authorized. In my case I think I've narrowed my issue down to that setting.
If you have it enabled, try disabling it to see if that fixes it for you... although that's really just a diagnostic step, it's not a resolution since you would still have users who have that setting enabled.
I'm trying to determine the workaround if any.. possibly involving the use of fb login flow "for web" (ie not using their sdk and thereby potentially avoiding the use of 3rd-party cookies)
here's my post on my version of this issue... can facebook javascript/php SDK's "talk" to each other if 3rd-party cookies are disabled? facebook->getUser() returns 0

Facebook javascript events not fired any way i turn it

I am using Facebook JavaScript SDK with my site, there is an option there to set events when user login/logout from Facebook so i can show him notifications in my website.
can't manage it to work, tried everything, also using offline_access permission.
here is my html code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:og="http://ogp.me/ns#" xmlns:fb="http://www.facebook.com/2008/fbml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="description" content="blabla" />
<meta name="keywords" content="blabla" />
<meta property="og:title" content="blabla" />
<meta property="og:url" content="http://XXX/" />
<meta property="fb:app_id" content="XXX" />
<title>Facebook Notifier</title>
<link href="<?php echo base_url(); ?>styles/style.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<script type="text/javascript" src="<?php echo base_url(); ?>js/jquery.cookie.js"></script>
<script src="http://connect.facebook.net/en_US/all.js"></script>
<script type="text/javascript" src="<?php echo base_url(); ?>js/global.js"></script>
</head>
<body>
<div id="fb-root"></div>
<div id="my_div">
</div>
</a>
</body></html>
here is my js code:
FB.init({
appId : 'XXX',
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true, // parse XFBML
oauth : true, // enables OAuth 2.0
channelUrl : 'http://XXX/channelUrl'
});
FB.getLoginStatus(function(response) {
if (response.authResponse) {
connected = true;
}
else{
connected = false;
}
}, true);
FB.Event.subscribe('auth.authResponseChange', function(response) {
if(response.authResponse) connected = true;
else connected = false;
});
in the end of this js code i have a function that run every few seconds checking the connection variable, its a global one. and it not changed i tried to login/logout from facebook and no event fires.
only when i refresh the page i can get the user status.
in firefox firebug console i get the message (also tried in chrome, ie):
uncaught exception: Error: https://www.facebook.com Proxy.InstallTrigger
i tried to solve it by doing everything i can find about this error in google and also in stackoverflow and still not working.
btw: when i wrote XXX in the original files its my url or my appid.
thanks.
I've always been a bit skeptical about the auth. events the Facebook fires so in your case I'd prob just setup a poller myself to check the auth status of the connected users. Like this:
var connected;
FB.init({
appId : 'XXX',
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true, // parse XFBML
oauth : true, // enables OAuth 2.0
channelUrl : 'http://XXX/channelUrl'
});
FB.getLoginStatus(handleUserStateChange);
FB.Event.subscribe('auth.authResponseChange', handleUserStateChange);
function handleUserStateChange(response) {
connected = !!response.authResponse;
}
setInterval(function() {
FB.getLoginStatus(handleUserStateChange, true);
}, 10000) // poll every 10 seconds
Also as you defined status: true in the FB.init config object you don't need to pass the second parameter to FB.getLoginStatus at the start as that forces a check to Facebook instead of reading from the stored variable (which is already the latest information as we just initd).
It looks like you might have a variable scope problem with connected.
Something like this might help:
var connected; // define/initialize connected variable outside functions
FB.init({
appId : 'XXX',
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true, // parse XFBML
oauth : true, // enables OAuth 2.0
channelUrl : 'http://XXX/channelUrl'
});
FB.getLoginStatus(function(response) {
if (response.authResponse) {
connected = true;
}
else{
connected = false;
}
}, true);
FB.Event.subscribe('auth.authResponseChange', function(response) {
if(response.authResponse) connected = true;
else connected = false;
});
I would use console.log() from within your functions that respond to subscribed events to see what is really happening (or not happening). Then write your real code based on what console.log() tells you.
I am doing FB.Event.subscribe in a function that is invoked on document ready event:
<script>(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/all.js#xfbml=1&appId=...";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
$("document").ready(function(){
FB.Event.subscribe('edge.create',
function(response) {
alert('You liked the URL: ' + response);
});
});
</script>
Or here there is another example of making sure that FB is initialised before you do any invocations.
I'm all new into FB development and ran into the same issue a couple days ago.
I tried pretty much all answers and solutions that are out there but nothing
worked out. The damn event wouldn't want to fire no matter what I did in my
latest VS project. However I remembered getting this to work in my first VS project
where I followed a tutorial on the same matter. After a while I checked that initial project and to my surprise it fired there and not in my other one.
Finally I realized that the Canvas Url on FB (app settings) was the culprit :
h t t p: // localhost:15497/
It was set to my localhost with the port used in my other project. I changed the port number and suddenly it also worked in my other project.
Make sure that the canvas url in the FB app settings matches where your Visual Studio runs the app. Also change the value once you deploy your web app.
If you're in 2022 wondering why it won't fire. Enable 3rd party cookies, this worked for me.

FB.api is not a function

I'm trying to pull all of the posts on a users wall. I got an example running that connects to FB okay, but when I try to use FB.api to get the username (I am definitely successfully connected), I get FB.api is not a function. Some searching found this which suggests that I'm using the wrong API link, but when I try the new one (which seems to connect using the same method) everything firebug NET panel says it loads successfully, there are no errors. . . nothing happens at all.
Here is the code (replace the http://connect.facebook.net/en_US/all.js link with http://static.ak.connect.facebook.com/js/api_lib/v0.4/FeatureLoader.js.php for the code to work up until the error I mentioned):
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:fb="http://www.facebook.com/2008/fbml">
<head>
<script src="http://connect.facebook.net/en_US/all.js" type="text/javascript"></script>
<script type="text/javascript">
function grab(){
FB.api('/me', function(response) {
alert(response.name);
});
}
function update_user_box() {
var user_box = document.getElementById("user");
user_box.innerHTML =
"<div>"
+ "<fb:profile-pic uid='loggedinuser' facebook-logo='true'></fb:profile-pic>"
+ " Welcome, <fb:name uid='loggedinuser' useyou='false'></fb:name>"
+ "</div>"
+ "try me";
FB.XFBML.Host.parseDomTree();
}
</script>
</head>
<body>
<div id='user'><fb:login-button onlogin="update_user_box();"></fb:login-button></div>
<br><br>
<div id="fb-root"></div>
<script type="text/javascript">
FB.init("b07e858317c9069d450023b7500b4511", "xd_receiver.htm", {"ifUserConnected": update_user_box});
</script>
</body>
</html>
thanks for any and all help!
You're using methods from two different SDKs. FB.api is part of the new SDK (all.js), and FB.XFBML.Host.parseDomTree() is part of the old SDK (feature loader). For example, to parse the dom tree with the new SDK, you call FB.XFBML.parse(). I recommend you pick one of the two SDKs, preferably the new SDK if you are just starting since the old SDK is deprecated.
I guess you are not intializing correctly. I had similar issues... it was not clear to me which one is oAuth2.0 and which FB-Connect. It seemed confusing. I followed the example (below), it worked for me. See here
<div id="fb-root"></div>
<script src="http://connect.facebook.net/en_US/all.js"></script>
<script>
FB.init({
appId : 'YOUR APP ID',
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
</script>
Hope this helps.
On a side note, you might need extended permission to access publish_stream, read_stream. You should refer here
Typeoneerror is right, you're mixing SDK's.
Here's how I'm initializing the newer JS SDK, using event.subscribe to be sure the SDK is initialized AND the user has authenticated on the JS side before moving forward with any API calls or letting my game try to load etc.
<div id="fb-root"> </div>
<script>
window.fbAsyncInit = function() {
FB.init({appId: 'YOUR_APP_ID', status: true, cookie: true, xfbml: true});
FB.Canvas.setSize({ width: 760, height: 1000 }); // use this to increase canvas height
FB.Event.subscribe('auth.login', function(response) {
// You can call your function that requires FB.whatever here...
});
};
(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>
I'm also using the PHP SDK to perform the initial auth... If the user is not authed, I echo a JS redirect to our the login url (available from the PHP SDK method getLoginUrl). Hope that helps.

Categories

Resources