Post to Facebook Fanpage as Page Admin through App via Impersonation

There seems to exist a lot of confusion when it comes to (programmatically) posting to Facebook (FB) fanpages through the PHP SDK, especially when trying to post as one of the page’s admin through an app via impersonation. Thus, instead of posting through your regular FB user account you want to directly post to a fanpage as the page’s admin (owner), without the hazzle of being forced to login for each post. Fortunately, there are only a few simple steps required to achieve this functionality which will be explained in the following.

Request App access token

First and foremost, the app through which you will be posting to the fanpage (as its admin) needs to request certain permissions, which can be done using the following link:

https://www.facebook.com/dialog/oauth?client_id=YOUR_APP_ID&client_secret=YOUR_APP_SECRET&redirect_uri=YOUR_REDIRECT_URL&scope=read_stream,publish_stream,offline_access,manage_pages

In order to be able to use this link you need to determine YOUR_APP_ID and YOUR_APP_SECRET via http://developers.facebook.com. Furthermore, in order to be able to post to the fanpage programmatically you need the offline_access permission. Additionally, to impersonate the fanpage’s admin manage_pages and publish_stream permissions are required.

Please note that FB is planning to deprecate the offline_permission in favor of a functionality to extend the lifespan of existing access_tokens. Read more here: https://developers.facebook.com/roadmap/offline-access-removal/

Based on the URL provided above you will be redirected to FB’s login page in case you are not already logged in as the account associated for YOUR_APP_ID. Once logged in, you will be redirected to YOUR_REDIRECT_URL where you’ll find the access token as a GET parameter. Alternatively, if you do not operate your own test environment for checking the response of this call (i.e. YOUR_REDIRECT_URL) you can simply use the following call, as stated in the client-side authentication flow in the official documentation.

https://www.facebook.com/dialog/oauth?client_id=YOUR_APP_ID&redirect_uri=https://www.facebook.com/connect/login_success.html&response_type=token&scope=read_stream,publish_stream,offline_access,manage_pages

This step needs to be done only once, unless you decide to change your permissions at a later point which will require you to re-authorize using the same link. Be sure to check out Authentication section in the Facebook Developer notes.

In case you get the “An error occurred. Please try again later.” message make sure that YOUR_REDIRECT_URL matches the one of your FB app.

Request (Fan)Page access token

Once you have acquired the permissions to post through your app the next step is to request the access token for the fanpage, based on the app’s authentication previously requested. Using this token you will be able to post on the fanpage through your app without the need to go through the client-side authentication process every time.

$pageInfo = $facebook->api("/$pageId?fields=access_token");

$pageInfo now holds an array, including the field access_token. Based on this access token we are ready to finally post to the fanpage as one of its admin (impersonation). Alternatively, in case this call does not return the access token you can issue a direct call to the OpenGraph API, as mentioned in server-side authentication flow:

https://graph.facebook.com/oauth/access_token?client_id=YOUR_APP_ID&redirect_uri=YOUR_REDIRECT_URI&client_secret=YOUR_APP_SECRET&code=CODE_GENERATED_BY_FACEBOOK

The code parameter represents the access token returned in the app-authentication step, which in our case does not expire due to the offline_access permission.

Post to Fanpage as Admin

try {
  $args = array(
    'access_token' => $page_info['access_token'],
    'message' => 'TEST'
  );
  $post_id = $facebook->api("/$pageId/feed", "post", $args);
} catch (FacebookApiException $e) {
  die($e->getMessage());
}

The final PHP code

Although the first step (request app access token) can also be done programmatically, normally you will do this manually as this is only required once. Acquiring the fanpage access token can be easily done on each request. Please contact FB’s Graph API for all methods. The following code snippets shows how to post a message to the fanpage. For instance, use LINK instead of FEED to post links.

$appid = 'XXX';
$appsecret = 'XXX';
$pageId = 'XXX';

$facebook = new Facebook(array(
  'appId' => $appid,
  'secret' => $appsecret,
  'cookie' => false,
));

$user = $facebook->getUser();

if ($user) {
  try {
    $page_info = $facebook->api("/$pageId?fields=access_token");
    if (!empty($page_info['access_token'])) {
      $args = array(
        'access_token' => $page_info['access_token'],
        'message' => 'TEST'
      );
      
      $postId = $facebook->api("/$pageId/feed", "post", $args);
    }
  } catch (FacebookApiException $e) {
    error_log($e);
    $user = null;
 }
}

That’s all there is to it!

You may also like...

