I am trying to post to a users 'Activity Feed' but I don't understand how.
Here is my demo application:
http://bazaar-market.co.uk/facebook_test/car.html
You can view the source to see all the code as it's all HTML.
<script type="text/javascript">
function postView()
{
FB.api(
'/me/fandango-auctions:view',
'post',
{ item : 'http://bazaar-market.co.uk/facebook_test/car.html' },
function(response) {
if (!response || response.error) {
alert("Error");
} else {
alert('View was successful! Action ID: ' + response.id);
}
console.log(response);
});
}
</script>
I am getting the error:
This method must be called with an app access_token
If I disable access_token's in the app's settings then It says something like:
You must use an access_token to access the users account details
Can anyone help?
Try this.
https://developers.facebook.com/docs/authentication/client-side/
<html>
<head>
<title>Client-side OAuth Example</title>
</head>
<body>
<script>
function displayUser(user) {
var userName = document.getElementById('userName');
var greetingText = document.createTextNode('Greetings, '
+ user.name + '.');
userName.appendChild(greetingText);
}
var appID = YOUR_APP_ID;
if (window.location.hash.length == 0) {
var path = 'https://www.facebook.com/dialog/oauth?';
var queryParams = ['client_id=' + appID,
'redirect_uri=' + window.location,
'response_type=token'];
var query = queryParams.join('&');
var url = path + query;
window.open(url);
} else {
var accessToken = window.location.hash.substring(1);
var path = "https://graph.facebook.com/me?";
var queryParams = [accessToken, 'callback=displayUser'];
var query = queryParams.join('&');
var url = path + query;
// use jsonp to call the graph
var script = document.createElement('script');
script.src = url;
document.body.appendChild(script);
}
</script>
<p id="userName"></p>
</body>
</html>
Error is in function : postView().
When i am loged in I have access_token :
AAAFIDJXVUKcBABpW5pcU97CC7sTwdDmJykOKhZAykZC6D8gaTumTsDZBRzCfJ3eqc58R5whIFuGTBnPeeRGmn6N0ccBDLRGNKXJmy5ZCexTvjBqExTmI
but function postView() using another access_token that already expired:
FB.api(
'/me/fandango-auctions:view',
'post',
{
access_token : 'AAAFIDJXVUKcBALARwKxJHdwwf7chdqleGsrQtYsIk3xiB4vR111s3Gc4cos3Dgd6CFynoUURci0i3t7lzh5mZA41UqSJzbccjy6JjWLSTk8UfgvEO',
item : 'http://bazaar-market.co.uk/facebook_test/car.html'
},
function(response) {
if (!response || response.error) {
alert("Error");
} else {
alert('View was successful! Action ID: ' + response.id);
}
console.log(response);
});
Related
I am trying to get photo of google contact. from api guide found this:
https://www.google.com/m8/feeds/photos/media/{userEmail}/{contactId}
my code:
`$.get("https://www.google.com/m8/feeds/photos/media/default/54b8abe0f52ad02?access_token=" + authorizationResult.access_token + "&v=3.0",
function(response){
//process the response here
console.log(response);
}
);`
it gives me this error:
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access.
but this seems to be working fine
`$.get("https://www.google.com/m8/feeds/contacts/default/full?alt=json&access_token=" + authorizationResult.access_token + "&max-results=500&v=3.0",
function(response){
//process the response here
console.log(response);
}
);`
Edit:
full js script:
`
<script type="text/javascript">
var clientId = 'my client id';
var apiKey = 'api key';
var scopes = 'https://www.googleapis.com/auth/contacts.readonly';
$(document).on("click",".googleContactsButton", function(){
gapi.client.setApiKey(apiKey);
window.setTimeout(authorize);
});
function authorize() {
gapi.auth.authorize({client_id: clientId, scope: scopes, immediate: false}, handleAuthorization);
}
function handleAuthorization(authorizationResult) {
if (authorizationResult && !authorizationResult.error) {
$.get("https://www.google.com/m8/feeds/photos/media/default/54b8abe0f52ad02?access_token=" + authorizationResult.access_token + "&v=3.0",
function(response){
//process the response here
console.log(response);
}
);
}
}
</script>
`
I got the picture by doing this: (prefix image url with proxy url)
` function handleAuthorization(authorizationResult) {
if (authorizationResult && !authorizationResult.error) {
console.log(authorizationResult);
var accessToken = authorizationResult.access_token;
$.get("https://www.google.com/m8/feeds/contacts/default/thin?alt=json&access_token=" + accessToken + "&max-results=500&v=3.0",
function(response){
//process the response here
console.log(response);
let photoUrl = response.feed.entry[2].link[0].href + "&access_token=" + accessToken;
let proxy = 'https://cors.now.sh/';
let finalPhotoUrl = proxy + photoUrl;
document.getElementById('photo').src = finalPhotoUrl;
}
);
}
}`
I need to login throw google in my page. I got my clientID and set the redirect_uri path in Google Console but when I am trying to login it is giving me the following error. I am integrating this on my asp.net page.
Error:
400. That’s an error.
Error: redirect_uri_mismatch
Application: odiyaDoctor
You can email the developer of this application at: odiyadoctor#gmail.com
The redirect URI in the request: http://localhost/immediateHelp.aspx did not match a registered redirect URI.
My requirement is when user will login by google on first page(UserLogin.aspx) and after successful login the next page(i.e.immediateHelp.aspx) will come. I am explaining my all code and google credentials below.
UserLogin.aspx:
</i>
<script>
var OAUTHURL = 'https://accounts.google.com/o/oauth2/auth?';
var VALIDURL = 'https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=';
var SCOPE = 'https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo.email';
var CLIENTID = '*************************g96b1elfa8.apps.googleusercontent.com';
var REDIRECT = 'http://localhost/immediateHelp.aspx';
var LOGOUT = 'http://accounts.google.com/Logout';
var TYPE = 'token';
var _url = OAUTHURL + 'scope=' + SCOPE + '&client_id=' + CLIENTID + '&redirect_uri=' + REDIRECT + '&response_type=' + TYPE;
var acToken;
var tokenType;
var expiresIn;
var user;
var loggedIn = false;
function googleLogin() {
var win = window.open(_url, "windowname1", 'width=800, height=600');
var pollTimer = window.setInterval(function () {
try {
console.log(win.document.URL);
if (win.document.URL.indexOf(REDIRECT) != -1) {
window.clearInterval(pollTimer);
var url = win.document.URL;
acToken = gup(url, 'access_token');
tokenType = gup(url, 'token_type');
expiresIn = gup(url, 'expires_in');
win.close();
validateToken(acToken);
}
} catch (e) {
console.log('its error', e);
}
}, 500);
}
function validateToken(token) {
$.ajax({
url: VALIDURL + token,
data: null,
success: function (responseText) {
getUserInfo();
loggedIn = true;
window.location.href = "immediateHelp.aspx";
},
dataType: "jsonp"
});
}
function getUserInfo() {
$.ajax({
url: 'https://www.googleapis.com/oauth2/v1/userinfo?access_token=' + acToken,
data: null,
success: function (resp) {
user = resp;
console.log('user info',user);
$('#imgHolder').attr('src', user.picture);
},
dataType: "jsonp"
});
}
function gup(url, name) {
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regexS = "[\\#&]" + name + "=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(url);
if (results == null)
return "";
else
return results[1];
}
</script>
In the above page the bellow error is coming in catch section.
at http://localhost:3440/UserLogin.aspx:92:32
UserLogin.aspx:103 its error DOMException: Blocked a frame with origin "http://localhost:3440" from accessing a cross-origin frame.
at Error (native)
clientID set in google.
Client ID for web application
Client ID
***************************************1ctsjaeg96b1elfa8.apps.googleusercontent.com
Client secret
*********oGbT13hv3S
Redirect URIs
https://localhost/immediateHelp.aspx
JavaScript origins
https://localhost
Here i need when user will logged in successfully,it will redirect to the immediateHelp.aspx page and in this page user can do the logout.Please help me to resolve these errors.
`"http://localhost/immediateHelp.aspx" != "https://localhost/immediateHelp.aspx"
The URL must be character perfect
I can upload single photos via URL to Facebook, but I'm having trouble doing it using batch. I'm getting the (#324) Requires Upload File uncaught exception. I'm ensuring the user is logged in and when I look at the batch payload (batchJson) it looks okay.
To be clear, if I remove all the batch-related setup code and in the FB.api call replace "batch" : batchJson with a single "url": photoUrl the code works.
Here's my code. TIA for any insight on my error:
var message = $("#message-fb").val();
var batchItems = [];
var photoUrl = "";
$(".photo-selected").each(function () {
photoUrl = $(this).data('content');
item = {};
item['method'] = 'POST';
item['relative_url'] = 'me/photos';
item['url'] = encodeURI(photoUrl);
item['caption'] = message;
batchItems.push(item);
});
batchJson = JSON.stringify(batchItems);
alert(batchJson);
FB.getLoginStatus(function (response) {
if (response.status === 'connected') {
// Already logged in and authorized
FB.api(
"/",
"POST",
{
"batch": batchJson
},
function (response) {
if (response && !response.error) {
/* successful upload */
alert('Photos uploaded to Facebook (nl) - ' + JSON.stringify(response));
}
if (response && response.error) {
/* Provide error info during testing */
alert('Sorry, there was a problem uploading your photo to Facebook - ' + JSON.stringify(response));
}
});
} else {
// Need to login and authorize
FB.login(function () {
FB.api(
"/",
"POST",
{
'batch': batchJson
},
function (response) {
if (response && !response.error) {
/* successful upload */
alert('Photos uploaded to Facebook - ' + JSON.stringify(response));
}
if (response && response.error) {
/* Provide error info during testing */
alert('Sorry, there was a problem uploading your photo to Facebook - ' + JSON.stringify(response));
}
});
}, { scope: 'publish_actions' });
}
});
EDIT: Here are the relevant changes using #CBroe's answer:
$(".photo-selected").each(function () {
var photoUrl = $(this).data('content');
var item = {};
item['method'] = 'POST';
item['relative_url'] = 'me/photos';
var itemUrl = encodeURI(photoUrl);
var itemCaption = encodeURIComponent(message);
item['body'] = "caption=" + itemCaption + "&url=" + itemUrl;
batchItems.push(item);
});
batchJson = JSON.stringify(batchItems);
You are sending url and caption parameters on the same “level” as the method and relative_url – they need to be put inside a body property however. And the content of that field has to be encoded the same way an actual POST request via a form would be encoded (so like a URL query string, param1=value1¶m2=value2).
So i have this code, with should connect to google api and get some info of the user. The problem however is that the link which starts the login function doesn't work.
This is a java RESTful project so its built via maven and deployed on a tomcat server if that helps.
<!DOCTYPE html>
<html>
<head>
<script src='http://code.jquery.com/jquery-2.1.3.min.js'></script>
<script type='text/javascipt'>
$(document).ready(function(){
var OAUTHURL = 'https://accounts.google.com/o/oauth2/auth?';
var VALIDURL = 'https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=';
var SCOPE = 'https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo.email';
var CLIENTID = 'sercret';
var REDIRECT = 'myredirect';
var LOGOUT = 'http://accounts.google.com/Logout';
var TYPE = 'token';
var url1 = OAUTHURL + 'scope=' + SCOPE + '&client_id=' + CLIENTID + '&redirect_uri=' + REDIRECT + '&response_type=' + TYPE;
var acToken;
var tokenType;
var expiresIn;
var user;
var loggedIn = false;
function login(){
var win = window.open(url1, 'windowname1', 'width=800, height=600');
var pollTimer = window.setInterval(function() {
try {
console.log(win.document.URL);
if (win.document.URL.indexOf(REDIRECT) != -1) {
window.clearInterval(pollTimer);
var url = win.document.URL;
acToken = gup(url, 'access_token');
tokenType = gup(url, 'token_type');
expiresIn = gup(url, 'expires_in');
win.close();
validateToken(acToken);
}
} catch(e) {
}
}, 500);
});
function validateToken(token) {
$.ajax({
url: VALIDURL + token,
data: null,
success: function(responseText){
getUserInfo();
loggedIn = true;
$('#loginText').hide();
$('#logoutText').show();
},
dataType: 'jsonp'
});
}
function getUserInfo() {
$.ajax({
url: 'https://www.googleapis.com/oauth2/v1/userinfo?access_token=' + acToken,
data: null,
success: function(resp) {
user = resp;
console.log(user);
$('#uName').text('Welcome ' + user.name);
$('#imgHolder').attr('src', user.picture);
},
dataType: 'jsonp'
});
}
/*credits: http://www.netlobo.com/url_query_string_javascript.html*/
function gup(url, name) {
name = name.replace(/[\\\\[]/,'\\\[').replace(/[\]]/,'\\\]');
var regexS = '[\\#&]'+name+'=([^&#]*)';
var regex = new RegExp( regexS );
var results = regex.exec( url );
if( results === null )
return ;
else
return results[1];
}
function startLogoutPolling() {
$('#loginText').show();
$('#logoutText').hide();
loggedIn = false;
$('#uName').text('Welcome ');
$('#imgHolder').attr('src', 'none.jpg');
}
});
</script>
</head>
<body>
<a href="#" onclick='login()' id='loginText'> Click here to login </a>
Click here to logout
<iframe name='myIFrame' id='myIFrame' style='display:none'></iframe>
<div id='uName'></div>
<img src='' id='imgHolder'/>
</body>
</html>
A Small Error, big waste of time :)
<script type='text/javascript'>
You have missed the 'r' in javascipt
This is looking for a function called login:
onclick='login()'
However, no such function exists in the current scope. It was defined only within the scope of the document.ready handler:
$(document).ready(function () {
function login() {
//...
}
});
So it's not visible outside of the handler. In order to make it visible, define it outside:
function login() {
//...
}
$(document).ready(function () {
//...
});
You generally don't need to define your functions in document.ready, it's mainly for waiting until the DOM is loaded before evaluating selectors. You can define functions within it, if those functions don't need to exist outside its scope.
Another alternative would be to bind it within the scope that it's defined, rather than in-line in the markup. Something like this:
$(document.ready(function () {
function login() {
//...
}
$('#loginText').click(login);
});
I want to redirect users to the oauth page if they have removed any of the permissions my app requires.
For some reason the below code results in an endless loop when I try to redirect from the FB.api callback function. Any ideas how I can fix this?
var perms = ['publish_actions', 'email', 'user_birthday', 'user_location'],
permsString = perms.join(','),
permissionsUrl = 'https://www.facebook.com/dialog/oauth';
permissionsUrl += '?client_id=' + config.facebook.appId;
permissionsUrl += '&redirect_uri=' + encodeURI(canvasUrl);
permissionsUrl += '&scope=' + permsString;
FB.getLoginStatus(function (response) {
if (response.status === 'connected') {
FB.api('/me/permissions', function(response) {
// using underscore here...
var keys = _.keys(response.data[0]),
diff = _.difference(perms, keys);
// send the user through the auth again if they've removed any of the perms we need
if (diff.length) {
window.location.href = permissionsUrl; // results in an endless redirect loop
// window.location.href = 'http://randomwebsite.com'; // does redirect successfully!!!!
}
});
}
}, true);
It's been a while since I did this but from memory I solved it with something like this:
var redirectMe = function (link) {
window.location.href = link;
};
FB.getLoginStatus(function (response) {
if (response.status === 'connected') {
FB.api('/me/permissions', function(response) {
if (true) {
redirectMe('http://www.browsehappy.com');
}
});
}
}, true);