Facebook SDK v5 Post as Page on Wall

心已入冬 提交于 2019-12-23 02:58:04

问题


I have the below snippet and it works and posts to a Facebook page as my own user account on Facebook.

The values FACEBOOK_* are defined earlier in the codebase.

// SDK Version 5.0
$fb = new Facebook\Facebook([
    'app_id' => FACEBOOK_APP_ID,
    'app_secret' => FACEBOOK_APP_SECRET,
    'default_graph_version' => 'v2.4',
]);

// Returns a `Facebook\FacebookResponse` object
$response = $fb->post('/'.FACEBOOK_PAGE_ID.'/feed', $postData, FACEBOOK_ACCESS_TOKEN);

$postId = $response->getGraphNode();

Now my question is how can I get it to post as the actual page and not my account which is the admin of the page.

I've had a look at the SDK documentation and I've been going around in circles, there are many examples of v4 but as it's deprecated I'm trying to use v5 and just can't seem to figure it out, any links to post attribution or impersonation I find are dead links in v5 of the SDK.

From what I can see I need to make a call to /{user-id}/accounts to get an access token for the page from my user, https://developers.facebook.com/docs/facebook-login/access-tokens#pagetokens

But to get a {user-id} I have to query the user, with something like the below example from the SDK documentation:

// Make sure to load the Facebook SDK for PHP via composer or manually
use Facebook\FacebookRequest;
use Facebook\GraphUser;
use Facebook\FacebookRequestException;

if($session) {
try {
    $user_profile = (new FacebookRequest(
        $session, 'GET', '/me'
    ))->execute()->getGraphObject(GraphUser::className());
    echo "Name: " . $user_profile->getName();
} catch(FacebookRequestException $e) {
    echo "Exception occured, code: " . $e->getCode();
    echo " with message: " . $e->getMessage();
} 

The issue here is that I have no idea how to get a session which I need to get the user data for which gives me the access token to allow me pass the access token into my code snippet above that works, that's if I understand it all correctly!?

Any help greatly appreciated!


回答1:


I work with classes, so I adapted my code to your examples above. Tested and working code.

After getting your user access token using the method you use (see the guide here), we have to obtain a long-lived access token. Add this to your code :

session_start();
$helper = $fb->getRedirectLoginHelper();

try {
  $accessToken = $helper->getAccessToken();
} catch(Facebook\Exceptions\FacebookSDKException $e) {
  // There was an error communicating with Graph
  echo $e->getMessage();
  exit;
}

if (isset($accessToken)) {

    $client = $fb->getOAuth2Client();

    try {
      $accessToken = $client->getLongLivedAccessToken($accessToken);
    } catch(Facebook\Exceptions\FacebookSDKException $e) {
      echo $e->getMessage();
      exit;
    }


  $response = $fb->get('/me/accounts', (string) $accessToken);

    foreach ($response->getDecodedBody() as $allPages) {
        foreach ($allPages as $page ) {               

            if (isset($page['id']) && $page['id'] == $pageId) { // Suppose you save it as this variable
                $appAccessToken = (string) $page['access_token'];
                break;
            }
        }
    }

    $response = $fb->post(
        '/'.$pageId.'/feed',
        array(
            "message" => "Message",
            "link" => "http://www.example.com",
            "picture" => "http://www.example.net/images/example.png",
            "name" => "Title",
            "caption" => "www.example.com",
            "description" => "Description example"
        ),
        $appAccessToken
    );

    // Success
    $postId = $response->getGraphNode();
    echo $postId;

} elseif ($helper->getError()) {
  var_dump($helper->getError());
  var_dump($helper->getErrorCode());
  var_dump($helper->getErrorReason());
  var_dump($helper->getErrorDescription());
  exit;
}

Explanations : You have to know which pages you are administrator :

$response = $fb->get('/me/accounts', (string) $accessToken);

Then search the table to retrieve the access token of the page that interests us (I have chosen to take the id of the page referenced).

Finally, simply run the post function provided by the SDK :

$response = $fb->post(
    '/'.$pageId.'/feed',
    array(
        "message" => "Message",
        "link" => "http://www.example.com",
        "picture" => "http://www.example.net/images/example.png",
        "name" => "Title",
        "caption" => "www.example.com",
        "description" => "Description example"
    ),
    $appAccessToken
);


来源:https://stackoverflow.com/questions/32328734/facebook-sdk-v5-post-as-page-on-wall

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!