LINUX.ORG.RU

Posting to facebook page from script using API


1

1

I need to develop application that automatically posts updates to its facebook page. So I logged into facebook.com and created app and page. I used this tutorial to obtain page access token:

http://aseriesoftubes.com/articles/obtaining-facebook-page-access-tokens-the-4-step-program/

To implement the process described in tutorial I've created 2 files, one.php:

<?php

require_once dirname(__FILE__)."/../lib/conf.php";

if (!( isset($_SESSION['user']) && $_SESSION['user']['email'] == ADMIN_EMAIL )) {
	header("Location: {$www_base}/user/login.php");
	exit;
}

header(
	"Location: https://www.facebook.com/dialog/oauth".
	"?client_id=".urlencode($facebookConf['app_id']).
	"&redirect_uri=".urlencode("{$www_base}/facebook/two.php").
	"&scope=manage_pages%2Cpublish_stream".
	"&state=state"
);
exit;

and two.php:

<?php

require_once dirname(__FILE__)."/../lib/conf.php";

if (!( isset($_SESSION['user']) && $_SESSION['user']['email'] == ADMIN_EMAIL )) {
	header("Location: {$www_base}/user/login.php");
	exit;
}

if (!( isset($_GET['code']) && is_string($_GET['code']) && $_GET['code'] != "" )) {
	header("Location: {$www_base}/facebook/one.php");
	exit;
}

require_once dirname(__FILE__)."/../lib/Curl.php";
$ch = new Curl();

$resp = $ch->get(
	"https://graph.facebook.com/oauth/access_token".
	"?client_id=".urlencode($facebookConf['app_id']).
	"&client_secret=".urlencode($facebookConf['app_secret']).
	"&code=".urlencode($_GET['code']).
	"&redirect_uri=".urlencode("{$www_base}/facebook/two.php")
);
if (!preg_match('#access_token=([^&]+)#Duis', $resp, $m)) exit("Wrong response while trying to receive access_token: |{$resp}|");
$access_token = $m[1];

$resp = $ch->get(
	"https://graph.facebook.com/oauth/access_token".
	"?grant_type=fb_exchange_token".
	"&client_id=".urlencode($facebookConf['app_id']).
	"&client_secret=".urlencode($facebookConf['app_secret']).
	"&fb_exchange_token=".urlencode($access_token)
);
if (!preg_match('#access_token=([^&]+)#Duis', $resp, $m)) exit("Wrong response while trying to receive long lived access_token: |{$resp}|");
$access_token = $m[1];

$resp = $ch->get("https://graph.facebook.com/me/accounts?access_token=".urlencode($access_token));
$json = json_decode($resp, true);
if (is_null($json)) exit("JSON error: |{$resp}|");

$pageToken = "";
foreach ($json['data'] as $page) {
	if ($page['id'] == $facebookConf['page_id']) {
		$pageToken = $page['access_token'];
	}
}

?>

<b>Your new page token is: </b>
<hr />
<textarea style="width: 90%;" rows="7"><?php h($pageToken); ?></textarea>
<hr />

<b>Please copy and paste it into 'lib/settings.php' -> $facebookConf -> 'page_token' so the line looks like this:<br /></b>

<textarea style="width: 90%;" rows="7">'page_token' => "<?php h($pageToken); ?>",</textarea>

<hr />

<pre><?php print_r($json); ?></pre>

So, from one.php browser redirects to facebook.com and facebook redirects it back to two.php. The code in two.php obtains the page access token and displays it for admin to insert into config file. This is the JSON array I received in two.php:

Array
(
    [data] => Array
        (
            [0] => Array
                (
                    [category] => Community
                    [name] => aliexpresspricewatcher.com
                    [access_token] => CAAKVUVmML7kBABbh5Adgp4AqnpJfakZB4rWr8DQjyLxIrZANgH6sAJv87RLPMwpn1sI3btu46kgaUQNZBGhvgyAUZCdm0TRcWQZBi2wUN034kbnEZCmzKCZCLGsUbGiTYCgilZC4X8EoClLw1cw8SUgg2R3iJjKwKM623RZCRVdYVXZBKHvpf1Nc9XJQLX2fISYUMZD
                    [perms] => Array
                        (
                            [0] => ADMINISTER
                            [1] => EDIT_PROFILE
                            [2] => CREATE_CONTENT
                            [3] => MODERATE_CONTENT
                            [4] => CREATE_ADS
                            [5] => BASIC_ADMIN
                        )

                    [id] => 381473385336541
                )

        )

    [paging] => Array
        (
            [next] => https://graph.facebook.com/v2.1/712868945455685/accounts?access_token=CAAKVUVmML7kBAEKWirBfCdP2VP0YVrhwGpbfDJ0ofLJ8s6RBdNxwY3UsFNN28NeAVrKPan21ZALfmgIqNAXKfsZAHqZArtZBDPrjfJp5mBBUZC0pf2KX6Yy0PL2kl5OIBOj0pKgXv9xzGpZCRERc8CtSeeUYaghkczDchQ14qU3PdzkWq22zi4&limit=1000&offset=1000&__after_id=enc_Aew6akARByTD9c1srd6xeb7_4aXnG9RGCU1VOF9V_ALfh9kDbiEHA0sZhMBBEcrnFtJlr7vPJeKWTu7mENZgDxTK
        )

)

So, I copied access token to my conf.php file and created test.php to test it:

<?php

require_once dirname(__FILE__)."/../lib/conf.php";

if (!( isset($_SESSION['user']) && $_SESSION['user']['email'] == ADMIN_EMAIL )) {
	header("Location: {$www_base}/user/login.php");
	exit;
}

require_once dirname(__FILE__)."/../lib/Curl.php";
$ch = new Curl();

$resp = $ch->post(
	"https://graph.facebook.com/v2.1/{$facebookConf['page_id']}/feed",
	"message=This+is+a+test+message"
);
echo "|{$resp}|";

But it shows an error:

|{ "error": { "message": "(#200) Permissions error", "type": "OAuthException", "code": 200 } }|

What did I do wrong? Please advice, it's very hard to find complete information in facebook documentation, worst documentation I've ever seen. The project is almost finished and this is the only feature I have no idea how to fix because I have no previous experience with facebook.

What did I do wrong?

$resp = $ch->post(
	"https://graph.facebook.com/v2.1/{$facebookConf['page_id']}/feed",
	"message=This+is+a+test+message"

↑ you're not supplying AppID and secret in this request.

x3al ★★★★★ ()
Ответ на: комментарий от reprimand

потому что текст поста на английском?

И какое это имеет отношение к троллингу? С каких пор английский стал языком троллей? Вы случайно Троллефобией не страдаете?

После того как запостил на devshed.com и никто не ответил решил скопировать сюда. Переводить было в лом и нет смысла т.к. тот кто не поймёт по английски вряд ли чем то сможет помочь в любом случае.

kjfoidios ()
Ответ на: комментарий от x3al

Огромное спасибо, глупая ошибка. Но проблема не решилась, с таким кодом

$resp = $ch->post(
	"https://graph.facebook.com/v2.1/{$facebookConf['page_id']}/feed",
	"message=This+is+a+test+message&access_token=".urlencode($facebookConf['page_token'])
);
echo "|{$resp}|";

Получаю

|{ "error": { "message": "(#200) The user hasn't authorized the application to perform this action", "type": "OAuthException", "code": 200 } }|

Как видно из one.php («&scope=manage_pages%2Cpublish_stream») it asks for manage_pages and publish_stream permissions. Isn't that enough? What permissions to add?

kjfoidios ()
Ответ на: комментарий от kjfoidios

В конфиг занеси username/password, курлом залогинься, зайди на page, и сделай post съимитировав браузерного юзера. Это facebook API то ещё говнецо, мои стены до сих пор помнят как я матерился когда пришлось однажды с ним поработать.

FutureBoy ()
Ответ на: комментарий от FutureBoy

kjfoidios есть шанс что вы мне поможете? похожая проблема с постингом на фэйсбуке

как вам можно написать?

georgyros ()
Вы не можете добавлять комментарии в эту тему. Тема перемещена в архив.