javafacebookrestfb

What's the correct way to obtain a page access token with restfb?


From my application I need to post images in a photo album of a Facebook Page.

Following resfb docs I'm implementing the OAuth flow. In particular I created the login url this way:

FacebookClient client = new DefaultFacebookClient(Version.VERSION_2_12);
String loginDialogUrlString = client.getLoginDialogUrl(APP_ID, REDIRECT_URL, scopeBuilder);

but now I can't understand I to create the Page Access Token.

I've tried using this:

AccessToken accessToken = client.obtainUserAccessToken(APP_ID, APP_SECRET, REDIRECT_URL, verificationCode); // verification code from the the previous login

but when I try to post contents on my page using this (USER) access token I get this error:

com.restfb.exception.FacebookOAuthException: Received Facebook error response of type OAuthException: (#210) A page access token is required to request this resource. (code 210, subcode null) 'null - null'

So, what's the correct way to obtain a PAGE access token?

NOTE I'm using this code to post the photo:

byte[] imageAsBytes = fetchBytesFromImage();
JsonObject obj = client.publish(
        "mypage",
        JsonObject.class,
        BinaryAttachment.with("cat.jpg", imageAsBytes, "image/jpeg"),
        Parameter.with("message", "A cat")
);

Solution

  • With a FacebookClient that was created with a user access token you can call:

    Connection<Account> connection = client.fetchConnection("/me/accounts", Account.class);
    

    and then iterate over the connection, and you can access all page access tokens of the pages the user is admin of.