88

I'm using the graph api.

I have a logged in user, and want to get back a list of page ids of all the pages that the user is an admin of.

Is there a way of doing this? The docs are pretty bad - and circular.

Steven Mercatante
  • 24,757
  • 9
  • 65
  • 109
EoghanM
  • 25,161
  • 23
  • 90
  • 123

10 Answers10

150

Its simple with Graph API. Steps:

  1. Get the manage_pages permission from the user (extended permissions).
  2. Call the Graph API - https://graph.facebook.com/me/accounts

You can test this procedure in the graph explorer -> Just click on 'Get Access Token' button-> under 'Extended permission' check 'manage_pages' & submit it. It will give you the admin-page-details JSON.

yprez
  • 14,854
  • 11
  • 55
  • 70
Avisek Chakraborty
  • 8,229
  • 10
  • 48
  • 76
  • 11
    Switching answers as this sounds like the more standard/stable way of doing it. Although I would warn against any use of the word 'simple': everything is simple once you know how :) – EoghanM Mar 02 '12 at 09:33
  • 1
    ya. u r right. But there can be several solutions to a problem. We need to choose the simplest among them. – Avisek Chakraborty Mar 02 '12 at 12:08
  • 1
    If you're using FB PHP SDK it's easier: just $user_admin_pages = $facebok->api('/me/accounts'); – Jepser Bernardino May 03 '12 at 18:24
  • 2
    The advantage of querying with FQL vs. using a graph request is that graph always forces the returned data to be 'paged' (it only returns the first few results, and a link to the next few) - while in FQL it always returns the entire result-set in one time. – Yuval A. Apr 28 '13 at 12:33
  • 6
    Thanks. It lists pages only if the current user administrates app. Is there any way to list pages of another person? – Soorajlal K G Jan 02 '15 at 13:51
  • 1
    Can i get any facebook page details without login? i have my app id and app secret – Maha Dev Dec 03 '15 at 13:27
  • ^ I need the same. Did you find anything about ? – activ8 Feb 16 '17 at 15:19
  • Think you can list the pages of another Facebook user if you supply their `id` in lieu of `me` in the endpoint for the `GET` request... – Kris Stern Apr 23 '20 at 07:52
  • I agree with @Soorajkal, this does not return the pages if the page is not in the app administered by the user. Which is what I need. Is there a way to do it? – Masroor Nov 03 '20 at 10:02
14

I solved it with some FQL:

FB.api({method: 'fql.multiquery',
        access_token: <access_token>,
        queries: {
            query1: 'select page_id from page_admin where uid = ' + <uid>,
            query2: 'select page_id, name, page_url from page where page_id in (select page_id from #query1)'
        }
       }, function(queries){
           var pages = queries[1].fql_result_set;
       }}
sakibmoon
  • 2,026
  • 3
  • 22
  • 32
EoghanM
  • 25,161
  • 23
  • 90
  • 123
  • 6
    As of August 2014: "The FQL and REST APIs are no longer available in v2.1: Previously announced with v2.0, apps must migrate to versioned Graph API calls starting with v2.1.". In other words, the FQL can no longer be used. – Kapitein Witbaard Aug 26 '15 at 07:31
12

go to this address

https://developers.facebook.com/tools/explorer/431294226918345/?method=GET&path=me%2Faccounts%3Ftype%3Dpage`

Just click on get Access token and go to extended Permission

Check the manage_pages checkbox

and click Get Access Token

Then under FQL write this

me/accounts?type=page

Click on Submit . and you will get all page lists that logged in user admin

Tarun Gupta
  • 6,305
  • 2
  • 42
  • 39
11

You can call FB.api(/me/accounts) if you don't want to use FQL.

'accounts' is a connection of the User object. See the documentation for this @ http://developers.facebook.com/docs/reference/api/user

Of course, with Facebook, there's always a catch. Right now this method will return not only the pages the user is an admin of, but also what applications they have installed. I'm almost positive this is NOT the intended behavior - I seem to remember using this a few months ago and only getting a list of pages. The documentation makes no mention of applications in this list either.

This is an easy problem to solve though - Facebook returns the name, category, and id for each item on the list, and each application has a category of 'Application'. I'm simply making sure I only list items whose category is not 'Application'.

Steven Mercatante
  • 24,757
  • 9
  • 65
  • 109
7

You ask for the permission with the JavaScript SDK on login

FB.login(function(){}, {perms:'manage_pages'});

and then once they log in you can retrieve the pages (and apps) as follow :

FB.api('/me/accounts', function(response){
    console.log(response);
})
sakibmoon
  • 2,026
  • 3
  • 22
  • 32
7

You can also use "pages_show_list" permission, if you want only the list of facebook pages the user is admin of.

The "manage_pages" permission will ask the user permission to manage his pages, which can be too intrusive depending on what you need it for.

glneto
  • 527
  • 3
  • 10
5

Permission

$facebook->getLoginUrl( array( "scope" => "manage_pages" ) );

action

$accounts = $facebook->api('/me/accounts');  
return $accounts;
Saurabh Chandra Patel
  • 12,712
  • 6
  • 88
  • 78
5

