#ruby-on-rails #facebook-graph-api #facebook-fql #omniauth #koala
#ruby-on-rails #facebook-graph-api #facebook-fql #omniauth #koala
Вопрос:
Я создаю приложение для Facebook. Я регистрирую пользователя с помощью omniauth-жемчужины facebook. Я прошу следующие разрешения:
provider :facebook, 'app_id', 'secret_key',
scope: "public_profile,user_friends,friends_photos,user_photos"
После входа пользователя я получаю список его друзей с koala
помощью gem и что-то вроде следующего кода:
@graph = Koala::Facebook::API.new(current_user.oauth_token)
@profile = @graph.get_object("me")
@friends = @graph.get_connections("me", "friends?fields=id,name,gender")
Я не знаю, смогу ли я получить альбомы и фотографии для каждого из его друзей. Я попробовал следующий запрос fql:
SELECT pid FROM photo WHERE aid IN (SELECT aid,name FROM album WHERE owner=user_id)
который работает только для меня, когда я тестирую его в graph api explorer, но он не работает из моего приложения (ни для моих друзей, ни для меня).
У меня отсутствуют какие-то разрешения или невозможно получить фотографии и альбомы чьих-то друзей? Есть ли другие предложения по получению всех фотографий чьих-либо друзей через facebook graph API?
Обновить
Я загрузил код здесь https://github.com/johndel/fbgame Вы можете увидеть приведенный выше код и остальную его часть в config/initializers/omniauth.rb и в app/controllers/pages_controller.rb
Комментарии:
1. Не уверен, что я что-то упускаю, но в вашем коде, где вы выбираете слово «фото», не появляется ни разу. Может быть, где-то просто опечатка? Я также не уверен, почему вы назначаете
@profile
переменную, но никогда не используете ее в коде, который вы нам показали.2. Я загрузил репозиторий на github, если вас интересует остальная часть кода.
3. Я обновил свой ответ, и репозиторий находится здесь github.com/johndel/fbgame
Ответ №1:
Проблема связана с разрешениями, которые запрашивает ваше приложение во время регистрации. Если вы установите флажок, он не запрашивает фотографии вашего друга.
Вышесказанное означает, что проблема связана с драгоценным камнем omniauth-facebook, поскольку это то, что вы используете. Вы используете старую версию (версия 1.4.0), хотя я обновил, и она по-прежнему не работала с текущей версией (1.6.0).
Я заставил его работать с версией javascript, в которой он генерировал правильный ключ omniauth и запрашивал предпочтительные разрешения (доступ к фотографиям друга). После входа в систему он отлично работал с драгоценным камнем koala, поэтому вам, вероятно, придется получить ключ omniauth каким-либо другим методом, поскольку в текущем драгоценном камне omniauth-facebook, похоже, есть какая-то ошибка (я думаю, что метод javascript, который я использовал, является рекомендуемым способом сделать это).
Вот код с javascript (большая его часть скопирована и вставлена из api facebook graph):
<!DOCTYPE html>
<html>
<head>
<title>Facebook Login JavaScript Example</title>
<meta charset="UTF-8">
</head>
<body>
<div style="width: 900px; margin: 0 auto;">
<script>
// This is called with the results from from FB.getLoginStatus().
function statusChangeCallback(response) {
// The response object is returned with a status field that lets the
// app know the current login status of the person.
// Full docs on the response object can be found in the documentation
// for FB.getLoginStatus().
if (response.status === 'connected') {
// Logged into your app and Facebook.
testAPI();
} else if (response.status === 'not_authorized') {
// The person is logged into Facebook, but not your app.
document.getElementById('status').innerHTML = 'Please log '
'into this app.';
} else {
// The person is not logged into Facebook, so we're not sure if
// they are logged into this app or not.
document.getElementById('status').innerHTML = 'Please log '
'into Facebook.';
}
}
// This function is called when someone finishes with the Login
// Button. See the onlogin handler attached to it in the sample
// code below.
function checkLoginState() {
FB.getLoginStatus(function(response) {
statusChangeCallback(response);
});
}
window.fbAsyncInit = function() {
FB.init({
appId : 'api_key',
cookie : true, // enable cookies to allow the server to access
// the session
xfbml : true, // parse social plugins on this page
version : 'v2.0' // use version 2.0
});
// Now that we've initialized the JavaScript SDK, we call
// FB.getLoginStatus(). This function gets the state of the
// person visiting this page and can return one of three states to
// the callback you provide. They can be:
//
// 1. Logged into your app ('connected')
// 2. Logged into Facebook, but not your app ('not_authorized')
// 3. Not logged into Facebook and can't tell if they are logged into
// your app or not.
//
// These three cases are handled in the callback function.
FB.getLoginStatus(function(response) {
statusChangeCallback(response);
});
};
// Load the SDK asynchronously
(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/en_US/sdk.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
// Here we run a very simple test of the Graph API after login is
// successful. See statusChangeCallback() for when this call is made.
function testAPI() {
FB.api('/me/albums', function(response) {
console.log(JSON.stringify(response));
// document.getElementById('status').innerHTML =
// 'Thanks for logging in, ' response.name '!';
});
}
</script>
<!--
Below we include the Login Button social plugin. This button uses
the JavaScript SDK to present a graphical Login button that triggers
the FB.login() function when clicked.
-->
<fb:login-button scope="public_profile,user_friends,friends_photos,user_photos" onlogin="checkLoginState();">
</fb:login-button>
<div id="fb-root">
</div>
<div id="status">
</div>
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script>
$(function() {
// FB.api('/me', function(response) {
// console.log(JSON.stringify(response));
// });
});
</script>
</div>
</body>
</html>
После успешного сгенерированного ключа omniauth с правильными разрешениями он работает. Вы можете протестировать это с помощью koala или с помощью javascript, как я это сделал, вызвав вышеупомянутый метод.