how to get publish_stream permissions for post on facebook wall? - javascript

here is my connection:
window.fbAsyncInit = function () {
FB.init({
appId: "348044465251207",
status: true,
cookie: true,
xfbml: true,
oauth: true
});
FB.Event.subscribe('auth.login', function (response) {
var credentials = { uid: response.authResponse.userID, accessToken: response.authResponse.accessToken };
SubmitLogin(credentials);
}, { perms: 'read_stream,publish_stream,offline_access' });
FB.getLoginStatus(function (response) {
if (response.status === 'connected') {
FB.api('/me', function (response) {
//console.log('Good to see you, ' + response.name + '.');
mail = response.email;
currentName = response.name;
gender = response.gender;
place = response.location;
$.ajax({
url: "/Login/DetailsToDataBase",
type: "POST",
data: { gender: gender, mail: mail, place: place },
success: function (data) {
generalScore = data;
div_element = document.getElementById("userScore");
div_element.innerHTML = "Your score is: " + generalScore;
}
});
});
} //end if
else if (response.status === 'not_authorized') { alert("user is not authorised"); }
else { alert("user is not conntected to facebook"); }
}, { scope: 'read_stream,publish_stream,offline_access' });
function SubmitLogin(credentials) {
$.ajax({
url: "/Login/FacebookLogin",
type: "POST",
data: credentials,
error: function () {
alert("error logging in to your facebook account.");
},
success: function () {
// alert("success log in facebook");
// window.location.reload();
}
});
}
};
(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));
and this is the function to post on user facebook wall:
var params = {};
params['method'] = 'stream.publish';
params['message'] = currentName +' earn '+ score+ '$ in battelship!';
params['name'] = 'BattelShip';
params['description'] = 'let\'s see if you sucsses to break my highlight';
params['link'] = 'https://apps.facebook.com/348044465251207/?fb_source=search&ref=ts&fref=ts';
params['picture'] = 'http://www.israup.net/images/98d0808995e356818a0c016bc1a2a7cc.png';
params['caption'] = 'Try it by Yourself!';
FB.api('/me/feed', 'post', params, function(response) {
if (!response || response.error) {
console.log('Error occured');
} else {
console.log('Published to stream - you might want to delete it now!');
}
});
it post only on my wall (because i am the admin of the app), but for another users it says:
"The user hasn't authorized the application to perform this action"
help me please!!

You need to look at the Login documentation again I think, you're using a parameter in part of your login flow 'perms' which was deprecated over a year ago in favour of 'scope' -
Check the examples that come with the SDK and read the login documentation, though the code might just work if you fix that error, i'd be wary of what other things have changed in the API since the example you're working from was written - you can check what permissions were granted to the access token you're using by calling /me/permissions with that access token

Related

Facebook Javascript Ajax Authentication

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.

Clear Phonegap's InAppBrowser Cache

I am using Google authorization into my app. It works perfectly,
but the problem is cache not clear when someone logout from app.
I have tried adding clearcache=yes and clearsessioncache=yes, but they do not seem to do anything. Without clearing the cache when someone tries to log back in it validates the token with the previously signed in account.
Is there a way I can delete everything associated to the InAppBrowser ?
var googleapi = {
authorize: function (options) {
var deferred = $.Deferred();
//Build the OAuth consent page URL
var authUrl = 'https://accounts.google.com/o/oauth2/auth?' + $.param({
client_id: options.client_id,
redirect_uri: options.redirect_uri,
response_type: 'code',
scope: options.scope
});
var authWindow = window.open(authUrl,'_blank','location=no,toolbar=no,clearsessioncache=yes');
$(authWindow).on('loadstart', function (e) {
var url = e.originalEvent.url;
var code = /\?code=(.+)$/.exec(url);
var error = /\?error=(.+)$/.exec(url);
if (code || error) {
//Always close the browser when match is found
authWindow.close();
}
if (code) {
//Exchange the authorization code for an access token
$.post('https://accounts.google.com/o/oauth2/token', {
code: code[1],
client_id: options.client_id,
client_secret: options.client_secret,
redirect_uri: options.redirect_uri,
grant_type: 'authorization_code'
}).done(function (data) {
deferred.resolve(data);
$("#loginStatus").html('Name: ' + data.given_name);
}).fail(function (response) {
deferred.reject(response.responseJSON);
});
} else if (error) {
//The user denied access to the app
deferred.reject({
error: error[1]
});
}
});
return deferred.promise();
}
};
var accessToken;
var UserData = null;
function callGoogle() {
googleapi.authorize({
client_id: 'client_id',
client_secret: 'client_secret-key',
redirect_uri: 'http://localhost',
scope: 'https://www.googleapis.com/auth/plus.login https://www.googleapis.com/auth/userinfo.email'
}).done(function (data) {
accessToken = data.access_token;
getDataProfile();
});
}
function getDataProfile() {
var term = null;
$.ajax({
url: 'https://www.googleapis.com/oauth2/v1/userinfo?alt=json&access_token=' + accessToken,
type: 'GET',
data: term,
dataType: 'json',
error: function (jqXHR, text_status, strError) {
},
success: function (data) {
var item;
var OAuthToken = accessToken;
var OAuthAccessToken = data.id;
var username = data.email;
var firstname = data.given_name;
var lastname = data.family_name;
var ExternalIdentifier = data.id;
var Email = data.email;
var ProviderSystemName = "ExternalAuth.Google";
ExternalResponseInsert(apiSecretKey, storeId, languageId, username, firstname, lastname, Email, ExternalIdentifier, OAuthToken, OAuthAccessToken, ProviderSystemName);
}
});
//disconnectUser();
}
function disconnectUser() {
var revokeUrl = 'https://accounts.google.com/o/oauth2/revoke?token=' + accessToken;
$.ajax({
type: 'GET',
url: revokeUrl,
async: false,
contentType: "application/json",
dataType: 'jsonp',
success: function (nullResponse) {
accessToken = null;
console.log(JSON.stringify(nullResponse));
console.log("-----signed out..!!----" + accessToken);
},
error: function (e) {
// Handle the error
}
});
}

