I am building a website that will allow any authenticated Facebook user to post photos to a specific album associated with a Facebook page. I am using the JavaScript SDK for this task. This is the code I have so far:
window.fbAsyncInit = function () {
FB.init({
appId: "492414284132122",
status: true,
cookie: true,
xfbml: true,
channelUrl: "http://wineoclock.dev.mag/ClockMoments/channel.html"
});
};
function uploadPhoto() {
console.log("called uploadPhoto()...");
FB.login(function (response) {
if (response.authResponse) {
document.getElementById("access_token").value = FB.getAuthResponse()["accessToken'];
var form = document.getElementById("fbPhotoUpload");
var formData = new FormData(form);
// indicate to user that upload is in progress
document.getElementById("btnUpload").value = "Posting...";
document.getElementById("btnUpload").disabled = true;
// post photo to Facebook
$.ajax({
type: "POST",
// post to "Timeline Photos" album
url: "https://graph.facebook.com/283773431737369/photos",
data: formData,
cache: false,
contentType: false,
processData: false,
dataType: "json",
success: function (response, status, jqXHR) {
console.log("Status: " + status);
if (!response || response.error) {
alert("Error occured:" + response.error.message);
}
else {
document.getElementById("fbPhotoUpload").reset();
$("#ThanksModal").reveal();
}
document.getElementById("btnUpload").value = "Post Photo";
document.getElementById("btnUpload").disabled = false;
},
error: function (jqXHR, status, errorThrown) {
console.log("AJAX call error. " + status);
console.log("errorThrown: " + errorThrown);
},
complete: function (jqXHR, status) {
console.log("AJAX call complete. " + status);
}
});
}
else {
alert("Login failed: " + response.error);
}
});
}
Running the code above, I discovered that the selected image gets uploaded, but it is uploaded to Facebook account that is logged in. This is not what I wanted. I wanted to upload it to the target fan page (designated in the AJAX POST request), instead of the logged in user.
I have read on the Internet that I need to request a page access token, instead of a user access token. To do so I would need to log in as the target page, as described in the Facebook doc here.
Is there a way to retrieve the page access token without having to login as the administrator of the Facebook page? If required, can the login be done behind-the-scenes?
EDIT:
I think i misunderstood You; the process described at link i posted results in getting access token for ANY user, you only have to do this once.
I do strongly believe that this is not possible; if it would be doable, practically any app could post at any fanpage.
According to solution from here:Extending Facebook Page Access Token, You need have administrator privileges to convert your short-lived page access token to a long-lived (2 months actually instead of couple of hours). The whole process is well described at the link.
Related
I'm using facebook authentication on my website using javascript sdk. I can get my email and name but I can't get their email, if they're loging in, only their name (it's my fb developer app).
It asks for the login, in case no one is logged in on facebook yet but get nothing happens. If I put an alert where it's supposed to login to my app and it indeed returns the name, just not the email. But if it's me I get both. Why's that?
Here's my code:
<%-- Facebook conection script--%>
<script src="//connect.facebook.net/en_US/all.js"></script>
<script> FB.init({
appId: '334351783684824',
cookie: true,
xfbml: true,
version: 'v2.8'
});
function fbAuthUser() {
FB.login(checkLoginStatus);;
}
function checkLoginStatus(response) {
if (response.status === 'connected') {
FB.api('/me', 'GET', { fields: 'email,name' }, function (response) {
alert(response.email + "; " + response.name);
Ajax(response.email, response.name);
});
}
}
function Ajax(expressao1, expressao2) {
var request = { email: expressao1, nome: expressao2 }
$.ajax({
url: 'login.aspx/LoginExterno',
method: 'post',
contentType: 'application/json',
data: JSON.stringify(request),
dataType: 'json',
success: function (resp) {
window.location.href = resp.d;
},
error: function () { }
})
}
</script>
It's supposed to login and, after getting the data, use that ajax function to access a code behind c# function that redirects the user to the index, if he/she already has an account or to the registry if he/she doesn't have one. It doesn't even go in the Ajax function, because the email parameter is undefined, probably. But when both are present it does.
So, how can I get the email?
Ok, I finally got it. On on FB.Login function, I need to add the scope and the user has to give permission. On my code, it would be like:
FB.login(checkLoginStatus,{scope: 'email'});;
I have an AngularJS Application I am trying to post a message through. I am successfully able to log the user in, get the access token, and I have ensured I have my domain in the JavaScript Origins within Yammer.
Whenever I try to post a message, however, I get the following error:
The strange thing is when it does the preflight it seems OK but as the error states I can't figure out why it isn't coming back in the CORS header as I have it registered within the Yammer Client area.
Here is the code for posting:
$scope.YammerPost = function (Yammer) {
var _token = Yammer.access_token.token;
var config = {
headers: {
'Authorization': 'Bearer ' + _token
}
};
$http.post('https://api.yammer.com/api/v1/messages.json', { body: 'blah blah', group_id: XXXXXXX }, config);
}
I call that scope variable in the view via a button click.
Here is the logic I use to sign the user in:
function checkYammerLogin() {
$scope.Yammer = {};
yam.getLoginStatus(
function (response) {
if (response.authResponse) {
$scope.Yammer = response;
console.dir(response); //print user information to the console
}
else {
yam.platform.login(function (response) {
if (response.authResponse) {
$scope.Yammer = response;
console.dir(response);
}
});
}
}
);
}
I ended up finding the issue.
For some odd reason, every time I would try to use an $http post it would include an Auth token from AD (app using Azure AD for authentication).
I ended up using jQuery inside of my Angular scope function on the button click and it works as I can control the headers for the request.
$.ajax({
url: 'https://api.yammer.com/api/v1/messages.json',
type: 'post',
data: {
body: 'this is a test from jQuery using AngularJS',
group_id: <group_id>
},
headers: {
'Authorization': _token
},
dataType: 'json',
success: function (data) {
console.info(data);
}
});
Fixed the issue and I can now post.
If anyone sees any issues with this practice please let me know, still a little new to angular
I have an HTML5 based android app. The app was working perfectly fine and was able to fetch data from the backend system. However, since today the app is reporting a weird error while fetching data SyntaxError Unexpected token and shows some gibberish character. This error is occurring only on phones having Jelly Bean (Android 4.2.1); it was working perfectly fine till last week and there has been no change in the code. In the below code the ajax call goes into the error section for Android 4.2.1.
function getData() {
jQuery.support.cors = true;
$.ajax({
type: "GET",
beforeSend: function(xhr) {
xhr.setRequestHeader('Content-Type', 'application/json;charset=utf-8');
xhr.setRequestHeader('X-SMP-APPCID', connectionID);
xhr.setRequestHeader('Authorization', 'Basic ' + btoa(appUser + ":" + appPass));
},
url: calURL, //calURL is the connection to backend
crossDomain: true,
dataType: "json",
processData: false,
xhrFields: {
withCredentials: true
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Error fetching Data - " + errorThrown);
hideMainContent(false);
document.getElementById("data").innerHTML = "Error fetching data - " + errorThrown;
if(errorThrown.indexOf("Unauthorized") > -1){**// Invalid token reported here**
document.getElementById("setButton").innerHTML = "<p>Unauthorized error can occur if your password has expired or changed. Below option can be used to change application password to your new Password.</p><button onclick=\"changePassword()\" class=\"ui-btn style=\"margin:10% 25%;width:50%;\">Change Password</button>";
}
else{
document.getElementById("setButton").innerHTML = "<p>Temporary communication error. Please refresh after some time.</p>";
}
},
success: function(jsonData) {
},
});
return;
}
Any help in this regards is highly appreciated.
Thanks!
I've got an AJAX request which pulls the data from the form and POSTs it to an API. The weird thing is it works perfectly fine on localhost but fails silently when I upload to remote server. And I mean silently: the response code is blank, there's nothing in the logs. I've checked on Firefox and Chrome. jQuery is loaded, function is firing properly. The code is below:
function send() {
console.log("preparing");
var beacon = {
beaconID: $("#beaconID").val(),
name:$("#beaconName").val(),
campaignID:$("#campaignID").val(),
clientID:$("#clientID").val()
}
console.log("payload:");
console.log(beacon);
$.ajax({
type: 'POST',
url: '../beaconAPI/index.php/createBeacon',
data: JSON.stringify(beacon),
contentType: "application/json; charset=utf-8",
traditional: true,
success: function (response) {
console.log("done:");
console.log(response);
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(JSON.stringify(jqXHR));
console.log("AJAX error: " + textStatus + ' : ' + errorThrown);
}
});
}
From the comments you posted
10:33:21.046 "{"readyState":0,"responseText":"","status":0,
"statusText":"error"}" addBeacon.html:34 10:33:21.046 "AJAX error: error : "
A status code of zero means one of two things:
You are running off file protocol
The page refreshed as Ajax call is made
Since you said this is on production, sounds like it is a case of #2.
So you need to cancel the action that is causing the page to refresh. Since you do not show how you call send, here is some basic ways of cancelling the action.
onclick="send(); return false"
onsubmit="send(); return false"
$("#foo").on("click", function(e) {
send();
e.preventDefault();
});
I have attempted to implement the Facebook Javascript SDK login into my website but need to store information about the user so that when the user logs back in using Facebook I have information stored about them such as their previous in-website activities. Could I integrate this into a MySQL database?
I think you may searching for the following way of storing logged user information into mysql database,
FB.login(function(response) {
if (response.authResponse) {
console.log('Welcome! Fetching your information.... ');
FB.api('/me', function(response) {
var fbname=response.name;
var fbid=response.id;
$.ajax({
type: "POST",
url: page_for_storing_information,
data: "name="+fbname+"&uid="+fbid,
success: function(msg){
}
});
console.log('Good to see you, ' + response.name + '.');
});
} else {
console.log('User cancelled login or did not fully authorize.');
}
});