post to the fan page's wall as page from anoth

2019-04-13 19:51发布

I know that there are lot's of questons on this, but all seem to be needing a user to be logged in... I have been using code snippets from all possible tutorials, but none seem to work.

Here is the scenario: I have a photo community running on PHP and I have a fan page on Facebook. When an image on the main site collects a certain amount of votes a function is triggered to post the image link to the Facebook wall. The link (post) is posted as a page and not as admin. Admin of course will not be online... Is this even possible to do these days? I have the latest PHP SDK and this is the function that I need to get working in stand alone mode before pluggin' into the main site.

OK. This code works perfectly if I am logged into the Facebook, but if I am not - it will not post... The App has all necessary and unnecessary :) permissions to interact with my page on my (admin) behalf. Any ideas will be appreciated.

    <?php
//facebook application
$fbconfig['appid' ]     = "1848740815xxxxx";
$fbconfig['secret']     = "a5aa62bb3a8ddcb98d5d9dbe4a3xxxxx";
$fbconfig['pageid']     = "121409594622865";

$user  =   null; //facebook user uid
try{
    include_once "facebook.php";
}
catch(Exception $o){
    error_log($o);
}
// Create our Application instance.
$facebook = new Facebook(array(
  'appId'  => $fbconfig['appid'],
  'secret' => $fbconfig['secret']
));
//Facebook Authentication part
$user       = $facebook->getUser();
$loginUrl   = $facebook->getLoginUrl(
        array(
            'scope'         => 'offline_access,publish_stream'
            )
        );
$logoutUrl  = $facebook->getLogoutUrl();
$pageid = $fbconfig['pageid'];

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' => 'This is a test feed message', 
            'link'    => 'http://www.fotodvor.com',
            'picture' => 'http://www.fotodvor.com/data/media/15/1319971991.jpg',
            'name'    => 'Test Picture',
            'description'=> 'Description of the test picture!'
        );
        $post_id = $facebook->api("/$page_id/feed","post",$args);
    }
  } catch (FacebookApiException $e) {
    error_log($e);
    $user = null;
  }
}
?>

Thanks in advance

3条回答
Bombasti
2楼-- · 2019-04-13 20:15

here is a modified script with explanations adjusted for the changes in the API

<?php
//facebook application
$fbconfig['userid']    = "5332534xx";
$fbconfig['appid' ]    = "184874081548xxx";
$fbconfig['secret']    = "a5aa62bb3a8xxxb98d5d9dbe4a368xxx";
$fbconfig['pageid']    = "121409594622xxx";

$fbconfig['token1']     = "AAACoJFn1eLABAKpL9W0nZBrw0e3zzdSNVsTg6FWDMhSnOUeinjid6yAQ2z9JDxxxxxxc1hMHBC3GG18KZBwppGDehWMEwLe56wagZDZD";  // step 1 - returned by loggin in.
$fbconfig['token2']     = "AAACoJFn1eLABAC2Q8OLnqxjUSKzdn9CzaXhy8nsG61vzp2ufePr5iwHZA7TM7Ibxxxxxxyf868O04FeBxMrIo0RCumrNaB78hZAp2uRrbVlGVPXP"; // step 3 - this is a page access token as page
$fbconfig['my_ulr']     = 'http://'.$_SERVER['SERVER_NAME'];

include_once "facebook.php";

// Create our Application instance.
$facebook = new Facebook(array(
  'appId'  => $fbconfig['appid'],
  'secret' => $fbconfig['secret'],
));

// 1. we need to get a user access_token first, (old approach with offline_access forces the tokens received not to expire (good examples here - http://developers.facebook.com/docs/authentication2/ and http://www.howtobe.pro/tag/graph-api)
// run the file and see step 1 instructions.

//offline_access has been deprecated in May 2012 and therefore excluded from the request below
$token_url1 = "https://www.facebook.com/dialog/oauth?"."client_id=".$fbconfig['appid']."&redirect_uri=".urlencode($fbconfig['my_ulr'])."&scope=manage_pages,publish_stream&response_type=token";

echo "<h2>This little working example should give you a working non expiring token to use in your PHP script to enable it to post to your Facebook page as a page and not as a user</h2><br>";
echo "1 - Click on the link below (this redirects to uri with token attached). Log in as admin of the page you are trying to post to. Then copy the token you will get in the address bar to be used in the script in step 2.<br>";
echo "<a href='".$token_url1."' target='_blank'>$token_url1</a>";

