Facebook: How to get any pages total likes, ratings? - javascript

I would like to get any facebook page's total likes, ratings, etc...
I have created a developer account
What I tried:
- Created an app for this.
- Tried to fetch this information using AppID & AppSecret
- Tried Using access token
I have also done R&D on google and tried many examples but not getting a correct solution which I want.
Pls help me to solve this.
Thanks.
Edit (taken from comment by author):
I tried this example but for every page it requires pageaccesstoken
FB.api('/{pagename}?fields=ratings', function (response) {
Data = response.name; //alert(Data);
if (response.error) {
alert(response.error.message);
}
}, { access_token: "xxxx|yyyy" });

You can get the current likes of a Page with a simple App Access Token:
/[page-id]?fields=fan_count&access_token=[App-Token]
For the ratings of a Page, you need to use a Page Token instead:
/[page-id]/ratings&access_token=[Page-Token]
More information about Tokens and how to get them:
https://developers.facebook.com/docs/facebook-login/access-tokens
http://www.devils-heaven.com/facebook-access-tokens/

Related

How to filter a displayed JSON file

I'm trying to make a web application using Outlook API's that allows me to search for a specific Outlook contact by his name.
I've got a little knowledge of javaScript but i never used any API or manipulated JSON files beforehand, so i looked through tutorials to help me, and
I ran into this one : https://dev.outlook.com/restapi/tutorial/javascript which i followed and succeeded to implement without much trouble.
Briefly, the tutorial allows me to build an app that can display the last 10 emails from the user, or the contact list of this user, which gives something like that :
Contacts displayed
Now what i'm trying to do is to filter this display and be able to search something like " give the contacts which name contains the syllable "AG" ".
I tried to understand the code as much as i can and i'm almost sure that i have to modify the function displaying all the contacts.
So what i did is that i pasted it, renamed it but now i'm struggling with the query parameters.
function getUserContacts(emailAddress, callback) {
getAccessToken(function(accessToken) {
if (accessToken) {
// Call the Outlook API
var callOptions = {
// Get contacts
url: apiEndpoint + '/Me/contacts',
token: accessToken,
method: 'GET',
email: emailAddress,
query: {
// Limit to the first 100 contacts
'$top': 100,
// Only return fields we will use
'$select': 'GivenName,Surname,EmailAddresses',
// Sort by given name alphabetically
'$orderby': 'GivenName ASC'
}
};
makeApiCall(callOptions, function(result, error) {
if (error) {
callback(null, error);
} else {
callback(result.value);
}
});
} else {
var error = { responseText: 'Could not retrieve access token' };
callback(null, error);
}
});
}
And that's the moment i get totally lost, i tried adding '$where':GivenName='AG' in the query{} section, as well as '$filter':GivenName='AG', but neither of them worked. I searched online for an answer but in every one i founded, the JSON file was "available" ( meaning for me that they have,somewhere this kind of code :
[
{"name":"Lenovo Thinkpad 41A4298","website":"google222"},
{"name":"Lenovo Thinkpad 41A2222","website":"google"}
]
But i don't have this type of code anywhere, so i'm wondering if it is possible to do it like i tried to, or if i have to find a way to retrieve the JSON file in order to obtain something like just above ?
I hope i've been clear enough despite my lack of experience in this field, i'd be glad to give some more details/codes if you ask too !
Thanks in advance and have a great day :)
Thanks to Useless Code and his link i managed to send the right request (error was coming from the fact that filter properties must be listed first in the orderby) from the outlook sandbox and get the expected answer with this URL:
https://outlook.office.com/api/v2.0/me/contacts?$filter=GivenName eq 'AG-Carto'&$orderby=GivenName ASC&$select=GivenName,Surname,EmailAddresses
Now what i'm trying to do is to get my javascript code to send it right.
So i know i have to modify the query{} part of the function, i tried this :
query: {
'$filter': 'GivenName eq AG-carto',
'$orderby': 'GivenName ASC',
'$select': 'GivenName,Surname,EmailAddresses'
}
But when i run it, i got a bad request error, and i see that the url sent by the js code is this one :
https://outlook.office.com/api/v2.0/Me/contacts?%24filter=GivenName+eq+AG-carto&%24orderby=GivenName+ASC&%24select=GivenName%2CSurname%2CEmailAddresses
So i'm obviously seeing that they aren't the same, and i have no idea on how to modify the query{} section so that the URL sent by js is the same as my working URL. If anyone could help me on that i'd be grateful !

Soundcloud SDK - load track from url

