How to share with access token? - facebook

I have write this code but it does work only if I am already logged in facebook, otherwise appears a popup window that require me email and password to login in facebook.
This is the code:
window.fbAsyncInit = function () {
FB.init({
appId: 'xxx',
frictionlessRequests: true,
status: true,
cookie: true,
xfbml: true,
oauth: true
});
function update(response) {
if (response.authResponse) {
FB.api('/me', function (info) {
login(response, info);
});
} else {
}
}
FB.getLoginStatus(update);
};
(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);
}());
function login(response, info) {
if (response.authResponse) {
publish();
}
}
function publish() {
var publish = {
method: 'feed',
access_token: '<?php echo $token; ?>',
message: 'How are you ?',
name: 'hi friends',
caption: 'yuhuuuuuuuu',
description: (' '),
link: 'http://www.example.com',
picture: 'http://cdn1.hark.com/images/000/004/514/4514/original.jpg',
actions: [{
name: 'Hello',
link: 'http://www.example.com/'
}],
user_message_prompt: 'Share on facebook'
};
FB.ui(
publish, function (response) {
if (response && response.post_id) {
alert('Post was published.');
} else {
alert('Post was not published.');
}
});
}

In your update method, in the blank else you should call the FB.login method:
Calling FB.login prompts the user to authenticate your application
using the OAuth Dialog.
However, you can't just do this:
function update(response) {
if (response.authResponse) {
FB.api('/me', function (info) {
login(response, info);
});
} else {
FB.login(function(response) {
if (response.authResponse) {
console.log("user is logged in!", response.authResponse);
}
});
}
}
Since as it states in the documentation:
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.
You'll have to show a user a button or something that tells him to click in order to login, and then you can call the FB.login method.

Related

facebook programmatically post on a facebook page with a big photo