Connecting Facebook on an application

Everytime I log out my account on Facebook itself, the connected account (same account) in the app also logs out. Is this expected?
I was hoping to come up with something like Hootsuite's functionalities, starting with Facebook first.
Here is my code.
<div id="fb-root"></div>
<script>
var app_id='{!#SETTINGS.facebook_api_key#value}';
function statusChangeCallback(response) {
console.log('statusChangeCallback');
console.log(response);
if (response.status === 'connected') {
console.log('The user is connected.');
var fb_access_token = response.authResponse.accessToken;
console.log(fb_access_token);
rbf_setFieldValue("facebook_access_token", fb_access_token);
} else if (response.status === 'not_authorized') {
console.log('The user is not authorized.');
} else {
console.log('The user is not logged in.');
FB.login(function(response) {
console.log('Logging in.');
var fb_access_token = response.authResponse.accessToken;
console.log(fb_access_token);
rbf_setFieldValue("facebook_access_token", fb_access_token);
}, {scope: 'public_profile, manage_pages, publish_actions, user_groups'});
}
}
function checkLoginState() {
FB.getLoginStatus(function(response) {
statusChangeCallback(response);
});
}
window.fbAsyncInit = function() {
FB.init({
appId : app_id,
cookie : true,
xfbml : true,
version : 'v2.1'
});
FB.getLoginStatus(function(response) {
statusChangeCallback(response);
});
};
// Load the SDK asynchronously
(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>
Got it.
My mistake was I used FB.ui for posting to Facebook, and it requires a Facebook account to post.
The solution was to use FB.api and pass the user/page access token so that you can post without user login.
function postToSocialTimeline() {
try {
var obj = {
name: name,
description: description,
link: link,
picture: picture,
caption: caption,
message: "Test",
access_token: accessCode
};
function resp(response) {
console.log('Cancelled');
} //FB.ui(obj, resp);
FB.api('/me/feed', 'POST', obj, function(response) {
if (!response || response.error) {
console.log(!response ? 'error occurred' : response.error);
console.log('Error');
alert('Unable to post to Facebook!');
return;
} else {
alert('Requisition has been successfully posted!');
}
});
} catch (e) {}
}

Sign Up user with facebook in firebase

Hi every one I am trying to sign up users in my app using facebook connect botton. That is when the user click the button I check if it is first time i store some of his informatios if it is not his first time i just ligged into the app .Now I can logged the user when he click the botton get his information as showing bellow. My problem is to save those informations in my Firebase App but it is not working. Please any help will be great
//Here is the snapshot of my controller
var app = angular.module("yopi", ["firebase"]);
app.controller("EventCtrl", function($scope, $firebase, $window) {
var ref = new Firebase("https://yopi.firebaseio.com/");
window.fbAsyncInit = function() {
FB.init({
appId : 'MY API', // Set YOUR APP ID/
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)
{
if (response.status === 'connected')
{
document.getElementById("message").innerHTML += "<br>Connected to Facebook";
//SUCCESS
}
else if (response.status === 'not_authorized')
{
document.getElementById("message").innerHTML += "<br>Failed to Connect";
//FAILED
} else
{
document.getElementById("message").innerHTML += "<br>Logged Out";
//UNKNOWN ERROR
}
});
};
$scope.Login = function()
{
FB.login(function(response) {
if (response.authResponse)
{
getUserInfo();
getPhoto();
$window.location.href = "https://yopevent.firebaseapp.com/events.html";
} else
{
console.log('User cancelled login or did not fully authorize.');
}
},{scope: 'email,user_photos,user_videos'});
}
function getUserInfo() {
FB.api('/me', function(response) {
UserId = response.id;
UserName = response.name;
UserEmail = response.email;
});
}
function getPhoto()
{
FB.api('/me/picture?type=normal', function(response) {
$scope.Id = UserId;
$scope.Name = UserName;
$scope.Email = UserEmail;
$scope.PicUrl = response.data.url;
var newUser = {
UserId: $scope.Id,
UserName: $scope.Name,
UserEmail: $scope.Email,
UserPicUrl: $scope.PicUrl
};
//Here no probleme Iamgeting the oblect correctly in the console.
console.log(newUser);
//but the problem is here this is not svaing this objet in firebase
ref.child("users").child($scope.Id).set(newUser);
var str="<br/><b>Pic</b> : <img src='"+response.data.url+"'/>";
document.getElementById("status").innerHTML+=str;
});
}
$scope.Logout = function()
{
FB.logout(function(){document.location.reload();});
}
// 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));
});

How to logout only my FBapplication not my facebook account?

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();
});
}
});
}

Categories

Resources