Publish to Facebook page or application’s wall with PHP

Just after implementing the Twitter Oauth API to publish tweets from a PHP application, I thought that doing the same with Facebook would be a piece of cake. Well, not quite, although I’ve finally managed to have the messages published to a page wall, or even to an application’s page wall from an automated script. In this article I explain some of the problems I encountered and how to solved them. I hope this example may be of help if you are having trouble with this.

Publishing to a page’s wall

According to the Facebook documentation, we need to register an application in order to use it to publish messages to a page’s wall. The process is explained on that page, so this should be a good moment to read it.

The process could be summarized as follows:

  1. Create an application.
  2. Get the token for that application to manage the user’s pages (where the user is administrator of those pages).
  3. Get the specific token for that application through the user to a precise page.

While it should have been worked as it is explained on the documentation, I was having the following error:

(#200) The user hasn’t authorized the application to perform this action

So… why? According to the documentation, manage_pages is the only permission required for an application to access a page, and everything seemed in order. Actually, it wasn’t. After some tests going back and forth and some googleing, I realized I didn’t have enough scope, and adding publish_stream and read_stream seemed to be a requirement for the application to actually write to page’s wall. In addition, offline_access would produce a token that does not expire.

Once this issue fixed, the following steps should lead to a successful publication in a page’s wall from an external script:

  1. Register your application here.
  2. Obtain access to manage pages from the authorized page administrator
    https://www.facebook.com/dialog/oauth?client_id=$id&client_secret=$secret&redirect_uri=$uri&scope=publish_stream,offline_access,read_stream,manage_pages&response_type=token
  3. Get an access token to the precise page of that administrator
    https://graph.facebook.com/me/accounts?access_token=$all_apps_token
  4. Now you should be able to publish to that page with this token through a POST call to
    https://graph.facebook.com/$page_id/feed

Here you are an example in PHP that uses this token to publish messages:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
class Facebook
{	    
    /**
     * @var The page id to edit
     */
    private $page_id = 'XXX';	
 
    /**
     * @var the page access token given to the application above
     */
    private $page_access_token = 'YYY';	
 
    /**
     * @var The back-end service for page's wall
     */
    private $post_url = '';
 
    /**
     * Constructor, sets the url's
     */
    public function Facebook()
    {
        $this->post_url = 'https://graph.facebook.com/'.$this->page_id.'/feed';
    }
 
    /**
     * Manages the POST message to post an update on a page wall
     * 
     * @param array $data
     * @return string the back-end response
     * @private
     */
    public function message($data)
    {   
        // need token
        $data['access_token'] = $this->page_access_token;
 
        // init
        $ch = curl_init();
 
        curl_setopt($ch, CURLOPT_URL, $this->post_url);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
 
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
 
        // execute and close
        $return = curl_exec($ch);
        curl_close($ch);
 
        // end
        return $return;        
    }
}
 
$facebook = new Facebook();
 
$facebook->message(array( 'message'     => 'The status header', 
                          'link'        => 'http://theurltopoint.to', 
                          'picture'     => 'http://thepicturetoinclude.jpg',
                          'name'        => 'Name of the picture, shown just above it', 
                          'description' => 'Full description explaining whether the header or the picture' ) );

Publishing to an app’s wall

In some cases, we might want to publish to the application’s wall itself, so that there is no need to have a second application to publish to the first one’s wall.

According to some of the discussions on the matter that can be found on the internet, this should work by simply using $page_id as the target and the same $page_id to request the manage_pages permission.

In this case, we would follow the same process explained above, but slightly simplified:

  1. Register your application here.
  2. Obtain an access code for your application
    https://graph.facebook.com/oauth/access_token?type=client_cred&client_id=$id&client_secret=$secret
  3. Now you should be able to publish to the application’s wall with the token obtained through a POST call to
    https://graph.facebook.com/$app_id/feed

However, Following the steps above, I obtained an error again:

{“error”:{“type”:”OAuthException”,”message”:”(#200) Posts where the actor is a page cannot also include a target_id”}}

Which was way confusing since there shouldn’t be any limitation according to Facebook’s documentation. After some searching and reading literature about (here and here), I discovered that publishing from an application to its own wall is doable, and in fact it works very well with the JS API provided by Facebook.

Then why the JS API would achieve the goal while its web service sister just throws a mystic error? It was quite obvious that they had to be using somewhat different service url’s… after inspecting the HTTP calls made by the JS API and was surprised to found that it is actually a GET (instead of POST call):

https://graph.facebook.com/$app_id/feed?access_token=$token&callback=FB.ApiServer._callbacks.$some_callback_id&message=Hello%2C%20World!&method=post&pretty=0&sdk=joey

I just had to test this new url with the parameters of my application, and this time it just worked as expected:

https://graph.facebook.com/$app_id/feed?access_token=$api_access_token&message=Hello%2C%20World!&method=post

This is the only solution I have found so far to be able to publish messages from PHP on behalf of an application itself. It is a bit awful, but I haven’t found any other way to make this work, and the documentation provided by Facebook seems like knocking on a wall.

Has anybody found any better solution for this problem? Comments are welcome!

47 thoughts on “Publish to Facebook page or application’s wall with PHP

  1. Hi Jorge,

    Thank you for your helpful post. I’ve got a question regarding your script though:

    Where in the code are you authenticating with the $page_access_token?? So far I haven’t been able to post to my page’s wall, even though I’ve gone through the whole process you described above.

    Another small note: why did you make the function message private? That way you wouldn’t be able to call the function through the object $facebook right??

  2. Hello Robin, thanks for your comment. You are right in both subjects: the function ‘message’ must be public to be called from an instance of the Facebook class, and $page_access_token must be added to the POST message as ‘access_token’. I’ve corrected the code in this post’s body.

    Please let me know if you are still having trouble with this script to work.

  3. Thanks so much for this information, I’ve been trying to do similar myself and the information has been extremely lacking from Facebook documentations.

    Does this require my website to have an SSL cert? When trying to register my application its requiring that I fill in a secure link section.

  4. Hi Jorge,

    Thanks for your sharing! It’s work for me.

    Could you advise how to change the poster name with application’s name not the application owner’s name?

  5. Thanks for the code.

    Needed to change the following line:
    curl_setopt($ch, CURLOPT_URL, $this->post_page_url);

    to:
    curl_setopt($ch, CURLOPT_URL, $this->post_url);

    And, if the following wasn’t clear to everyone, what should go here:
    private $post_url = ”;

    use the following as the value:
    https://graph.facebook.com/$page_id/feed

    Thanks again!

  6. It looks like you have EXACTLY what I am looking for… now I have to go thru this step by step and get the silly thing to work.

    (basically the ability to post comments to our FB Page “https://www.facebook.com/pages/Inferno-Online-Stockholm/149232401793444” from the website “www.infernoonline.com/” (you would think this was a little more straight forward)

  7. Thank you Jorge . It worked fine for me. At first I thought I should download and include php-sdk. But it was not needed.
    Thank you james for giving hint of $post_url.

  8. Hello and thank you for your code, it works very well !
    I want to know if it is possible to post at the page’s wall as the “page” and not as the page owner. Currently when i make a post, i post by my facebook name instead of my page’s name.

    Thank you in advance.

  9. I followed all the steps but I dont understand why I get a blank page when I run the code! :S

  10. Yes I would be keen to know (like redion) how to ‘post as the app’ and not as the facebook user. If that is even possible.

  11. @redion: Check the return value of $facebook->message(), I haven’t had the need to use it for my project but as far as I can remember, there is some information about the publication there.

  12. @Jeff & @redion As far as I know, it is not possible, at the least I haven’t found a way. Due to the tokens system in Facebook, you need whether a user, whether an application to publish on a page, therefore their information will appear on the publication credits, instead of it being posted as the page itself. If anybody has found a solution to this problem, please let us know!

  13. Thanks Jorge for this helpful post,

    I am able post on my page but the problem is whatever I post is posted as me and not the page itself, secondly I am unable to post images (though I’ve setup things in the curl part) and it actually posts images on my profile instead of the page.

    please help.

  14. Trying to get the access token, but Facebook only returns “An error occurred. Please try again later.”

    I’ve added client_id = app id and client_secret = app secret.

    And the redirect_uri goes to my page wall.

    Did I miss something?

  15. Very nice post mate thanks.

    One question (sorry i am a noob) how can I call external vars in the final array ?
    Like :
    $facebook->message(array(
    ‘message’ => $dbvar1,
    ‘link’ => $dbvar2 ) );

    so i can get that data for dbvar1 and dbvar2 from a database call.

    Thanks allot
    Larry

  16. Have the same problem, like you, Urme, but your solution also doesn’t work for me. Got the JSON-Error-Object

    {
    error: {
    message: “Invalid redirect_uri: Die Anwendungseinstellungen lassen die angegebene URL nicht zu.”,
    type: “OAuthException”,
    code: 191
    }
    }

    (Translated from german: “ARL not allowed by app settings”).
    Any idea?

    It’s driving me crazy: Just want to do a f***g post to a pages’ wall and blowed out about 5 hours without any working solution, because google find’s many solutions but finding and interpreting the RIGHT solution is a pain.

  17. It seems like this is what I need, but no idea of how to use it, can you be less “dev” and give to some of us the steps as in where this code need to be placed ? thanks a lot

  18. Nice tut. But i have one problem. The Share link doesn`t apear on my posts. Can i solve this? Thanls

  19. Hi ! Nice post, exactly what I need. I have FB page (facebook.com/pages/…/…/) and need to post on its wall from an e-shop. I have problem with point 2 – https://www.facebook.com/dialog/oauth?….. Error 500 after this. I also tried Urme’s method. Not working too :O( Maybe error in FB application settings – any hints how to setup it correctly ? Thank you very much.

  20. can a publish all my content of div tag…
    it contain 3 images
    Background image
    And two simple Img …

    reply asap

  21. “offline_access would produce a token that does not expire.”

    This is no longer true, after May 2012.
    Facebook now only gives you a two hour token, that can be extended to 60 days.

    ..Just noticed this after implementing and deploying a working setup based on your class. (yes, in less than two hours) 😉

  22. Hi Sven, thanks for your comment. It has changed on May 1st, indeed. Some info https://developers.facebook.com/roadmap/offline-access-removal/ and a couple of keypoints:

    – Tokens generated before that change will see their expiration time truncated to 60 days.
    – Tokens with a long-lived expiration time “can be renewed each time the user revists your app” – I understand that as long as the token is being used within the 60 days, it will never expire.
    – According to FB: “Once the migration is enabled, if the access_token is generated from a server-side OAuth call, the resulting access_token will have the longer expiration time by default”. Please note the “server-side” part, this might not be case if using JS auth libraries.

    Said this, I haven’t had any issue so far, the migration has been transparent for me – although I didn’t request any new token during it. How exactly did you do to get a 2h token instead of a 60day one? Did you try during the transition period without checking “deprecate offline_access” on your FB configuration?

    Thanks again for sharing!

  23. Hi guys, I was experiencing some problems while trying to post to page through app when the user was logged out. The reason of that is that Facebook is changing the flow of server-side authenticating and removing the offline access permisions (http://developers.facebook.com/roadmap/offline-access-removal/). The access token you get using code in this tutorial is now only short-lived. To get a long-lived token, which you can use to post to page even with a logged out user, you need to follow these instructions: https://developers.facebook.com/docs/authentication/server-side/ . Hope it helps!

  24. I have a BIG trouble – I have to solve a serious puzzle with Facebook.

    I need to publish to the application’s wall itself from my PHP-application. I created the application with the page.

    So I try to do the next things:

    1.
    I get an access code for my application:
    https://graph.facebook.com/oauth/access_token?type=client_cred&client_id=$id&client_secret=$secret (type this URL to browser)

    2.
    I try to publish a message on application’s page:
    https://graph.facebook.com/$app_id/feed?access_token=$api_access_token&message=Hello%2C%20World!&method=post (in browser again)
    API returns ID of the “just created” post, but I don’t see any new posts on application’s page!
    If I change $app_id to $page_id (numeric page identification in FB) API returns error message: “(#200) The user hasn’t authorized the application to
    perform this action”.

    Can you give me advice what can I do to post the message to the application’s wall from the application?

  25. if you have multiple apps facebook will get the first app(appId) in line. Any idea how to set this to my other app?

  26. A thousand thank you’s to you Jorge! I was getting really frustrated after many lost hours trying to achieve this and finally I found your post – minutes later I can do exactly what I need.

    Much appreciated sir! :)

  27. By the way, for those wanting to post as a fan page with a permanent access token:

    1) Follow the above steps until you have your access token

    2) Follow the post by Urme above to set your apps permissions (being sure to including manage_pages in the scope)

    3) Then use the token you have and extend it by submitting this URL;
    https://graph.facebook.com/oauth/access_token?
    grant_type=fb_exchange_token&
    client_id=APP_ID&
    client_secret=APP_SECRET&
    fb_exchange_token=SHORT_LIVED_ACCESS_TOKEN

    4) This will return another (long life) token. Enter that via:
    https://graph.facebook.com/me/accounts?access_token=token

    This will return details of each page you are an adminitrator of including an ID number and access token specific to each. When you check these in the facebook Access Token Debugger they should say expires: never

    5) Use the relevant access token for your page, your page ID number and Canvas URL in Jorges class and you should be able to post to your page as your page.

    To answer Joseph above, this will indeed work as a cronjob – mine autoposts data drawn from my database daily via cron.

    Hope this helps!

  28. Facebook is effective to promote, if known what to do to use it effectively. Probably why it’s so difficult is because the administrator’s do not communicate in their audience’s language. We know it’s not easy, as it’s difficult to grow a large fan base.

  29. Hi !

    Great article, with good compements in comments. Publish on FB fan page is really simple with this method.

    But just a question : is someone has succeed to post photos on facebook page with the API ?

    I succeed in choose my thumbnail image for links but upload don’t want to work…

  30. Forget my previous question, I fixed the bug.

    I tried to upload some cross-domains image and apparently it doesn’t work but same domain images work fine.

  31. Hi Jorge,
    Great article! We were stucked around this topic until i’ve read your article.
    I still can’t understand why FB made interaction like these a pain in the ***. :)

    thankyou anyway.

  32. Hi Guys,
    In this code example line: 56
    $facebook = new Facebook();
    returns 0, if not pass $config array to create object of the class.
    There should have APP_ID in this config array.
    (I am using facebook Version 2.0).
    So, how can I get current logon user id before creating object from facebook class??

  33. Hi,

    I have change the code to upload a photo to a Page. Thats works very fine. The problem is that only I can see the Photo. Can someone help me?

Leave a Reply

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