So I did a tutorial on Soundcloud SDK through CodeAcademy here and wanted to take the knowledge I learned from that and put it on Codepen. But I want to use a different track than the one they use in this tutorial - specifically this song https://soundcloud.com/hardwell/coldplay-sky-full-of-stars-hardwell-remix-download.
I read that /resolve was a good approach to get the trackid but it's not working. I get 403 Forbidden in the console.
SC.get('/resolve/?url=https://soundcloud.com/hardwell/coldplay-sky-full-of-stars-hardwell-remix-download&client_id=3596a42d6242b9c1ee76740a7771d33a', function(track) {
console.log(track); // returns null
});
Here is my codepen. Please help me load this track for my basic SoundCloud SDK audio player. Thanks
Your code is correct and even works with some tracks, for example the ones from the documentation.
You're encountering a problem that I found personally should be emphasized in their documentation. The API access for this track has been disabled (even if the widget is enabled), therefore your have not right to query this track using the API and it returns a 403 Forbidden HTTP status code.
This is described in the Linked Services part of the SoundCloud terms of use:
You can limit and restrict the availability of certain of Your Content to other users of the Platform, and to users of Linked Services, at any time using the permissions tab in the track edit section for each sound you upload, subject to the provisions of the Disclaimer section below.
You can check in your code if any error like this one was encountered while fetching the track informations and depending on the success or failure, continue with the correct action:
var clientId = 'CLIENT_ID';
SC.initialize({
client_id: clientId
});
var songUrl = 'https://soundcloud.com/hardwell/coldplay-sky-full-of-stars-hardwell-remix-download';
SC.get('/resolve?url=' + songUrl + '&client_id=' + clientId, function(data, error) {
if (error === null) {
console.log('Do something like playing the song.');
} else {
console.log('Print an error message?');
}
});

Facebook API - access token for web application

