The answer already provided by @mgibsonbr is perfect, but I would like to share another solution (a little more complex, it’s true) that I used at the end of last year to get the Ikes of a series of photos in a campaign of a company here in São Paulo.
First of all, I would like to mention that when I developed this code I learned that it is not all resources (photos, posts, etc.) that can be freely accessed. Sometimes (depending on the resource privacy setting) you need to get and use it 'access token', and for this the page on which the code is executed needs to be registered in Facebook Application Center so that the user (logged in) can grant permission to access. The example I prepared to answer the question would not need it, but to perhaps help someone who needs it I decided to include how I did the process.
The first step is to access Facebook’s Application Center (apps) and create a new application. At this point, just define a name and a category (you can also use a namespace if you have more applications on the same domain, say) to list your application/page by FB. See the following image where I created the example 'Test' application:
When creating a new application, Facebook provides a unique code called App ID (see image below in my case). This App ID is required to initialize the API in Javascript and allow the user to approve access to the application to your account data (just remembering that the creation of an app is not necessary to answer the question asked, I’m only sharing because I think it may be useful).
Once done, just indicate on the page "Settings" what is the URL in which the application, page is hosted. You can create different types of platforms (note the "+Add Platform" button) through which your application will be accessed. In this example, I am creating only one Web Page (because the intention is only to build a page that will access FB content). To do the local test, you necessarily need a local server (I don’t think you can directly access the file system). I use the Wampserver. The following image exemplifies this setting.
Once this setup is ready, just create the page and the Javascript code to access the data with the user’s permission.
In the HTML file you should put some code to boot. The example I prepared is presented below. The div with id='fb-root' is requested by FB, and the function definition in 'window.fbAsyncInit' serves to initialize the application and the automated login (there is a note saying that this is not necessary for this example, and so this function can be commented for access to public resources, as in this case). The following code on this same piece of script executes the asynchronous loading of the FB javascript library (which could also be loaded synchronously, but this is the way indicated by Facebook).
<html>
<head>
<title>Teste de Likes</title>
<script type="text/javascript" src="facebook.js"></script>
</head>
<body>
<!--
Inicialização assíncrona da biblioteca javascript para o Facebook
(conforme documentação: https://developers.facebook.com/docs/javascript/quickstart),
com login automático e obtenção do token de acesso.
-->
<div id="fb-root"></div>
<script>
/** Armazena o token de acesso */
var gsAccessToken = "";
/**
* Função de inicialização e login no Facebook.
* NOTA: Essa função é apenas necessária para acesso a recursos com privacidade controlada
* (que requer o uso do token de acesso).
* Para ESTE teste (com o post do Porta dos Fundos), essa função pode ser simplesmente
* comentada (ou removida) que a consulta funciona da mesma forma.
*/
window.fbAsyncInit = function() {
// Inicio da biblioteca do FB (com definição do ID da página Web)
FB.init({
appId : '1401642456751870', // ID da página Web criada no App Center
status : true,
xfbml : true
});
// Requisição ao usuário do login no FB
FB.login(function(oResponse) {
if(oResponse.authResponse) {
gsAccessToken = FB.getAuthResponse()['accessToken'];
console.log('Token de acesso = '+ gsAccessToken);
FB.api('/me', function(oResponse) {
console.log('Bem-vindo, ' + oResponse.name + '!');
});
}
else
console.log('O usuário cancelou o login ou não autorizou completamente.');
}, {scope: ''});
};
// FIM DA FUNÇÃO DE INICIALIZAÇÃO E LOGIN (que pode ser comentada se desejado)
/*
* Carregamento assíncrono do arquivo js com a api do FB
* (note o uso de 'pt_BR' na URL, para janelas de login/permissão localizadas).
*/
(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/pt_BR/all.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
</script>
<!-- Função de callback para exibição do total de likes. -->
<script>
function displayLikes(iLikes) {
alert("Total de likes do post: " + iLikes);
}
</script>
<!--
Testa com o post da seguinte página do grupo "Porta dos Fundos":
https://www.facebook.com/PortaDosFundos/posts/643579779013746
O ID é facilmente obtido da própria URL acima.
-->
<button onclick="queryLikes('643579779013746', displayLikes);">Consulta likes do post 'Careca' (Porta dos Fundos)</button>
</body>
</html>
Once this page is loaded, the FB library is loaded. Then, the startup and login function is executed and an access authorization for the application is requested from the user, as illustrated in the following image:
The button included in the body of the HTML previously shown executes the call of the function 'queryLikes' passing as parameter an ID that is the ID of the resource for which to obtain the likes (Likes). In my example I used as a resource o post do vídeo 'Bald' do grupo "Porta dos Fundos". The ID can be obtained in several ways, either directly from the resource link (in the example, for the URL post https://www.facebook.com/PortaDosFundos/posts/643579779013746 the ID is 643579779013746) or by queries on graph explorer tool facebook.
The Javascript code for the query of the Likes I prepared of example is presented below:
/**
* Função de consulta dos Likes de um recurso (páginas, fotos, vídeos, etc) do Facebook.
* @param sResourceID Identificador do Facebook para o recurso. O identificador é facilmente
* obtido a partir de uma consulta com o link do recurso na ferramenta Graph API Explorer do Facebook.
* @param oCallback Função de callback com a assinatura function(iLikes) a ser chamada com o resultado
* da consulta.
*/
function queryLikes(sResourceID, oCallback) {
var oCounter = { likes: 0 };
// Consulta o número de likes do recurso
FB.api("/" + sResourceID + "/likes?limit=5000",
function(oResponse) {
outputLikers(oResponse.data);
queryResponse(oCounter, oResponse.data.length, oResponse.paging.next, oCallback);
}
);
}
/**
* Função recursiva para contagem acumulada dos likes em múltiplas páginas.
* @param oCounter Objeto para manter a contagem dos likes entre as chamadas.
* @param iLikes Número de likes da atualização da paginação atual recebida do Facebook.
* @param sNext String com o link para a próxima paginação ou null se não existir mais paginações.
* @param oCallback Função de callback com a assinatura function(iLikes) a ser chamada com o resultado
* da consulta.
*/
function queryResponse(oCounter, iLikes, sNext, oCallback) {
oCounter.likes += iLikes;
if(sNext != null) {
FB.api(sNext,
function(oResponse) {
outputLikers(oResponse.data);
queryResponse(oCounter, oResponse.data.length, oResponse.paging.next, oCallback);
}
);
}
else
oCallback(oCounter.likes);
}
/**
* Função utilitária para 'imprimir' no console os nomes (e IDs) dos usuários que curtiram
* o recurso.
* @param aData Array com os objetos de usuários que curtiram o recurso, conforme retornado pela
* query ao FB.
*/
function outputLikers(aData) {
for(var i = 0; i < aData.length; ++i) {
var oUser = aData[i];
console.log(oUser.name + "(" + oUser.id + ")");
}
}
This code uses the Facebook API to make Ajax requests directly, but hiding the details of the formation of the FQL (Facebook Query Language) clauses. As in the previous answer, the result is a JSON, only in this case with the Ids and names of each person who liked the resource. As this number can be quite large, the data is returned on multiple pages, and so the code is prepared to process the following pages. In the example I also list the names and ids of people who liked (in the system I did last year, I created and saved a listing with names, Ids and emails for the company to use in future campaigns - the email you access in new queries directly to each user’s ids - if the user provided a public email).
Keep in mind that in order to perform this query in a post of a general visibility page like the Backdoor group, you do not need an access token.
The result of this test is shown by the following images:
Just out of curiosity, you can test the API calls via the Graph Explorer tool, as illustrated in the image below:
And, if you select "FQL Query" instead of "Graph API", you can test queries as provided by the great @mgibsonbr response. :)
+1 because of step-by-step with images.
– Cleiton
Thank you very much man, your tip was key, thank you for posting in detail, a hug!
– Felipe Viero Goulart
@Felipestoker Wow, for nothing. I’m really happy to have helped. :)
– Luiz Vieira