I am trying to post to my facebook's wall using javascript SDK. I am first getting user access token. Then using user access token i am getting page access token and including it while posting to a wall. I'm getting following error
here's my code : First am trying to login using FB.login
FB.login(function(response) {
if (response.authResponse) {
console.log('Welcome! Fetching your information.... ');
FB.api('/me', function(response) {
console.log('Good to see you, ' + response.name + '.'+JSON.stringify(response));
});
} else {
console.log('User cancelled login or did not fully authorize.');
}
},{scope: 'manage_pages,publish_pages'});
Then trying to post to a page.
var body = 'Reading JS SDK documentation';
FB.getLoginStatus(function(response) {
console.log('login status',response);
if(!(response.status === 'connected')){
location.href = './fb-login.html';
} else {
uID = response.authResponse.userID;
accessToken = response.authResponse.accessToken;
console.log('accesstoken::',response.authResponse.accessToken);
FB.api('/me', {fields: 'last_name'}, { access_token : accessToken } ,function(response) {
console.log(response);
});
//get list of pages
if(accessToken!=null){
FB.api('/me/accounts','get',{ access_token : accessToken },function(response){
console.log('resp of pages',response);
if(response!=null){
var data = response.data;
pageAccessToken= data[0].access_token;
console.log('pageAccessToken::',pageAccessToken);
FB.api('/6599048*******/feed', 'post', {message :body, access_token : pageAccessToken }, function(response) {
console.log('response',response)
if (!response || response.error) {
alert('Error occured');
} else {
alert('Post ID: ' + response.id);
}
});
}
});
}
Related
I've got my Cordova app authenticating with Facebook although i'm trying retrieve some data and I get errors. Was wondering if my URL is incorrect. Can anyone spot a mistake in this?
Errors:
app: makeAPICalls: error:setting authenticatedUser to Yes and skip registration.{"readyState":0,"status":0,"statusText":"Error: SyntaxError: DOM Exception 12"}
function makeAPICallsFB(token) {
$.ajax(
{
//url: 'https://api.linkedin.com/v1/people/~?format=json',
url: 'https://graph.facebook.com/v2.6/me?fields=id,first_name,last_name,bio,email,work,friends,picture{url}',
//url: 'https://graph.facebook.com/v2.6/oauth/access_token',
beforeSend: function (xhr) {
try {
console.log("Authorization...");
xhr.setRequestHeader('authorization', 'Bearer ' + token);
console.log("Finished Auth...");
} catch(err) {
alert(err);
}
},
success: function (linkedInData) {
console.log("TEST....");
if (linkedInData != null) {
console.log("Success");
try {
console.log('app: makeAPICalls LinkedInData: ' + JSON.stringify(linkedInData) + " token: " + token);
console.log('name: ' + linkedInData.id);
vsetaService.saveLinkedInData(linkedInData, token);
checkUserStatus();
} catch(err) {
alert(err);
}
} else {
alert("Data is NULL!");
}
},
error: function (error) {
console.log("app: makeAPICalls: error:setting authenticatedUser to Yes and skip registration." + JSON.stringify(error));
//navigator.notification.confirm('Unable to connect to LinkedIn at this time.', confirmCallback, "VSETA - Think Material", ["Ok"]);
//Take user to Home if an error with LinkedIn + Temp assign access
authenticatedUser = 1;
homeScreen();
}
});
console.log("Finished!");
}
This is my FB Login
function oauth2_loginFaceBook() {
$.oauth2({
type: 'post',
auth_url: 'https://www.facebook.com/v2.6/dialog/oauth', // required
response_type: 'code', // required - "code"/"token"
token_url: 'https://www.facebook.com/v2.6/oauth/access_token', // required if response_type = 'code'
logout_url: '', // recommended if available
client_id: 'confidential', // required
client_secret: 'confidential', // required if response_type = 'code'
redirect_uri: 'http://localhost/callback', // required - some dummy url
other_params: { scope: 'public_profile', state: 'somethingrandom1234' } // optional params object for scope, state, display...
}, function (token, response) {
console.log('app: oauth2_login Success: ' + response.text);
// do something with token or response
makeAPICallsFB(token);
}, function (error, response) {
console.log('app: oauth2_login ERROR: ' + response.text + " AuthenticateUser anyways to allow access to App as of right now.");
//Take user to Home if an error with LinkedIn + Temp assign access
authenticatedUser = 1;
homeScreen();
});
}
Any help is appreciated!
EDIT: Linkedlin was done correctly and the code is almost the exact same!
function makeAPICalls(token) {
$.ajax(
{
//url: 'https://api.linkedin.com/v1/people/~?format=json',
url: 'https://api.linkedin.com/v1/people/~:(id,first-name,last-name,picture-urls::(original),headline,industry,num-connections,location,summary,specialties,site-standard-profile-request,api-standard-profile-request,public-profile-url,picture-url,positions:(id,title,summary,start-date,end-date,is-current,company:(id,name,type,size,industry,ticker)),educations:(id,school-name,field-of-study,start-date,end-date,degree,activities,notes))?format=json',
beforeSend: function (xhr) {
xhr.setRequestHeader('authorization', 'Bearer ' + token);
},
success: function (linkedInData) {
if (linkedInData != null) {
console.log('app: makeAPICalls LinkedInData: ' + JSON.stringify(linkedInData) + " token: " + token);
vsetaService.saveLinkedInData(linkedInData, token);
checkUserStatus();
}
},
error: function (error) {
console.log("app: makeAPICalls: error:setting authenticatedUser to Yes and skip registration." + JSON.stringify(error));
//navigator.notification.confirm('Unable to connect to LinkedIn at this time.', confirmCallback, "VSETA - Think Material", ["Ok"]);
//Take user to Home if an error with LinkedIn + Temp assign access
authenticatedUser = 1;
homeScreen();
}
});
}
I was thinking that it could be the URL. Any suggestions?
I think the problem is probably picture{url}
If you want the URL of their profile picture,
photoURL = "http://graph.facebook.com/" + response.id + "/picture";
EDIT
Alright then if that's not it I'll just tell you how I go about what you're trying to do.
Use facebook's SDK. It's way easier than using Ajax for this type of thing.
//1
//This initializes the SDK
FB.init({
appId : 'your app id goes here',
cookie : true, // enable cookies to allow the server to access
// the session
xfbml : true, // parse social plugins on this page
version : 'v2.6' // use graph api version 2.6
});
//2
//This loads the SDK
(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'));
//3
//This is the login button
<fb:login-button scope="public_profile,email" onlogin="facebookDoAThing();" data-max-rows="1" data-size="large" data-show-faces="true" data-auto-logout-link="true"></fb:login-button>
//4
//This function gets called by the button, then calls the next couple of functions
function facebookDoAThing() {
FB.getLoginStatus(function(response) {
statusChangeCallback(response);
});
}
//5
//This checks that they authorized your app
function statusChangeCallback(response) {
if (response.status === 'connected') {
// logged into facebook and gave your app access to their account
getInfoAndSuch(response);
}
}
//6
//This is where you grab their info
function getInfoAndSuch(response){
authType = "facebook";
authId = response.authResponse.userID; //For the api call
// This is the SDK's api call syntax.
FB.api('/' + authId + '?fields=id,first_name,last_name,email,permissions',
function(response) {
firstName = response.first_name; //grabs first name
lastName = response.last_name; //grabs last name
email = response.email; //grabs email
photoURL = "http://graph.facebook.com/" + response.id + "/picture"; //Grabs photo url, probably an easier way to do this
});
//This removes your app from their account if you want that
FB.api("/me/permissions", "delete", function(response){});
That flow should be able to accomplish what you want.
I had successfully post a message to my own Facebook page but it was posted as a visitor(I want post as a page). I'm not sure where i missed and also i confused to the page access token.
$('#btn-fb').click(function () {
getPageAccess(function (page_id){
postToFB(page_id,'sien');
});
//postStatus();
});
function getPageAccess(callback) {
FB.login(function (response) {
// handle the response
if (response.authResponse) {
FB.api('/' + page_id + '', {fields: 'access_token'}, function (response) {
if (response && !response.error) {
callback(page_id);
}
});
}
}, {scope: 'manage_pages,publish_pages'});
}
function postToFB(page_id, message) {
FB.api(
"/" + page_id + "/feed",
"post",
{
"message": message
},
function (response) {
if (response && !response.error) {
/* handle the result */
}
else {
}
}
);
}
You need to use a Page Token to post as Page, right now you are using a User Token. You are asking for the Page Token (fields parameter), but you never use it and you donĀ“t add it as callback parameter:
{
'message': message,
'access_token': pageToken
}
I'm working on a Facebook login for a Parse App, and have added the login element, but would now like to add the FB profile email and name into the database. However, I am unable to do so. How would I be able to insert the username and email of a new user who is using Facebook to register on the app?
$scope.loginFacebook = function() {
Parse.FacebookUtils.logIn("email", {
success: function(user) {
if (!user.existed()) {
FB.api('/me?fields=name,email', function (response) {
var user = new Parse.User();
user.set("username", response.username);
user.set("email", response.email);
});
} else {
alert("You're logged in with Facebook!")
//redirect to dashboard page
}
},
error: function(user, error) {
alert("User cancelled the Facebook login or did not fully authorize.");
}
});
};
Just found out the solution to this. I needed to make a request from FB graphs on the url:
$scope.loginFacebook = function() {
Parse.FacebookUtils.logIn(null, {
success: function(user) {
if (!user.existed()) {
FB.api('/me?fields=id,name,email,permissions', function (response) {
user.set('username', response.name);
user.set('email', response.email);
user.save();
alert("You're registered and logged with via Facebook!");
//redirect to dashboard
});
} else {
alert("You're logged in with Facebook!");
//redirect to dashboard page
}
},
error: function(user, error) {
alert("User cancelled the Facebook login or did not fully authorize.");
}
});
};
This should work for you...
FB.api('/me', function (me) {
user.set("facebook_id", me.id);
user.set("facebook_link", me.link);
user.set("firstName", me.first_name);
user.set("lastName", me.last_name);
user.setEmail(me.email);
user.save().then(function () {
//go to new page
});
});
I am using facebook javascript sdk on my web application. I am using graph api to login my application. When I logged out from my application, my application is logged out and my facebook account is also logout.
How to logout only my application not my facebook account ?
Please help me if someone has found solution for this.
Code:
<script type="text/javascript">
var button;
var userInfo;
window.fbAsyncInit = function() {
FB.init({ appId: '########',
status: true,
cookie: true,
xfbml: true,
oauth: true});
showLoader(true);
function updateButton(response) {
button = document.getElementById('fb-auth');
userInfo = document.getElementById('user-info');
userdata = document.getElementById('user-data');
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:'email,user_birthday,status_update,publish_stream,user_about_me'});
}
}
}
// 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);
}
//stream publish method
function streamPublish(name, description, hrefTitle, hrefLink, userPrompt){
showLoader(true);
FB.ui(
{
method: 'stream.publish',
message: '',
attachment: {
name: name,
caption: '',
description: (description),
href: hrefLink
},
action_links: [
{ text: hrefTitle, href: hrefLink }
],
user_prompt_message: userPrompt
},
function(response) {
showLoader(false);
});
}
function showStream(){
FB.api('/me', function(response) {
//console.log(response.id);
streamPublish();
});
}
function share(){
showLoader(true);
var share = {
method: 'stream.share',
u: 'http://www.appovative.com/'
};
FB.ui(share, function(response) {
showLoader(false);
console.log(response);
});
}
function setStatus(){
showLoader(true);
status1 = document.getElementById('status').value;
FB.api(
{
method: 'status.set',
status: status1
},
function(response) {
if (response == 0){
alert('Your facebook status not updated. Give Status Update Permission.');
}
else{
alert('Your facebook status updated');
}
showLoader(false);
}
);
}
function showLoader(status){
if (status)
document.getElementById('loader').style.display = 'block';
else
document.getElementById('loader').style.display = 'none';
}
</script>
Their is function defined in FB object use this to destroy FB session ,
usage( via PHP)
$facebook->destroySession();
Or
FB API provides a logoutURL which will log the user out of their current Facebook account.
you can use it like this ,
$facebook = new Facebook($config);
$params = array('next' => 'www.yousite.com/test.php' );
$logoutURL = $facebook->getLogoutUrl($params);
***note
advisable to add below codes also (not in case if you dont want your user to log out of your site)
//remove PHPSESSID from browser
if ( isset( $_COOKIE[session_name()] ) )
setcookie( session_name(), '', time()-7000000, '/' );
//clear session from globals
$_SESSION = array();
With JS using a custom event
ref : (FB.logout() called without an access token. javascript sdk)
function fbLogoutUser() {
FB.getLoginStatus(function(response) {
if (response && response.status === 'connected') {
FB.logout(function(response) {
document.location.reload();
});
}
});
}
Am working on a facebook application to post images to a page, i want to delete a particular the facebook post using javascript api, any help please?
This is my code:
FB.api('/1234/photos', 'post', {
access_token : FB.getAuthResponse()['accessToken'],
message: "message",
url : '',
from : 1234,
}, function (response) {
if (!response || response.error) {
alert('Error occured');
} else {
alert('Post ID: ' + response.id);
}
});
Delete post function:
function delete_post(post_id)
{
FB.api(post_id, 'delete',function(response) {
console.log(response)
if (!response || response.error) {
alert('Error occured');
} else {
alert('Post was deleted');
}
});
}
This is not working for me, always getting error occured message.
which Id should i choose to delete a post? response.id or response.post_id?
Thanks