5

如何使用 facebook php sdk v4 和 graph api 2.x 作为页面管理员用户在 Facebook 页面墙上发布帖子?

我花了很多时间,但大多数文章都是旧的(旧 Facebook PHP SDK 的示例)并且有点混乱

我已经想出了以下步骤

第 1 步:将应用程序重定向到 Facebook 用于登录管理员
第 2 步:获取用户访问令牌(短期)
第 3 步:通过交换短期令牌获得用户访问令牌(长期)
第 4 步:获取页面访问令牌

您能否解释一下我需要为上述步骤调用哪些 Facebook PHP SDK 功能,或者您可以给我一些代码示例的 url?

或者

如果我错了,请纠正我谢谢提前

========================
注意:

  • 我已经为 app_id 和 app_secret 创建了应用程序
  • 我创建了 Facebook 页面
  • 我正在使用 Facebook PHP SDK 4
  • Facebook PHP SDK 4 使用图形 API 2.x(我假设)
4

2 回答 2

2

我有一个教程,解释了如何使用 PHP SDK v4.0.x 和 Graph API vx实现发布到页面

本质上,您可以通过执行以下操作来获取页面访问令牌:

// get page access token
$access_token = (new FacebookRequest( $session, 'GET', '/' . $page_id,  array( 'fields' => 'access_token' ) ))
    ->execute()->getGraphObject()->asArray();

// save access token in variable for later use  
$access_token = $access_token['access_token'];

然后,您可以使用我们上面获得的访问令牌进行第二次 API 调用,以将内容发布到给定页面:

// post to page
$page_post = (new FacebookRequest( $session, 'POST', '/'. $page_id .'/feed', array(
    'access_token' => $access_token,
    'name' => 'Facebook API: Posting As A Page using Graph API v2.x and PHP SDK 4.0.x',
    'link' => 'https://www.webniraj.com/2014/08/23/facebook-api-posting-as-a-page-using-graph-api-v2-x-and-php-sdk-4-0-x/',
    'caption' => 'The Facebook API lets you post to Pages you administrate via the API. This tutorial shows you how to achieve this using the Facebook PHP SDK v4.0.x and Graph API 2.x.',
    'message' => 'Check out my new blog post!',
  ) ))->execute()->getGraphObject()->asArray();

// return post_id
print_r( $page_post );
于 2014-08-23T13:19:12.277 回答
0

我找到了另一种获取永不过期令牌的方法:

    //get your access token for the app that you will use in 
    //https://developers.facebook.com/tools/explorer/

    //exchange it for long-term access token

    $accessToken='xxxxxxxxGet it above';
    $session = new FacebookSession($accessToken);
    $response = (new FacebookRequest($session, 'POST', '/oauth/access_token', array(
        'grant_type' => 'fb_exchange_token',
        'client_id' => 'the client id for the app',
        'client_secret' => 'the client secret for the app',
        'fb_exchange_token' => $accessToken)))->execute()->getGraphObject()->asArray();


    $LongTermUserAccessToken=$response['access_token'];


    $session = new FacebookSession($LongTermUserAccessToken);

    //get My User ID if you don't know 

    $response = (new FacebookRequest( $session, 'GET', '/me' ,  array( 'fields' => 'id' ) ))
        ->execute()->getGraphObject()->asArray();
    $meId=$response['id'];

    //get Tokes for all my pages the page that you are usig will have a never expire token
    //you can prove on https://developers.facebook.com/tools/debug/

    $response = (new FacebookRequest( $session, 'GET', '/'.$meId.'/accounts' ))
        ->execute()->getGraphObject()->asArray();

    var_dump($response);die;
于 2014-10-23T16:28:49.563 回答