How to post to Facebook fanpage as fanpage, not user - javascript

How can I post on fanpage wall as fanpage not as a user - using javascript sdk.
RIght now on Init im receiving menage_pages and acquiring suitable fanpage id, how can i change call below?
var target = '/'+params.target+'/feed'
FB.api(target,
'post',
{ message: params.message,
link: params.link,
picture: params.picture,
caption: params.caption,
description: params.description,
name: params.name
}
,function(response) {
if (!response || response.error) {
$("#error").removeClass('hidden');
} else {
$("#success").removeClass('hidden');
}
});

You need the following permissions:
publish_stream
manage_pages
Now we call the page object to retrieve the page's access_token and then post with that token, something like:
function postToPage() {
var page_id = 'MY_PAGE_ID';
FB.api('/' + page_id, {fields: 'access_token'}, function(resp) {
if(resp.access_token) {
FB.api('/' + page_id + '/feed',
'post',
{ message: "I'm a Page!", access_token: resp.access_token }
,function(response) {
console.log(response);
});
}
});
}
Result:
More about this in my tutorial.

All you need is those three functionalities to be implemented:
First one is for setting the basic parameters for your Application(XXX-APP needs to be changed with your real id of application).
Second, function fol login to Facebook and granting needed permissions to be able to post to Facebook.
Third function is for posting to Facebook(XXX-page need to be changed with ID of the Page that you want to post something)
FB.init({ appId: 'XXX-APP', status: true, cookie: true, xfbml: true, oauth: true });
access_token = '';
function loginFB(){
FB.login(function(response) {
if (response.authResponse) {
access_token = FB.getAuthResponse()['accessToken'];
console.log('Access Token = '+ access_token);
} else {
console.log('User cancelled login or did not fully authorize.');
}
}, {scope: 'publish_stream,manage_pages'});
}
function postToPage() {
FB.api('/XXX-page', {fields: 'access_token'}, function(resp) {
if(resp.access_token) {
FB.api('/' + page_id + '/feed',
'post',
{ message: "MSG", access_token: resp.access_token }
,function(response) {
console.log(response);
});
}
});
}

Related

Fetching Album Ids from facebook account using graph api is working for developer account not for others

I tried to fetch the albums from facebook but I am getting null response from the facebook server. while I am using developer account its working fine but for others users its not working.Can anyone help me?
I am using the below code :
FB.login(function (response) {
if (response.authResponse) {
getFbUserData(callback);
}
}, { 'scope': 'id,first_name,last_name,email,link,gender,locale,picture,birthday,user_photos' });
function getFbUserData(callback) {
FB.api('/me', { locale: 'en_US', fields: 'id,first_name,last_name,email,link,gender,locale,picture,birthday,user_photos' },
function (response) {
callback(response);
});
}
FB.login(function (response) {
if (response.authResponse) {
var userId = FB.getAuthResponse()['userID'];
FB.api(
"/" + userId + "/albums",
{ fields: 'id,cover_photo,user_photos' },
function (albumResponse) {
alert(JSON.stringify(albumResponse));
}
);
});
}
});

Email not able to retrieve from facebook javascript SDK [duplicate]

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.

Facebook post as page

I know this question was asked already often, but I have been trying to fix this problem for like more than 6 hours now and I could use a little help. Error Message: Insufficient permssion to post to target on behalf of the viewer.
I'm trying to post as page, my code so far:
var pageID = "myPage";
FB.init({
appId: "myId",
secret: "mySecret",
status: true,
cookie: true,
});
function postToFeed() {
FB.login(function(response) {
FB.api('/me/accounts', function(response) {
var accessToken = "";
var data = response.data;
for (var i=0; i<data.length; i++) {
if (data[i].id == pageID) {
accessToken = data[i].access_token;
}
}
if (accessToken == "") {
alert("You are not allowed to post.");
}
else {
console.log(accessToken);
FB.api('/' + pageID + '/feed', 'post', {
message : "test",
link : 'Link',
picture : 'Imageurl',
name : 'test',
to : pageID,
from : pageID,
description : 'test'
}, function(response) {
if (!response || response.error) {
alert(JSON.stringify(response.error));
} else {
alert('Post ID: ' + response.id);
}
});
}
});
}, {scope: 'publish_actions,manage_pages,public_profile'});
}
When I echo my accessToken via console and copy the accessToken inside this code, it works perfectly. But that's not an solution because I want it to be dynamic:
function postToFeed() {
FB.login(function(response) {
FB.api('/' + pageID + '/feed', 'post', {
access_token: 'theAcccessToken',
message: "I'm a Page!",
}, function(response) {
console.log(response);
}
);
}, {scope: 'publish_actions,manage_pages,public_profile'});
}
And this does not work? (not sure what you want to do with the "to" and "from" parameters, so i removed them)
FB.api('/' + pageID + '/feed', 'post', {
message : 'test',
link : 'Link',
picture : 'Imageurl',
name : 'test',
description : 'test',
access_token: accessToken
}
The most important thing: You need publish_pages to post "as Page", not publish_actions.
Btw, a small optimization:
for (var i = 0; i < data.length; i++) {
if (data[i].id === pageID) {
accessToken = data[i].access_token;
break;
}
}
if (accessToken === "") {
alert("You are not allowed to post.");
}
...always use typesafe comparison :)

Facebook Post image to Facebook fan page with Javascript

It's funny really...
This is my script
var imgURL = "http://onseiekoerant.com/upload/uploads/1411504661_2786.jpg";
FB.api('/'MY PAGE ID'/photos', 'post', {
message: 'Website Genius',
url: imgURL,
access_token: accessToken
}, function (response) {
if (!response || response.error) {
alert('Error occured');
} else {
alert('Post ID: ' + response.id);
//alert('Post ID: ' + response.post_id);
}
console.log(response);
});
When I call this function, it returns te restponse the the POST_ID. It's suposed to be successfull, but nothing is on my facebook fan page.
To give additional info, the access token cames from my currently signed in user of facebook, which is admin of the page.
What am I missing?

How to publish something on user's friend stream/wall in an application

In a Facebook application, I need to publish a user's friend stream a mlessage.
how can i figure out of that?
Thanks
send HTTP POST request to the following address https://graph.facebook.com/FRIEND_ID/feed
it returns the ID of posted message on success
here's the example code:
var msg = 'hello world';
FB.api('/YOUR_FRIEND_ID/feed', 'post', { message: msg }, function(response) {
if (!response || response.error) {
alert('Error occured');
} else {
alert('Post ID: ' + response.id);
}
});
You can also use the javascript API for posting. The manual has sample code.
https://developers.facebook.com/docs/reference/javascript/FB.ui/
FB.ui(
{
method: 'feed',
to: friendId,
name: 'title',
link: 'http://host.com/title_link.com',
picture: 'http://host.com/image.jpg',
description: 'description',
caption: 'caption',
},
function(response) {
// Check for a posting to wall
if (response && response.post_id) {
// do some logging
}
}
});

Categories

Resources