Search code examples
phpfacebookcurlfeed

Post a feed on facebook after a form on my website


I have a news form on my website. After creating this news message I want to publish it on Facebook. I tried alot of things, but nothing was working. Here is my class:

<?php

class Facebook {

    const FACEBOOK_APP_ID           = 'MY_APP_ID';

    const FACEBOOK_APP_SECRET       = 'MY_APP_SECRET';

    const FACEBOOK_ACCESS_TOKEN_URI = 'https://graph.facebook.com/oauth/access_token';

    const FACEBOOK_FEED_URI         = 'https://graph.facebook.com/app/feed';

    private function getAccessToken() {
        $params = array(
            'client_id'     => self::FACEBOOK_APP_ID,
            'client_secret' => self::FACEBOOK_APP_SECRET,
            'grant_type'    => 'client_credentials',
        );

        $ch = curl_init();

        curl_setopt($ch, CURLOPT_URL, self::FACEBOOK_ACCESS_TOKEN_URI);
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $params);

        $data = curl_exec($ch);

        curl_close($ch);

        return substr($data, strpos($data, '=') + 1);
    }

    public function sendFeed() {
        $params =  array(
            'access_token'  => $this->getAccessToken(),
            'message'   => $message,
            'name'      => $name,
            'link'      => $url,
            'description'   => $description,
        );

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, self::FACEBOOK_FEED_URI);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 

        $data = curl_exec($ch);

        curl_close ($ch);

        return $data;
    }

}

If I call the method sendFeed() it returns the following:

{"id":"404322099626551_404397542952340"}

I think the submit was successfull, but when I visit my page on facebook, there is no new feed. What am I doing wrong? I searched the complete day and couldn't get it to work. I thank you for your help.


Solution

  • What you are doing here is posting it on your user's feed. You are using a user access token. What you want to use is a page access token.

    You'll need the manage_pages permission to perform tasks on behalf of your page.

    In addition you should consider using the official PHP SDK, it'll make accessing Facebook's API much easier and improve readability.