33 Responses

  1. Jim says:

    When I tried your code the $page_info array only contains the page id, not the access token. I am using print_r($page_info); to see this array. I’m not sure what I am doing wrong. I got the permissions using the method you suggested. There was an access token returned but I’m not sure what do to with that access token.

    • Hi Jim,
      I’ve updated the post. It now includes another way to request the access token, by directly invoking to OG API. Please note that it is not required to request the access token every time you want to post to your page. Instead, using the offline_access permission you are able to request a permanent access token (although FB has already announced to remove the offline_access permission in the near future…). Either way, you are able to programmatically request this access token prior to posting to your wall or persisting it to your database (etc.) for future use. Hope that helps. Cheers

  2. Christian says:

    Hi,
    First of all, I really liked the way you explained all the steps to achieve this in your post.
    Second of all, I’d like to ask you for an alternative to the permission “offline_access”, knowing it’s going to be deprecated I’ll like to know how to proceed about that.
    Thanks! and Keep up the good work!

  3. Hello Christian,

    first of all existing FB apps do not have to be changed. Instead, FB is depecrating the offline_access permission in favor of a new functionality to increase the lifespan of existing access_tokens.

    Please have a look at their offical statement on this matter: https://developers.facebook.com/roadmap/offline-access-removal/.

    Thanks for noticing that – I will add the link to FB’s official statement on this matter in the post.

    Cheers

  4. Kenny says:

    When trying to use your code I am receiving an error on the getUserInfo();

    Call to undefined method Facebook::getUserInfo()

    I pretty much copy pasted your code exactly.

    • Hello Kenny,

      sorry for the late response. getUserInfo() is wrong and should read getUser() – thanks for the feedback.

      Just for clarification: I’ve used getUserInfo() in another FB SDK abstraction class and copied the wrong line – sorry for the confusion.

      I’ve updated the code snippet accordingly. Have a nice weekend.

  5. repdef says:

    There is certainly a lot to learn about this issue. I like all of the points you made.

  6. ABHIJITH says:

    Hi, congrts for your work 🙂
    But am facing a small problem. when i run the page manually facebook gives link to login. if i click it then the content will post to the page as admin.
    But i need to run this page automatically and to post on wall as admin automatically by using cron job, and cant click on login link always. what should i do??

    • Hi there,

      could you please explain which “page” you mean that you run manually and get the login link.

      Basically, it is possible to automatically post through impersonation as the page’s admin, e.g. by using a cronjob like you are trying to do. This is the core message of this post 😛

      All you need to do is to authorize your FB app to post as the page’s admin, i.e. impersonate the admin account. Through your authenticated FB app you can do whatever you have access to.

      Cheers

  7. Roderick says:

    Hi,
    the result of using $user = $facebook->getUser(); is 0 (zero)
    I mean echo $user; I see 0.

    But why ? Can you help me ?

  8. Abbood says:

    Hi 🙂
    thanx for this ..

    can you look at this plz , it maybe help you ^_^

    https://www.facebook.com/connect/uiserver.php?app_id=YOU_APP_ID&&method=stream.publish&redirect_uri=http://www.facebook.com&attachment=}}&actor_id=YOUR_PAGE_ID

  9. YuSuF says:

    in Request (Fan)Page access token step ..,where we put this code??

    $pageInfo = $facebook->api(“/$pageId?fields=access_token”);

    • Hello YuSuF,

      sorry for the late reply. This code requests the access token for the fanpage (identified by $pageId) based on your previously authenticated app (i.e. your app access token). This code is used on line 15 of the “The final PHP code” section in the post. Hope that helps! Cheers

  10. Marco says:

    Hi,

    thanks for your work but the script is not working …

    I run some test and it seems to stop just after the

    $facebook->getUser();

    Can you help me please?

    Thanks

    Marco

    • Hello Marco, sorry for the late reply. Did you verify all the steps/suggestions mentioned above? Also, could you please provide more info what you mean by stops there. Cheers

  11. Jeff says:

    I too am having the $user = 0 issue. I followed your example but I’m not quiet sure what I need to do to be logged in from my site. Can you please explain?

    Thanks,

    • Hi Jeff,

      first of all please make sure that you have a valid app access token (so that you are able to post content by using this access token, use your app admin user for this) and a valid page access token (so that you actually can post through your app to the fanpage, use you page admin user for this).

      Second, make sure your app and page access token have not expired in the meantime, otherwise your attempt to automatically post to your fanpage will fail.

      Hope that helps 😛

  12. Ankit Sharma says:

    Hey, very nice article. But i got little confused now. As you said requesting app token is a one time process, so is it still valid after offline_access removal?

    Secondly, what about page token expiry, Does it expire or not ? If yes, how do i handle expired tokens at runtime?

    • Hi Ankit,

      due to the fact that FB is deprecating the offline_access token in favor of extending existing tokens I’m afraid that previously requested tokens will not be valid anymore. Thus, be sure to have a look at their new approach, as linked in the post.

      Since the page access token request merely uses the app access token it will too “expire” once the app access token has expired.

      I hope this sheds some light on your concerns 🙂

  13. Aby says:

    First of all Great Post…matthias.

    Actually i am facing some problems.

    i have written code to post to my page via an facebook application.

    But when i post it says “xyz has shared a link via abc”.

    where xyz is my page and abc is my application name.

    i want to post to my page as admin…

    in code i am not using the below code..

    $facebook = new Facebook(array(
    ‘appId’ => $appid,
    ‘secret’ => $appsecret,
    ‘cookie’ => false,
    ));

    Please guide.

    • Hi Aby!
      You need to get the page access token through your Facebook app in order to post as admin to your page, as described in the post. Once you have acquired this token you can use the code provided to post as the page admin through your app. Hope that helps. Sorry for the late reply BTW… Cheers

  14. Adi says:

    Hi!
    Good tutorial. I just want to know if its possible to post a note to a fan page as admin. I have been trying it for a long time now and I am facing a problem wherein the note is being posted to MY wall whereas it should be appearing on the page wall. I have included all the required permissions, page id, access token…everything. Yet I still face this issue! Could you please suggest a solution? Thanks!

    • Hi,
      sure you can. Simply adjust the API call to reflect this URL:

      https://graph.facebook.com/id_your_fanpage/notes?.

      After the “?” you need to specify the parameters shown in $args. Or you can call the API directly using cUrl:

      $access_token=’MY ACCES TOKEN FAN PAGE’;
      $args= array(
      ‘access_token’ => $accessToken,
      ‘message’ => ‘Message’,
      ‘subject’ => ‘Subject’
      );

      // set the target url
      $ch = curl_init();
      curl_setopt($ch, CURLOPT_URL,’https://graph.facebook.com/id_your_fanpage/notes?’);
      curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); // ignore SSL check
      curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
      curl_setopt($ch, CURLOPT_POST, true); // we need to POST data
      curl_setopt($ch, CURLOPT_POSTFIELDS, $args);
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, false); //suppress the curl output

      For information can be found here: https://developers.facebook.com/docs/reference/api/note/

      That’s it, enjoy 🙂

  15. Crony says:

    Hi,

    I am using PHP sdk for fanpage wall post.

    Sometimes its working fine,

    Sometimes ask switch account dialog. and redirect my return url with code parameter and stopped nothing happen why?

    Pls reply me

  16. Crony says:

    Thanks for ur reply.

    I receice Code parameter in the returlurl

    ex:www.website.com/facebook.php?code=ccdfe2323kefotfrtrt

    How i renew my token and continue to wall post

    Pls reply me

  17. Crony says:

    Hi I am using this code

    Some times it worked fine. sometimes get returnurl with code parameter and stppped

    $appid,
    ‘secret’ => $appsecret,
    ‘cookie’ => false,
    ));

    $user = $facebook->getUser();

    // Contact Facebook and get token
    if ($user) {
    // you’re logged in, and we’ll get user acces token for posting on the wall
    try {
    $page_info = $facebook->api(“/$pageId?fields=access_token”);

    if (!empty($page_info[‘access_token’])) {
    $attachment = array(
    ‘access_token’ => $page_info[‘access_token’],
    ‘message’ => $msg,
    ‘name’ => $title,
    ‘link’ => $uri,
    ‘description’ => $desc,
    ‘caption’ => $caption,
    ‘picture’=>$pic,
    /* ‘actions’ => json_encode(array(‘name’ => $action_name,’link’ => $action_link))*/
    );

    $status = $facebook->api(“/$pageId/feed”, “post”, $attachment);

    $msg=”Sucessfully Posted On Facebook Wall”;
    }
    else
    {

    $status = ‘No access token recieved’;
    }

    } catch (FacebookApiException $e) {
    error_log($e);
    $user = null;
    }
    } else
    {
    // you’re not logged in, the application will try to log in to get a access token

    header(“Location:{$facebook->getLoginUrl(array(‘scope’ => ‘photo_upload,user_status,publish_stream,user_photos,manage_pages’))}”);
    }

    echo $status;
    echo $msg;
    ?>

  18. Raj says:

    If i get more than one page info, how can i select the particular page in which my applications is tabed

  19. wissam says:

    check this step by step guide to get a permanent access token for a facebook page
    http://logicum.co/getting-a-facebook-page-permanent-access-token/
    you can use this token permanently instead of authenticating every time

  20. diego says:

    Hola gracias por el tutorial, te comento que logre publicar el la pagina pero luego al otro dia dejo de publicar y no tira error sino que el getUser() me retorna 0, como ño soluciono? gracias

Leave a Reply

Your email address will not be published. Required fields are marked *