I've created a fake facebook page (entertainment page).
On the left of the attached image, I made a first post manually (the one below with the
big photo), and one programmatically (the one above with the small photo).
The code I used for the small photo looks like this:
FB.api(
'https://graph.facebook.com/[myAppId]/feed',
'post',
{
message: 'this is a grumpy cat',
description: "This cat has been lost for decades now, please call at 654321486",
picture: "http://laughingsquid.com/wp-content/uploads/grumpy-cat.jpg"
},
function (response) {
if (!response) {
alert('Error occurred.');
} else if (response.error) {
document.getElementById('result').innerHTML =
'Error: ' + response.error.message;
} else {
document.getElementById('result').innerHTML =
'<a href=\"https://www.facebook.com/' + response.id + '\">' +
'Story created. ID is ' +
response.id + '</a>';
}
}
);
But I'm not happy with it:
the application I'm working on make a list of lost animals,
so it would be much greater with big photos.
I didn't see any example of how to do it on the facebook developer pages.
I believe this is possible, but I've not found it out yet.
Have you guys already gone through this problem before?
There are two things that you will need to do to achieve this. I'm not 100% sure if the JS-SDK will allow you to do the second step, but you can use a server side SDK if needed.
The application will need to request the manage_pages and publish_stream permission. Then make a call to /{user-id}/accounts which will return all pages the authorized user manages, and their respective page access tokens.
Store in a variable the page access token returned for the page you want to post to. Set the photo you want to upload as the source parameter (must be local to the server running the code) and make a POST request to /{page_id}/photos using the page access token (NOT the application access token!).
So it would be along the lines of:
FB.api('/{page_id}/photos', 'post', { source: 'path/to/image.jpg', access_token: {page_access_token}, message: 'hey heres a photo' }, function(response) {
if (!response || response.error) {
alert('Error occured');
} else {
alert('Post ID: ' + response.id);
}
});
I believe the application also needs to specify fileUpload as true when initializing.
I would be happy to share my PHP code to do this if it would be helpful to you.
Finally, I did it!
I'm posting the solution, thanks to cdbconcepts for pointing me in the right direction.
After reading the doc again:
https://developers.facebook.com/docs/reference/api/photo/
They say that:
"You can also publish a photo by providing a url param with the photo's URL."
The url doesn't have to be on the same server, as shown in the example below,
and it works with the js-sdk.
So here is the final code that works for me:
<html>
<head>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
</head>
<body>
<div id="fb-root"></div>
<script>
var appId = 'Replace with your appId';
window.fbAsyncInit = function () {
FB.init({
appId: appId,
status: true, // check login status
cookie: true, // enable cookies to allow the server to access the session
xfbml: true // parse XFBML
});
var options = {
scope: 'manage_pages, publish_stream'
};
FB.Event.subscribe('auth.authResponseChange', function (response) {
if (response.status === 'connected') {
testAPI();
} else if (response.status === 'not_authorized') {
FB.login(function () {
}, options);
} else {
FB.login(function () {
}, options);
}
});
};
// 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 + '.');
});
}
function error(msg) {
document.getElementById('result').innerHTML = 'Error: ' + msg;
}
function postApi() {
var myPageID = '484364788345193';
var targetPageName = 'Entertainment page of ling';
var pathToImg = 'http://laughingsquid.com/wp-content/uploads/grumpy-cat.jpg';
var accessToken = null;
FB.api(
'https://graph.facebook.com/me/accounts',
function (response) {
if (!response || response.error) {
console.log(response);
error('Error occured');
} else {
console.log(response);
for (var i in response.data) {
if (targetPageName === response.data[i].name) {
accessToken = response.data[i].access_token;
}
}
if (accessToken) {
FB.api(
'https://graph.facebook.com/' + myPageID + '/photos',
'post',
{
url: pathToImg,
access_token: accessToken,
message: "Tadaam"
},
function (response) {
if (!response || response.error) {
console.log(response);
error('Error occured');
} else {
console.log(response);
alert("PostId: " + response.id);
}
}
);
}
else {
error("Page not found in the accounts: " + targetPageName);
}
}
}
);
}
function logout() {
FB.logout();
}
$(document).ready(function () {
$("#logout").click(function () {
logout();
});
$("#post1").click(function () {
postApi();
});
});
</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. -->
<fb:login-button show-faces="true" width="200" max-rows="1"></fb:login-button>
<button id="logout">Logout</button>
<button id="post1">post something</button>
<div id="result"></div>
</body>
</html>

Facebook JS SDK -Access Tokens unable to post actions

When I use the code below nothing happens,I am unable to understand why this is so
function graphStreamPublish(){
var passString = '?[OBJECT]=http://entrancesuccess.net&access_token=' + accesstoken;
FB.api('/me/[APPNAMESPACE]:[ACTION]' + passString,'post',
function(response) {
showLoader(false);
if (!response || response.error) {
alert('Error occured');
} else {
alert('Post ID: ' + response.id);
}
});
}
but, when I just simply copy-paste the Access Token(YTWYDGFXVVZG456AVGAFV45HGCZXHGFACGFCGFXDG546FXGFXJGFXGFXGXFJXGFXG) in the variable "passString" everything works fine and actions are published on user activity on facebook.
Example:
function graphStreamPublish(){
var passString = '?[OBJECT]=http://entrancesuccess.net&access_token=YTWYDGFXVVZG456AVGAFV45HGCZXHGFACGFCGFXDG546FXGFXJGFXGFXGXFJXGFXG';
The rest of the code is below(if required):
window.fbAsyncInit = function() {
FB.init({ appId: 'XXXXXXXXXXXXX', //change the appId to your appId
status: true,
cookie: true,
xfbml: true,
oauth: true});
showLoader(true);
function updateButton(response) {
button = document.getElementById('fb-auth');
userInfo = document.getElementById('user-info');
if (response.authResponse) {
//user is already logged in and connected
FB.api('/me', function(info) {
login(response, info);
});
button.onclick = function() {
FB.logout(function(response) {
logout(response);
});
};
} else {
//user is not connected to your app or logged out
button.innerHTML = 'Login';
button.onclick = function() {
showLoader(true);
FB.login(function(response) {
if (response.authResponse) {
FB.api('/me', function(info) {
login(response, info);
});
} else {
//user cancelled login or did not grant authorization
showLoader(false);
}
}, {scope:'publish_stream,public_action'});
}
}
}
// 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);
}());
function login(response, info){
if (response.authResponse) {
var accessToken = response.authResponse.accessToken;
userInfo.innerHTML = '<img src="https://graph.facebook.com/' + info.id + '/picture">' + info.name
+ "<br /> Your Access Token: " + accessToken;
button.innerHTML = 'Logout';
showLoader(false);
document.getElementById('other').style.display = "block";
}
}
function logout(response){
userInfo.innerHTML = "";
document.getElementById('debug').innerHTML = "";
document.getElementById('other').style.display = "none";
showLoader(false);
}
I’d say there is no variable accesstoken in your function graphStreamPublish.
You’re using the var keyword in the function login, which makes it a local variable – so it’s contents are thrown away once that function is done.
You could do the assignment without var, then it’d be a global variable, and graphStreamPublish should be able to access it.
But normally you should not need to pass the access token explicitly at all, because the JS SDK is perfectly capable of passing it by itself in the background, without any need for you to pass it around actively by yourself.

