Facebook connect fbs_[app_id] cookie not being set from JavaScript SDK - javascript

I'm using the Graph API via JavaScript SDK like this (this is basic example straight from documentation):
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#login').click(function() {
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 + '.');
});
} else {
console.log('User cancelled login or did not fully authorize.');
}
});
})
})
</script>
</head>
<body>
Hellow!
Login
<div id="fb-root"></div>
<script src="http://connect.facebook.net/en_US/all.js"></script>
<script>
window.fbAsyncInit = function() {
FB.init({
appId: '249274258430595',
cookie: true,
status: true,
xfbml: true,
oauth: true
});
};
</script>
</body>
</html>
It's also possible to test it live here:
http://bitcells.com
This cookie I need for backend access to API (fbs_249274258430595) is not being set.
Only something called fbsr_249274258430595 is present and this is not what I need. I tested this with FireCookie extension for Firebug.
I really don't understand how this basic example is not working right - meaning that I want to use API from the backend code (PHP, Ruby etc.).
Any ideas?
Thank you!
David

I, on the other hand ended up setting my own cookie which server side can read:
I have one checkbox which asks user if he wants to share on fb, here is the code:
function setFbCookies(response) {
Cookie.set('fb_access_token', response.authResponse.accessToken, {path: '/'})
Cookie.set('fb_user_id', response.authResponse.userID, {path: '/'})
}
when('#share_on_fb', function(checkbox) {
checkbox.observe('change', function(ev) {
if(checkbox.getValue()) {
FB.getLoginStatus(function(response) {
if (response.authResponse) {
setFbCookies(response)
} else {
FB.login(function(response) {
if (response.authResponse) {
setFbCookies(response)
} else {
checkbox.checked = false
}
}, {scope: 'publish_stream'});
}
})
}
})
})
And here is the reason why fbs_xxxxx cookie doesn't get set:
https://developers.facebook.com/blog/post/525/
It looks like if you use oath=false, then it does get set, but this is only valid until 1st of october. There is still no documentation on how to get encrypted access token from the new fbsr_xxxxxx cookie.

Related

how to customize the Facebook Login Button with ReactJs