Note that your solution returns Pages as well as Applications. If you strictly want Pages, you can use FQL Multiquery with a "Type not equals" clause like this:

{
"query1":"select page_id from page_admin where uid = me()",
"query2":"select page_id, name, page_url, type from page where type!='APPLICATION' AND page_id in (select page_id from #query1)"
}
dbau
  • 16,009
  • 2
  • 21
  • 31
1
<head>
 <link rel="stylesheet" href="@Url.Content("~/Content/jquery.remodal.css")">
</head>

<body>
<script type="text/javascript" src="@Url.Content("~/Scripts/Home/jquery.remodal.js")"></script>
<div class="remodal" id="page-selector-remodal" data-remodal-id="pageselector">
        <p>Please select a facebook page Share </p>
        <div id="page-name-container">
            <select id="page-name" class="form-control">
            </select>
        </div>
        <a class="remodal-confirm" id="facebookPageSelectSubmit" href="#">OK</a>
        <a class="remodal-cancel" id="remodal-cancel" href="#">CANCEL</a>
    </div>

    <div data-remodal-id="modal-status">
        <p id="modal-status-content">
            The Account you have selected does not have Email.
        </p>
        <br>
        <a class="remodal-confirm" href="#">OK</a>
    </div>
<script type="text/javascript>
 (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'));

        window.fbAsyncInit = function () {
            FB.init({
                appId: 'YOUR APP ID',
                cookie: true,  // enable cookies to allow the server to access 
                // the session
                xfbml: true,  // parse social plugins on this page
                version: 'v2.2' // use version 2.1
            });
        };

        var pageSelector = $('[data-remodal-id=pageselector]').remodal();
        var modalstatus = $('[data-remodal-id=modal-status]').remodal();

        function statusChangeCallback(response) {

            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.
                $("#modal-status-content").empty().html(response.status);
                modalstatus.open();
            }

            else {
                $("#modal-status-content").empty().html(response.status);
                modalstatus.open();
                // 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.';
            }
        }


        function FacebookHandler() {
            FB.login(function (result) {
                if (result != null && result.authResponse != null && result.authResponse != undefined) {
                    facebookPageData = result;
                    FB.api('/me/accounts', function (accountsResult) {
                        if (accountsResult != null && accountsResult.data.length != 0) {
                            //open the remodal here
                            pageSelector.open();
                            facebookAccountsData = accountsResult;
                            var data = accountsResult['data'];
                            if (data != null) {
                                for (var i = 0; i < data.length; i++) {
                                    $("#page-name").append('<option value="' + data[i].id + '">' + data[i].name + '</option>');
                                }
                            }
                            unblockUI('body');
                            $("#flip-container, #feature-container, #branding-container, #intro-arrow-container, #share-container, #copyright-text-container").hide();
                            $("body").css("padding-right", "0");
                        }
                        else {
                            $("#modal-status-content").empty().html("The Account you have selected does not have any facebook page,<br />Post to Wall.");
                            modalstatus.open();
                            pageSelector.open();
                            unblockUI('body');
                        }
                    });
                }
                else {
                    $("#modal-status-content").empty().html("Unable to retrieve your details from facebook, try again after sometime.");
                    modalstatus.open();
                    unblockUI('body');
                }
            }, { scope: 'manage_pages, publish_stream' });
        }

        $("#facebookPageSelectSubmit").on("click", function () {
            var facebookpageId = $("#page-name option:selected").val();
            if (facebookpageId != null) {
                FB.api('/' + facebookpageId, function (identity) {

                    if (identity != null) {
                        FB.api('/' + facebookpageId, { fields: 'access_token' }, function (resp) {
                            if (resp.access_token != null) {
                                //Get the "resp"(Data) here
                        }
                        else {

                        }

                    });
                }

                else {

                }
            });
        }
        else {

        }
    });
</script>

//Finally call the "FacebookHandler()" function on click


</body>
0

With the new GRAPH API v3 with Javascript use the 'tasks' field instead of 'perms' field.

//Example JS Call
FB.api('/me/accounts?fields=name,picture.type(square),access_token,tasks', function(response) {console.log(response)});

//Example Response
{
      "name": "Engage",
      "picture": {
        "data": {
          "height": 50,
          "is_silhouette": false,
          "url": "https://scontent.xx.fbcdn.net/v/t1.0-1/c1.0.50.50a/p50x50/430597_259746387431503_2144341304_n.jpg?_nc_cat=103&_nc_eui2=AeGVrU8Wxe7k5BMvRXOEAcUo9dMIxyeMP9POPkYDwfgdRl8QquAtz1GcwXpJaK4z_0o&_nc_ht=scontent.xx&oh=e5b952a4adbbcd1b1af6b71b688f7284&oe=5CF9A64C",
          "width": 50
        }
      },
      "access_token": "XXXXXXXXXX",
      "id": "253263371413138",
      "tasks": [
        "ANALYZE",
        "ADVERTISE",
        "MODERATE",
        "CREATE_CONTENT",
        "MANAGE"
      ]
    }

Instead of looking of 'ADMINISTER' within the array, look for 'MANAGE'.

Full info here: https://developers.facebook.com/docs/pages/access-tokens

Jason Engage
  • 437
  • 4
  • 14