Facebook login button ins't working for IE

window.fbAsyncInit = function () {
FB.init({
appId: '#',
status: true,
cookie: true,
xfbml: true,
oauth: true
})
FB.getLoginStatus(function (response) {
if(response.status === 'connected') {
var uid = response.authResponse.userID;
alert(uid);
FB.api('/' + uid, {
fields: 'name,email,id,picture'
}, function (result) {
//Code
})
}
})
FB.Event.subscribe('auth.login', function (response) {
// do something with response
login();
});
FB.Event.subscribe('auth.logout', function (response) {
logout();
});
FB.getLoginStatus(function (response) {
if(response.session) {
// logged in and connected user, someone you know
login();
}
});
};
function login() {
FB.getLoginStatus(function (response) {
if(response.status === 'connected') {
var uid = response.authResponse.userID;
// alert(uid);
FB.api('/' + uid, {
fields: 'name,email,id,picture'
}, function (result) {
//code
})
}
})
}
function logout() {
//code
}
(function () {
var e = document.createElement('script');
e.type = 'text/javascript';
e.src = document.location.protocol + '//connect.facebook.net/en_GB/all.js';
e.async = true;
document.getElementById('fb-root').appendChild(e);
}());
I use the <div class="fb-login-button">Sign in with Facebook</div> for the login button to appear.
I have put this script in a JS file and i'm using it on my JSP.
I get a login authentication screen in firefox and chrome, but somehow the button doesn't show in IE 7,8,9
Idk if this is your problem or not, but you might try adding:
<html xmlns:fb="http://www.facebook.com/2008/fbml">
To your html document
An explanation here:
http://www.zolton.org/2011/04/facebook-fbml-tags-fail-to-load-in-ie/

how to get email id of Facebook user using javascript sdk

