首页 文章

以管理员身份发布到Facebook页面

提问于
浏览
12

我正在使用Cordova facebook插件在facebook页面上以admin身份发布 .

我拥有在Facebook页面上发布所需的所有权限 . 以下是我拥有的权限列表:

email, manage_pages, public_profile, publish_actions, publish_pages

我试图使用我的应用程序在页面上发布,但每次使用用户令牌而不是页面令牌发布 .

我试过的代码:

//提供用户管理的页面列表

$$('#apiTest_fb').on('click', function () {
                facebookConnectPlugin.api( "me/accounts", ["manage_pages"], 
                    function (response) {
                        console.log(JSON.stringify(response.data[0].name))  
                        //alert(JSON.stringify(response));
                        //fb_pages(response);                                   
                        alert("Manage Pages Permission granted");
                        },
                    function (response)
                    {
                        console.log(JSON.stringify(response))
                    }); 
            });

//用户页面的动态下拉列表

$$('#apiTest_fb_pages').on('click', function () {
                facebookConnectPlugin.api( "me/accounts", ["manage_pages"], 
                    function (response) {
                        console.log(JSON.stringify(response.data[0].name))  
                        //console.log(JSON.stringify(response));
                        //fb_pages(response);

                            var select = document.getElementById("selectPage");
                            for (var i = 0; i < response.data.length; i++) { 
                                var opt = response.data[i].name;
                                var page_val = response.data[i].id;
                                var el = document.createElement("option");
                                 el.textContent = opt;
                                 el.value = page_val;
                                 select.appendChild(el);
                            }

                        },
                    function (response)
                    {
                        console.log(JSON.stringify(response.data.name))
                    }); 
            });

//在选择传递获取页面access_token

$$('#selectPage').on("change", function(){
                var selectPage_id = $$(this).val();
                console.log(selectPage_id);
                window.localStorage.setItem("selectPage_id",selectPage_id);

            });

            $$('#FBActionPage').on('click', function () {           

                facebookConnectPlugin.api( window.localStorage.getItem("selectPage_id") + "?fields=access_token", ['publish_pages', 'manage_pages'], 
                    function (response) {
                        var pageToken = JSON.stringify(response.access_token);
                        //window.localStorage.setItem("fbtokenPage",JSON.stringify(response.access_token));                     
                        post_fbPage(pageToken);
                        },
                    function (response)
                    {
                        console.log(JSON.stringify(response))
                    }); 

            });

//贴到脸书

function post_fbPage(pageToken){

            console.log(pageToken); 

                facebookConnectPlugin.getLoginStatus( function(response) {
                        var url = '/'+ window.localStorage.getItem("selectPage_id") +'/feed?method=post&message=' + encodeURIComponent('Test') + '&link=' + 'impalz.co/JMR3a' + '&picture=' + 'www.impalz.com/images/affiliate-1.jpg' + '&caption=' + 'New Product' + '&description=' + 'we would love to know your feedback' +'&access_token=' + pageToken;
                        facebookConnectPlugin.api(
                            url,
                            ['publish_pages', 'manage_pages'],
                        function (response) { console.log(response.id)},
                        function (error) { console.error(error); }
                        );
                    });
            };

这是帖子的样子:

Screenshot

如何使用我的应用程序以管理员身份分享帖子?

编辑1:

我尝试删除 publish_actions 并在页面上发布时从用户标签中删除和添加应用程序,仍然使用用户令牌发布 . 我调试了access_token和以下内容:

Screen_Shot

编辑2:

我尝试将我的令牌传递给facebook PHP SDK并完美地贴在我的墙上 . 如何使用PHP SDK在Facebook页面上发布?

我已经尝试使用PHP SDK传递 page_tokenpage_id 在fb页面上发布但它无法正常工作 .

代码我试图在用户Facebook墙上发布:

require_once('src/Facebook/autoload.php');

$token = $_POST["token"]; // Used AJAX to post data on server

$fb = new Facebook\Facebook([
  'app_id' => '{ID}',
  'app_secret' => '{SECRET}',
  'default_graph_version' => 'v2.2',
  'default_access_token' => $token, 
  ]);

$linkData = [
  'link' => 'http://www.example.com',
  'message' => 'User provided message',
  ];