I am making a web app that pulls the latest posts from our Facebook page and processes them.
This is all working fine with a hard-coded access token generated from this page.
The problem is that this token expires, so i am looking for a solution to generate a new token every time the page loads or a non-expiring token - (i have read somewhere that non expiring tokens don't exist anymore).
So of course i did some research, here, here and here.
But non of these examples seem to be working.
Before any complaints of some code that i have tried so far, this is my working example - with an expiring access token:
var Facebook = function () {
this.token = 'MYTOKEN';
this.lastPost = parseInt((new Date().getTime()) / 1000);
this.posts = [];
};
Facebook.prototype.GetPosts = function () {
var self = this;
var deffered = $q.defer();
var url = 'https://graph.facebook.com/fql?q=SELECT created_time, message, attachment FROM stream WHERE created_time < ' + self.lastPost + ' AND source_id = 437526302958567 ORDER BY created_time desc LIMIT 5&?access_token=' + this.token + '';
$http.get(url)
.success(function (response) {
angular.forEach(response.data, function (post) {
self.posts.push(new Post(post.message, post.attachment.media, post.attachment.media[0].src, post.created_time, 'facebook'));
});
self.lastPost = response.data[response.data.length -1].created_time;
deffered.resolve(self.posts);
self.posts = [];
});
return deffered.promise;
};
return Facebook;
Any help / suggestion will be greatly appreciated.
First off, it is important to remember that Facebook has just launched the Version 2 of the Graph API. From April 2014 on, if you have issues with your app, you need to tell us when you created it on Facebook Developers (new apps use the Version 2 by default).
In order manage pages, your app needs to have manage_pages permission. Make sure that the user you want to manage fan pages for has authorized you. If your app uses the Version 2, make sure that Facebook (the Facebook staff) has authorized you to ask users that kind of permission, otherwise your app won't work.
Once you get your token, exchange it for a permanent token (or a token with long expiry date). Make sure you use the token of the fan page, not the token of the user.
If instead you want to read the stream of public fan pages, you need an access token with read_stream permissions. This permission needs to be approved by Facebook (see above) and this specific type of permission takes time to approve, if you're using the Version 2 of the Graph API. If you're using the old API (Version 1), you can still do that without pre-approval on Facebook's side.
The URL to ask for the permission to read the stream is as follows: https://www.facebook.com/dialog/oauth?client_id=$YOUR_APP_ID&redirect_uri=$YOUR_URL&scope=read_stream,manage_pages (i've added manage_pages in this case, you may not need it).
That url will prompt for authorization. Once the user has authorized the app, you'll be recirected to the URL you chose, with a code= variable.
At that point, call this other url:
https://graph.facebook.com/oauth/access_token?client_id={$app_id}&redirect_uri=$someurl&client_secret={$app_secret}&code={$code}
You'll get a response that has the access_token=variable in it. Grab that access token, exchange it for a long one, with the following URL:
https://graph.facebook.com/oauth/access_token?grant_type=fb_exchange_token&client_id={$app_id}&client_secret={$app_secret}&fb_exchange_token={$token_you_have_just_grabbed}
The response will give you a token that lasts for some time. Previously, Facebook had decided to have these "long duration tokens" expire after one month. I have found out, though, that they may have changed their mind: if you put a user token in the debugger, you'll see it never expires.
This is the authorization flow for users who visit with a browser. There's the app authorization flow too. If all you need is a stream from your own Fan page, you want to do the following (with Graph API V.1):
make an HTTP GET request using the following URL:
https://graph.facebook.com/oauth/access_token?type=client_cred&client_id={$app_id}&client_secret={$app_secret}
Use the resulting token to make another HTTP GET call, like so:
https://graph.facebook.com/{$your_page_id}/feed?{$authToken}&limit=10
//ten posts
Decode the json object
You're done.

How to get Facebook user's friends' profile picture using Javascript SDK V2.0

I am creating a website using Facebook API V2.0 JavaScript SDK and I would like to display the profile pictures of the user's friends.
I have managed to display my profile picture using the graph API but I can't manage to get the ID of all my friends if I am logged in my app (I am an admin). If I have the ID, I'll be able to show their profile picture.
In the graph explorer, I have checked all permissions (User Data Permissions + Extended Permissions). I have noticed if I switch to API V1.0, I get friends permission which is exactly what I'd like.
Also, I have added a couple of permission to my app in Facebook developers > App details > App Center Listed Platforms > Configure app center permissions. (user_friends + friends_birthday + friends_religion_politics + friends_relationships + friends_relationship_details + friends_location + friends_photos + friends_about_me)
So far, my html looks like this :
<fb:login-button scope="public_profile,email,user_friends,read_friendlists" onlogin="checkLoginState();">
After loading the Facebook SDK, I have :
function getUserFriends() {
FB.api('me/friends?fields=first_name,gender,location,last_name', function (response) {
console.log('Got friends: ', response);
$("#friendslist").html('<img src="https://graph.facebook.com/'+ response.id+'/picture?type=large"/>');
});
}
However, the array which is suppose to contain all my friends info is empty (see image : http://www.screencast.com/t/W02GaOm3h)
If all you need is their image, this can be found in the "taggable_friends" scope. However, do note that this field is very limited (by design) and that you require additional review by Facebook in order to present it to the average user.
It contains:
A taggable id. This is an id with the express purpose of tagging; it cannot be used to identify the user or otherwise gather information from their profile.
A name. The user's first and last name.
A picture, with common related fields. Url, is_silhouette, height and width.
function getUserFriends() {
FB.api('me/taggable_friends', function (response) {
console.log('Got friends: ', response.data);
$("#friendslist").html('<img src="'+response.data[0].picture.data.url+'"/>');
// maybe an $.each as well
// var friendMarkup = '';
// $.each(response.data, function(e, v) {
// friendMarkup += '<img src="' + v.picture.data.url +'" alt="'+ v.name +' picture"/>';
// }
// $("#friendlist").html(friendMarkup);
});
}
Related reading:
https://developers.facebook.com/docs/graph-api/reference/v2.0/user/taggable_friends
https://developers.facebook.com/docs/opengraph/using-actions/v2.0 - Tagging friends and Mentioning friends sections
A disclaimer: I've been battling with this issue for several days without really being able to mention-tag. My submission to use taggable_friends as a comprehensive, navigatable list for the user was rejected and I speculate (speculation ho!) it was because I did no actual tagging. I'll get back to this in a few days when I've clarified and re-submitted my request for a review on Facebook.
-- Edit --
It would seem the reason my initial submission was rejected was because I was using a special development url and did not point out clearly enough why it was not enough to use the url set under settings. This time I clearly pointed out and explained this reasoning in both the general description of my submission and in the step-by-step notes. In summary, be exceptionally clear in your submission about everything; your reasoning as to why you need this permission, how they can access it, etc. Just to make sure it isn't missed if skim-read.
It seems like in V2.0, Friends permission have dissapeared :
Facebook graph api explorer doesn't show 'Friends Data Permission' tab
https://developers.facebook.com/docs/facebook-login/permissions/v2.0

Get friends read articles with Facebook JS API

i'd like to know how to fetch articles that friends have read from a Facebook app. I use the following query to get articles that I have read:
/me/news.reads
But i want all the articles that friends have read, is that possible?
It is not an apt solution but you can do is loop through facebook id's of your friends and for each friend's Id get all the news read as /$friend_id/news:reads
I dont think there is any direct api function to get action performed by friends.
Try this
FB.api('/me/friends', { 'fields' : 'name,news.reads.limit(10)' }, function (data) {
// if(!data || data.error) { }
// console.log(data);
});
You can omit the limit if you like, or add more fields. Of course this would also work as a GET request to: http://graph.facebook.com/me/friends?fields=name,news.reads.limit(10)&access_token=XXXX

Categories