//2. then paste the token you received into "step 1" variable in the config section above. Run this script again when logged in to receive all info.
$token_url2 = "https://graph.facebook.com/me?access_token=".$fbconfig['token1'];
$me = json_decode(file_get_contents($token_url2), true);

//echo "<hr><br>this URL gives you all pages that you as admin have access to, but these are NOT what we need to post to the fan page as PAGE so this is just for the heck of it...<br>";
//echo "<a href='".$token_url2."' target='_blank'>$token_url2</a>";
//echo "<hr>this is a raw server reply<br>";
//echo d($me['id'])."<hr>";

//new changes to API - https://developers.facebook.com/roadmap/offline-access-removal/#extend_token
$new_token_url2 = "https://graph.facebook.com/oauth/access_token?client_id=".$fbconfig['appid']."&client_secret=".$fbconfig['secret']."&grant_type=fb_exchange_token&fb_exchange_token=".$fbconfig['token1'];
$new_token2 = file_get_contents($new_token_url2);
$vars = explode('&', $new_token2);
//d($vars);

echo "2. We now obtain a long lasting token (based on <a href='https://developers.facebook.com/roadmap/offline-access-removal/#extend_token' target='_blank'>this</a>)
<br><br>We send the request<br>'".$new_token_url2."'<br><br>and the reply is:<br>'".$new_token2."'<br><br>";

//http://developers.facebook.com/tools/explorer?method=GET&path=533253476&accounts&access_token=AAACoJFn1eLABAFZBftV0vtlBiHKA7ZAIrukrriyp2coWSavj3L4CbfJ9r3WY76IPi7pwUgt3wsubaI4iBbsr663PrbNyaLdZAhLxneOLAZDZD

echo"So now open this page <a href='http://developers.facebook.com/tools/explorer' target='_blank'>http://developers.facebook.com/tools/explorer</a>, 
then put the token above to put into the 'Access Token: ' field and press enter... You will need to press 'accounts' link to the right from the response window.
<br>you will see another response and copy your page access token from there. Automating this task into one query did not work... I tried many times.. the token returned IS NOT THE SAME as you would get following the instructions step by step...
This approach does not work - <br>";
echo "http://developers.facebook.com/tools/explorer?method=GET&path=".$me['id']."%2Faccounts&".$vars[0]."<BR><BR><BR>";
echo "Please check it here <a href='http://developers.facebook.com/tools/debug' target='_blank'>https://developers.facebook.com/tools/debug</a> and make sure it never expires...";


$pageid = $fbconfig['pageid'];
try {

//Step 3. Run this script WHEN LOGGED IN to and paste the resulting token into step 3 variable above to check the functionality

/*     $page_info = $facebook->api("/$pageid?fields=access_token&".$new_token2);  //wrong approach to use this straight. THIS is the access token is that we need. BUT this will work only if user is logged in. so 
    echo "<hr>this is a page_info breakdown";
    d($page_info);
    echo "and the access token you needs to paste into fbconfig['token2'] variable is this:<br>";
    echo $page_info['access_token']; */

    $args = array(
            'access_token'  => $fbconfig['token2'], //do not attempt to plug the $page_info['access_token'] here... it will be empty once you log off Facebook
            'message' => 'This is a test feed message', 
            'link'    => 'http://www.test.com',
            'picture' => 'https://www.google.com/intl/en_com/images/srpr/logo3w.png',
            'name'    => 'Test Picture',
            'description'=> 'Description of the test picture!'
        );

         //uncomment this once you are ready to post and you can see all the access token in the last step. Then comment out all echo and d()'s to make the script silent...            
        //$post_id = $facebook->api("/$pageid/feed","post",$args);
        echo "<hr>This will show once the message is posted - post_id is: <br>";
        d($post_id); 
  } catch (FacebookApiException $e) {
    error_log($e);
  }

function d($d){
    echo '<pre>';
    print_r($d);
    echo '</pre>';
}
?>
查看更多
叛逆
3楼-- · 2019-04-13 20:27