I am using JavaScript API to create my app for Facebook. The problem is, it's returning
email = undefined.
I don't know why? And if I use Facebook login/logout button on my app then the alert shows correct email id of the user but I don't want to do that.
What am I missing?
Here is my code:
<p><fb:login-button autologoutlink="true" perms="user_about_me,email"></fb:login-button></p>
<script>
window.fbAsyncInit = function () {
FB.init({ appId: '250180631699888', status: true, cookie: true,
xfbml: true
});
FB.getLoginStatus(function (response) {
if (response.session) {
greet();
}
});
};
(function () {
var e = document.createElement('script');
e.type = 'text/javascript';
e.src = document.location.protocol +
'//connect.facebook.net/en_US/all.js';
e.async = true;
document.getElementById('fb-root').appendChild(e);
} ());
function greet() {
FB.api('/me', function (response) {
alert('Welcome, ' + response.name + "!");
alert('Your email id is : '+ response.email);
});
}
</script>
// https://developers.facebook.com/docs/javascript/reference/FB.api/
// v2.4
FB.api('/me', { locale: 'en_US', fields: 'name, email' },
function(response) {
console.log(response.email);
}
);
here is example how i retrieve user name and e-mail:
<div id="fb-root"></div>
<script src="http://connect.facebook.net/en_US/all.js"></script>
<script>
$(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
});
FB.getLoginStatus(function(response) {
if (response.status == 'connected') {
getCurrentUserInfo(response)
} else {
FB.login(function(response) {
if (response.authResponse){
getCurrentUserInfo(response)
} else {
console.log('Auth cancelled.')
}
}, { scope: 'email' });
}
});
function getCurrentUserInfo() {
FB.api('/me', function(userInfo) {
console.log(userInfo.name + ': ' + userInfo.email);
});
}
});
</script>
According to the latest info on the facebook page you should use 'scope' instead of perms.
https://developers.facebook.com/docs/reference/javascript/FB.login/
If you visit
https://developers.facebook.com/tools/console/
and use the fb-api -> user-info example as a starting point, then logout and back in again, it should ask you for email perms and you can see your email being printed. It is done using response.email as you mention in your post.
<button id="fb-login">Login & Permissions</button>
<script>
document.getElementById('fb-login').onclick = function() {
var cb = function(response) {
Log.info('FB.login callback', response);
if (response.status === 'connected') {
Log.info('User logged in');
} else {
Log.info('User is logged out');
}
};
FB.login(cb, { scope: 'email' });
};
</script>
Use this to for extra permission
for more details visit :
https://www.fbrell.com/examples/
In this code i have get user data form facebook and store into my database using ajax
FB.login(function(response) {
if (response.authResponse) {
FB.api('/me?fields=email,name,first_name,last_name', function(response)
{
FB.api(
"/"+response.id+"/picture?height=100",
function (responses) {
//console.log(responses.data.url)
response['profile_pic']=responses.data.url;
$.ajax({
type:"POST",
url:'<?php echo base_url(); ?>'+'home/facebook_get_signup',
data:response,
success:function(res)
{
if(res=='success')
{
window.location='<?php echo base_url(); ?>';
}
if(res=='exists')
{
window.location='<?php echo base_url(); ?>';
}
}
});
}
)
});
} else {
console.log('User cancelled login or did not fully authorize.');
}
// handle the response
}, {scope: 'email,user_likes'});
There are a couple of things wrong with your solution. First of all you are using the old authentication scheme. You should use the new one described here :
https://developers.facebook.com/docs/reference/javascript/
You need to add the oauth:true to your init function, and make sure that your getLoginStatus looks for the new type of response.
When that is said you need to make sure you have the right permissions to see the users e-mail. You can see the required permissions here:
http://developers.facebook.com/docs/reference/api/user/
You get those by using the FB.login function as described by TommyBs in another answer.
Once you have those options you can use the FB.api function to get the e-mail.

posting to friends wall using facebook javascript sdk

How can I post to a friends wall using the facebook javascript SDK?
In addition to #ifaour's answer on FB.api...
Set oauth and status parameters in FB.init
Request extended permission, publish_stream, via FB.login
Other resources:
using facebook stream publish
Complete example...
<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!');
// Post message to friend's wall
var opts = {
message : 'Post message',
name : '',
link : 'http://www....',
description : 'Description here',
picture : 'http://domain.com/pic.jpg'
};
FB.api('/FRIEND_ID/feed', 'post', opts, function(response)
{
if (!response || response.error)
{
alert('Posting error occured');
}
else
{
alert('Success - Post ID: ' + response.id);
}
});
}
else
{
alert('Not logged in');
}
}, { scope : 'publish_stream' });
};
</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 -->
You need to use the FB.api method, something like:
var body = 'Reading Connect JS documentation';
FB.api('/FRIEND_ID/feed', 'post', { message: body }, function(response) {
if (!response || response.error) {
alert('Error occured');
} else {
alert('Post ID: ' + response.id);
}
});