try {
  // Returns a `Facebook\FacebookResponse` object
    $response = $fb->post('/me/feed', $linkData, $token);       

} catch(Facebook\Exceptions\FacebookResponseException $e) {
  echo 'Graph returned an error: ' . $e->getMessage();
  exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
  echo 'Facebook SDK returned an error: ' . $e->getMessage();
  exit;
}

$graphNode = $response->getGraphNode();

echo 'Posted with id: ' . $graphNode['id'];

1 回答

  • 2

    你可以拥有一个永不过期的fan page令牌,这将解决你的问题 .

    按照简单的步骤:

    • 获取admin 's(i.e. your' s)扩展令牌(2个月有效期) . 通过链接获取 long-lived token .

    Extending tokens

    • 使用此令牌获取任何页面的永不过期的访问令牌

    facebook-> API( “/ PAGE_ID字段=的access_token?”);

    (您可以使用Facebook's Debug Tool来检查令牌的有效性) .

    以管理员身份发布很容易,但发布为Page需要更多的工作 . 要以页面形式发布,我们需要以下权限:

    publish_stream
    manage_pages
    

    我们需要 manage_pages 权限来获取页面访问令牌,以便我们可以代表它发布 . 这就是我们这样做的方式:

    <?php
    // This code is just a snippet of the example.php script 
    // from the PHP-SDK <https://github.com/facebook/facebook-php-sdk/blob/master/examples/example.php>
    require '../src/facebook.php';
    
    // Create our Application instance (replace this with your appId and secret).
    $facebook = new Facebook(array(
      'appId'  => 'app_id',
      'secret' => 'app_secret',
    ));
    
    // Get User ID
    $user = $facebook->getUser();
    
    if ($user) {
      try {
        $page_id = 'page_id';
        $page_info = $facebook->api("/$page_id?fields=access_token");
        if( !empty($page_info['access_token']) ) {
            $args = array(
                'access_token'  => $page_info['access_token'],
                'message'       => "I'm a Page!"
            );
            $post_id = $facebook->api("/$page_id/feed","post",$args);
        } else {
            $permissions = $facebook->api("/me/permissions");
            if( !array_key_exists('publish_stream', $permissions['data'][0]) || 
                !array_key_exists('manage_pages', $permissions['data'][0])) {
                // We don't have one of the permissions
                // Alert the admin or ask for the permission!
                header( "Location: " . $facebook->getLoginUrl(array("scope" => "publish_stream, manage_pages")) );
            }
    
        }
      } catch (FacebookApiException $e) {
        error_log($e);
        $user = null;
      }
    }
    
    // Login or logout url will be needed depending on current user state.
    if ($user) {
      $logoutUrl = $facebook->getLogoutUrl();
    } else {
      $loginUrl = $facebook->getLoginUrl(array('scope'=>'manage_pages,publish_stream'));
    }
    
    // ... rest of your code
    ?>
    

    Using the Javascript-SDK Achieving the same with only client-side technology:

    function postToPage() {
        var page_id = '000000000000';
        FB.api('/' + page_id, {fields: 'access_token'}, function(resp) {
            if(resp.access_token) {
                FB.api('/' + page_id + '/feed',
                    'post',
                    { message: "I'm a Page!", access_token: resp.access_token }
                    ,function(response) {
                        console.log(response);
                });
            }
        });
    }
    

    Using /me/accounts connection

    如果您正在构建某种类型的CMS,其中管理员想要选择其中一个页面来更新其状态,那么使用/ me / accounts更好地列出页面并在一次API调用中保存它们的access_token .

    $page_id = "XXXXXXXXX";
    $page_access_token = "";
    $result = $facebook->api("/me/accounts");
    foreach($result["data"] as $page) {
        if($page["id"] == $page_id) {
            $page_access_token = $page["access_token"];
            break;
        }
    }
    if( !empty($page_access_token) ) {
        $args = array(
            'access_token'  => $page_access_token,
            'message'       => "I'm a Page!"
        );
        $post_id = $facebook->api("/$page_id/feed","post",$args);
        // sucess...
    } else {
        // couldn't find the page!
    }
    

    始终与您的页面粉丝进行沟通,因为页面不是管理员,粉丝知道(并信任)您的页面(产品),但不是必需的!

相关问题