I am trying to customize the Facebook button for my ReactJs website, but it seems to be not working. I want my Facebook button look like the following design:
Google login is working as I expected, but facebook is kept appearing like following:
Any help would be appreciated!
codesandbox link
I found the answer to my own question, I just stupidly did not see the correct way of importing the FacebookLogin
import FacebookLogin from 'react-facebook-login/dist/facebook-login-render-props'
This is how the import should be done. After that I was able to make my own custom style through render prop:
appId="1088597931155576"
autoLoad
callback={responseFacebook}
render={renderProps => (
<button onClick={renderProps.onClick}>This is my custom FB button</button>
)}
/>```
You can achieve this thing very easily. What you have to do is you have to design your custom button and then use the onclick property.
Here how you do it:
Include this thing where you want to show the Facebook login button and don't forget to style this button according to your needs.
<div id="fb-root"></div>
<button onclick="fb_login();">Login using facebook</button>
Now here is the code you have to include in your page that has the fb_login function defined. You have to put your app id to see the results.
window.fbAsyncInit = function () {
FB.init({
appId: 'your_app_id_here',
oauth: true,
status: true, // check login status
cookie: true, // enable cookies to allow the server to access the session
xfbml: true // parse XFBML
});
};
function fb_login() {
FB.login(function (response) {
if (response.authResponse) {
console.log('Welcome! Fetching your information.... ');
//console.log(response); // dump complete info
access_token = response.authResponse.accessToken; //get access token
user_id = response.authResponse.userID; //get FB UID
FB.api('/me', function (response) {
user_email = response.email; //get user email
// you can store this data into your database
});
} else {
//user hit cancel button
console.log('User cancelled login or did not fully authorize.');
}
}, {
scope: 'public_profile,email'
});
}
(function () {
var e = document.createElement('script');
e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
e.async = true;
document.getElementById('fb-root').appendChild(e);
}()

FB.ui feed or share not returning post_id response

I am trying to use FB.ui share or feed on my test web site and want to get post_id on response message. App has permissions from my test user (user_posts, public_profile) and also i am checking if login status is "connected".
this is javascript code that i am trying to check login and let user to share link. shareOnFacebook() is triggered by a simple html button;
<script async defer src="https://connect.facebook.net/en_US/all.js"></script>
<script type="text/javascript">
window.fbAsyncInit = function () {
FB.init({
appId: '****************',
cookie: true,
xfbml: true,
version: 'v5.0'
});
};
function shareOnFacebook() {
FB.getLoginStatus(function (response1) {
console.log(response1)
if (response1.status === 'connected') {
FB.ui({
method: 'feed',
link: 'http://www.linktoshare.com',
picture: 'http://www.linktoshare.com/images/imagethumbnail.png'
}, function (responseEnd) {
if (responseEnd) {
console.log(responseEnd);
alert('Success');
} else {
alert('Fail');
}
});
}
else {
FB.login(function (response2) {
console.log(response2)
FB.ui({
method: 'feed',
link: 'http://www.linktoshare.com',
picture: 'http://www.linktoshare.com/images/imagethumbnail.png'
}, function (responseEnd) {
if (responseEnd) {
console.log(responseEnd);
alert('Success');
} else {
alert('Fail');
}
})
});
}
});
}
</script>
As you can see from below image, if i close pop-up, i can get response image like that;
But when i share, reponse returns as an empty array like that;
I know the error about "Https" is not important because my app is on development status.
What should i do to get post_id on response here?
Thank you very much.
What should i do to get post_id on response here?
You can’t get the post ID any more, Facebook has removed that completely.
It was getting abused by shady developers and website owners to try and force users to share stuff, to get some kind of reward - which is absolutely not allowed. To stop that kind of spam, Facebook has removed this a while ago already.

How do you attach a picture to LinkedIn share from a blog post?

I have a blog that I want to make shareable via LinkedIn. The docs LinkedIn presents, while simply stated don't have enough detail for me to understand my use case. My use case requires me to dynamically put the picture and description in each blog post, which isn't being populated right now. This is an Angular project.
My current code:
post.html
<script>
delete IN;
$.getScript("https://platform.linkedin.com/in.js");
</script>
<script type="IN/Share" data-url={{webAddress}} data-counter="right"></script>
post.js
//I have all of my data in $scope variables in this area, which includes
// the picture and description I'd like to attach to the post.
Here is what the LinkedIn docs show as the right way to do this:
post.html
<script type="text/javascript" src="//platform.linkedin.com/in.js">
api_key: YOUR_API_KEY_HERE
authorize: true
onLoad: onLinkedInLoad
</script>
<script type="text/javascript">
// Setup an event listener to make an API call once auth is complete
function onLinkedInLoad() {
IN.Event.on(IN, "auth", shareContent);
}
// Handle the successful return from the API call
function onSuccess(data) {
console.log(data);
}
// Handle an error response from the API call
function onError(error) {
console.log(error);
}
// Use the API call wrapper to share content on LinkedIn
function shareContent() {
// Build the JSON payload containing the content to be shared
var payload = {
"comment": "Check out developer.linkedin.com! http://linkd.in/1FC2PyG",
"visibility": {
"code": "anyone"
}
};
IN.API.Raw("/people/~/shares?format=json")
.method("POST")
.body(JSON.stringify(payload))
.result(onSuccess)
.error(onError);
}
</script>
As I understand it, I need to populate the payload object with the right data/links. I have no clue how to do this based on what's in the docs.
Here are a few things I've tried/thought about along with where I'm currently stuck:
1) Get the data from post.js and put it in the payload object between the script tags in post.html. After doing some research, it is not possible to do this. Though I welcome being corrected if I'm wrong.
2) Bring the IN object into angular and populate the payload in post.js. This sounds really great but LinkedIn provides no html with which to call a function in post.js with Angular. Plus the LinkedIn code as presented takes care of formatting for the button and what comes after you click it.
3) Make an http call inside the script tags with JQuery. I rarely if ever use JQuery and have never used http for JQuery before. If this is even a feasible way to think of this problem, this is what I came up with:
<script type="IN/Share" data-url={{webAddress}} data-counter="right">
$.get( "https://public-api.wordpress.com/rest/v1.1/sites/myPost", function( response ) {
var post = _.first(_.filter(response.posts, function(n){return n.title.replace(/ /g,"-").replace(/[:]/g, "").toLowerCase() === $stateParams.id}));
var post1 = _.assign(post, {category: _.first(_.keys(post.categories)), pic: _.first(_.values(post.attachments)).URL, credit: _.first(_.values(post.attachments)).caption, linkCredit: _.first(_.values(post.attachments)).alt, fullStory: post.content.replace(/<(?!\s*\/?\s*p\b)[^>]*>/gi,'')});
**var image = post1.pic;**
**var title = post1.title;**
**var webAddress = window.location.href;**
function onLinkedInLoad() {
IN.Event.on(IN, "auth", shareContent);
}
function onSuccess(data) {
console.log(data);
}
function onError(error) {
console.log(error);
}
function shareContent(title, image, webAddress) {
var payload = {
"content": {
"title": title,
"submitted-image-url": image,
"submitted-url": webAddress
}
};
IN.API.Raw("/people/~/shares?format=json")
.method("POST")
.body(JSON.stringify(payload))
.result(onSuccess)
.error(onError);
}
});
</script>
This solution did not result in a solution either. Where to go from here, I have no ideas. I'm sure this simple but idiosyncratic enough that I need a little hand holding.
Unfortunately, I have not worked with linkedin API.
Perhaps not all will be right in my example. But I've got to use a variable IN in angular and write about the call API wrapper.
An example of the use of plugins, see page LinkedIn Plugins.
Live example on jsfiddle.
//CallBackHell
function LinkedInServiceFunc(callback) {
callback && IN.Event.onDOMReady(callback);
}
angular.module('ExampleApp', [])
.controller('ExampleController', function($scope, LinkedInService, ShareLinkedINService) {
console.log('ExampleController IN', IN);
console.log('ExampleController LinkedInService', LinkedInService);
LinkedInService.promise.then(function(LIN) {
console.log('Complete loading script for LinkedIn in ExampleController', LIN.Objects)
});
//Then you can interact with IN object as angular service. Like this
$scope.shareContent = function() { // Use the API call wrapper to share content on LinkedIn
// Build the JSON payload containing the content to be shared
var payload = {
"comment": $scope.comment,
"visibility": {
"code": 'anyone'
}
};
// Handle the successful return from the API call
function onSuccess(data) {
console.log(data);
}
// Handle an error response from the API call
function onError(error) {
console.log(error);
}
console.log('shareContent', payload);
LinkedInService.promise.then(function(LIN) {
LIN.API.Raw("/people/~/shares?format=json")
.method("POST")
.body(JSON.stringify(payload))
.result(onSuccess)
.error(onError);
});
}
$scope.shareContentService = function() {
//It's better way, i think
ShareLinkedINService.shareContent($scope.comment, 'anyone').then(function(data) {
console.log('success', data);
}).catch(function(data) {
console.err('error', data);
});
}
})
.service('LinkedInService', function($q) {
var defer = $q.defer();
LinkedInServiceFunc(function() {
defer.resolve(IN);
});
return {
promise: defer.promise
};
})
//You can create wrapper on IN API
.service('ShareLinkedINService', function(LinkedInService, $q) {
return {
shareContent: function(comment, visible) {
var defer = $q.defer();
var payload = {
"comment": comment,
"visibility": {
"code": visible
}
};
LinkedInService.promise.then(function(LIN) {
LIN.API.Raw("/people/~/shares?format=json")
.method("POST")
.body(JSON.stringify(payload))
.result(defer.resolve)
.error(defer.reject);
});
return defer.promise;
}
}
})
.directive('linkedInShareButton', function(LinkedInService) {
return {
restrict: "E",
replace: false,
scope: {
shareUrl: "#",
counter:"#"
},
link: function(scope, elem, attr) {
var script = document.createElement('script');
script.setAttribute('type', 'IN/Share');
script.setAttribute('data-url', scope.shareUrl);
script.setAttribute('data-counter', scope.counter);
elem.append(script);
},
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script type="text/javascript" src="//platform.linkedin.com/in.js">
authorize: false
onLoad: LinkedInServiceFunc
//I don't have api_key, because i delete it
// api_key: YOUR_API_KEY_HERE
// authorize: true
// onLoad: onLinkedInLoad
</script>
<body ng-app="ExampleApp">
<div>
<div ng-controller="ExampleController">
<input ng-model="comment">
<button ng-click="shareContent()">
shareContent
</button>
<button ng-click="shareContentService()">
shareContentService
</button>
<script type="IN/Share" data-url="www.mail.ru" data-counter="top"></script>
<linked-in-share-button share-url="www.mail.ru" counter="top"></linked-in-share-button>
</div>
</div>
</body>

Facebook connect: can retrieve the id, the username but cannot retrieve the email

I can get the id and username from facebook connect, but I cannot retrieve the email !
Here is the JS script:
function connectionFacebook()
{ console.log('connectionFacebook called');
FB.api('/me?fields=email,name', { fields: 'name, email' }, function(response)
{
console.log(response);
response gives me:
Object {name: "John Doe ", id: "11112222333344445555"}
But no email !
PS. I guess it uses some old FB connect js since I work on an quite old site.
I have no idea what version of FB it uses, but I guess an old one !
ex: of code found in site;
FB.Event.subscribe('auth.login', function(response)
{
connectionFacebook();
;
});
FB.getLoginStatus(function(response)
{
if (response.authResponse)
{
connectionFacebook();
}
else
{
// no user session available, someone you dont know
//alert("getLoginStatus:deconnecté");
}
});
$.fn.connexionFacebook = function( ) {
return this.each(function () {
FB.init({
appId : xxxxxxxxx,
status : true,
cookie : true,
xfbml : true
});
});
}
})( jQuery );
<script src="http://connect.facebook.net/fr_FR/all.js"></script>
<fb:login-button show-faces="false" width="450" perms="email,user_birthday,user_location" size="medium">FaceBook connect</fb:login-button>
I'd guess that you don't have a permission to access the user's email. Facebook requires you to set the scope that determines which information you need to access.
In you case you need to specify the scope as public_profile,email to access the email. you can do that when your user logs in. Either with the API call:
FB.login(callback, { 'scope': 'public_profile,email' });
or with the button:
<fb:login-button scope="public_profile,email"></fb:login-button>
Specifying the email in the scope will ask the user to share her email address with your application when she logs in:

How to request permissions for facebook app with JavaScript

How can I check the current user login status and ask for permissions for my app? This recently changed and now my app is not working anymore. Thanks for your help!
I always use this setup to handle login status and permissions:
function getPerms() {
FB.login(function(response) {
if (response.authResponse) {
//user has granted permissions
}
}, {scope:"email, ..."});
}
function getStatus() {
FB.getLoginStatus(function(response) {
if (response.status === "connected") {
//user has granted permissions
} else {
getPerms();
}
});
}
You still have to include the all.js and call FB.init(...)
Here is how you can do that:
FB.init(
{
"appId" : xxxxxxxxxx,
"status" : true,
"cookie" : true,
"xfbml" : true,
"oauth" : true
});
FB.Event.subscribe('auth.authResponseChange', function(response)
{
// need to wait few seconds for fb login status to work in FireFox
setTimeout('window.location.reload()', 3000);
});
function fbConnect(){
FB.getLoginStatus(function(response) {
if (response.authResponse){
FB.login(function(response)
{
if (response.authResponse) { }
else
{
//console.log('User cancelled login or did not fully authorize.');
}
}, {"scope":"email,manage_pages"});
}
});
}
You need to call fbConnect() function.
Also make sure that you have these below <body> tag on your page:
<div id="fb-root"></div>
<script src="//connect.facebook.net/en_US/all.js"></script>
You need to provide some code to get better/accurate answers
Most likely you didn't upgrade your code to use OAuth 2.0, see here
Based on the link above, use scope instead of perms
Use response.authResponse instead of response.session
Welcome to Stackoverflow!

Categories

Resources