Facebook SDK v5 Post as Page on Wall

℡╲_俬逩灬. 提交于 2019-12-06 21:59:37

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