You should be using the page access token if i'm understanding what you're trying to do correctly - this is a token which allows your app to act as the page, not as one of the admins. This is accessible at the /me/accounts endpoint when you have a user access token with manage_pages permission - if you use that access token to post to /{page id}/feed (or photos, etc) it'll appear as the page

查看更多
仙女界的扛把子
4楼-- · 2019-04-13 20:38

I think I have found the answer. After a long time of testing here is the solution: Treat this as a little sample/guide for those who are new to this. The code and output has all necessary info:

<?php
//facebook application
$fbconfig['appid' ]    = "184874081XXXXXX";
$fbconfig['secret']    = "a5aa62bb3a8ddcb98d5d9dbe4aXXXXXX";
$fbconfig['pageid']    = "121409594XXXXXX";
$fbconfig['token1']     = "AAACoJFn1eLABAHn92JsWIHZCESQWXmkXZBCedXXXXXXcyUG5vrCYZBXcgsNHN0IUvBj0Sec9vOxVsUgtMHflXXF2cbOF1oZD";  // step 1 - returned by loggin in.
$fbconfig['token2']     = "AAACoJFn1eLABAAUAPthH5DaZCmasZCh5DGGSnZXXXXXXSDh8v1WYYUEWJYuFdua9E5EfJ63c03lfwXrVJbP4VQj35aVcztFgKRYZAheHPNfDeLfbkPys"; // step 3 - this is a page access token as page
$fbconfig['my_ulr']     = 'http://'.$_SERVER['SERVER_NAME'];

include_once "facebook.php";

// Create our Application instance.
$facebook = new Facebook(array(
  'appId'  => $fbconfig['appid'],
  'secret' => $fbconfig['secret'],
));

// 1. we need to get a user access_token first, offline_access forces the tokens received not to expire (good examples here - http://developers.facebook.com/docs/authentication2/ and http://www.howtobe.pro/tag/graph-api)
//run the file and see step 1 instructions.
$token_url1 = "https://www.facebook.com/dialog/oauth?"."client_id=".$fbconfig['appid']."&redirect_uri=".urlencode($fbconfig['my_ulr'])."&scope=manage_pages,offline_access,publish_stream&response_type=token";
echo "1 - this redirects to uri with token attached. Copy and paste this line into your browser and log in as admin of the page you are trying to post to. Make sure you change redirect_uri to your own. Then copy the token you will get in the address bar to be used in the script in step 2.<br>";
echo $token_url1;


//2. then paste the token you received into "step 1" variable in the config section above. Run this script again when logged in to receive all info.
$token_url2 = "https://graph.facebook.com/me/accounts?access_token=".$fbconfig['token1'];
$app_token2 = file_get_contents($token_url2);
echo "<hr><br>2 - this URL gives you all pages that you as admin have access to, but these are NOT what we need to post to the fan page as PAGE<br>";
echo $token_url2;
echo "<hr>2 - this is a raw server reply<br>";
d($app_token2);


$pageid = $fbconfig['pageid'];
try {

  //Step 3. Run this script WHEN LOGGED IN to and paste the resulting token into step 3 variable above
    $page_info = $facebook->api("/$pageid?fields=access_token");  //wrong approach to use this straight. THIS is the access token is that we need. BUT this will work only if user is logged in. so 
    echo "this is a page_info breakdown";
    d($page_info);
    echo "and the access token you needs to paste into fbconfig['token2'] variable is this:<br>";
    echo $page_info['access_token'];

    $args = array(
            'access_token'  => $fbconfig['token2'], //do not attempt to plug the $page_info['access_token'] here... it will be empty once you log off Facebook
            'message' => 'This is a test feed message', 
            'link'    => 'http://www.test.com',
            'picture' => 'https://www.google.com/intl/en_com/images/srpr/logo3w.png',
            'name'    => 'Test Picture',
            'description'=> 'Description of the test picture!'
        );
         //uncomment this once you are ready to post and you can see all the access token in the last step. Then comment out all echo and d()'s to make the script silent...            
        //$post_id = $facebook->api("/$pageid/feed","post",$args);
        echo "<hr>This will show once the message is posted - post_id is: <br>";
        d($post_id); 
  } catch (FacebookApiException $e) {
    error_log($e);
  }

function d($d){
    echo '<pre>';
    print_r($d);
    echo '</pre>';
}
?>
查看更多
登录 后发表回答