Facebook API 使用 Firebase 登录调用

Facebook API call with Firebase login

我已将登录绑定到 Facebook 身份验证,这全部由 Firebase 处理。 但是我需要给 Facebook 'me/friends/' 打电话 API 由于我已经登录,我将如何使用 OAuth 对象进行调用而不发出另一个请求。

我正在使用 Angular 的以下包装器来连接到 Facebook。 https://github.com/ccoenraets/OpenFB

您不需要包装器。 $firebaseAuth() + $http() = easy Graph API 请求。

Graph API 非常易于使用,可以轻松与 Firebase 一起使用。

确保您启用了 Facebook 好友权限,否则您将无法取回任何数据。

您可以使用 $firebaseAuth() 登录并获取 Facebook access_token。该令牌可用于 Graph API 以通过 HTTP 请求获取数据。 Angular 有一个很好的 $http 库来进行这些调用。

不要介意我构建代码的方式,我更喜欢使用 Angular styleguide

angular.module('app', ['firebase'])
  .constant('FirebaseUrl', 'https://<my-firebase-app>.firebaseio.com/')
  .constant('FacebookAppId', '<app-id>')
  .service('RootRef', ['FirebaseUrl', Firebase])
  .factory('Auth', Auth)
  .factory('Friends', Friends)
  .controller('MainCtrl', MainCtrl);

function Friends($http, RootRef, $q, FacebookAppId) {

  function getFriends() {
    // get the currently logged in user (may be null)
    var user = RootRef.getAuth();
    var deferred = $q.defer();
    var token = null;
    var endpoint = "https://graph.facebook.com/me/friends?access_token="

    // if there is no logged in user, call reject 
    // with the error and return the promise
    if (!user) {
      deferred.reject('error');
      return deferred.promise;
    } else {
      // There is a user, get the token
      token = user.facebook.accessToken;
      // append the token onto the endpoint
      endpoint = endpoint + token;
    }

    // Make the http call
    $http.get(endpoint)
      .then(function(data) {
        deferred.resolve(data);
      })
      .catch(function(error) {
        deferred.reject(error);
      });

    // return the promise
    return deferred.promise;
  }

  return {
    get: getFriends
  };
}
Friends.$inject = ['$http', 'RootRef', '$q', 'FacebookAppId'];

function Auth($firebaseAuth, RootRef) {
  return $firebaseAuth(RootRef);
}
Auth.$inject = ['FirebaseAuth', 'RootRef'];

function MainCtrl($scope, Friends) {

  $scope.login = function login() {
    Auth.$authWithOAuthPopup('facebook').then(function(authData) {
      console.log(authData, 'logged in!');
    });
  };

  $scope.getFriends = function getFriends() {
    Friends.get()
      .then(function(result) {
        console.log(result.data);
      });
  };

}
MainCtrl.$inject = ['$scope', 'Friends'];