Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Post to facebook page as Admin

I am using Cordova facebook plugin to post on facebook page as admin.

I am having all permissions which are required to post on facebook page. Following is the list of permission I am having:

email, manage_pages, public_profile, publish_actions, publish_pages

I am trying to post on page using my app but everytime it post with user token and not with page token.

Code I tried:

//Gives list of pages user manage

$$('#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))
                    }); 
            });

//Dynamic dropdown of user pages

$$('#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))
                    }); 
            });

//on select pass get page 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))
                    }); 

            });

//post to face book

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); }
                        );
                    });
            };

This is how post look like:

Screenshot

How can I share post as admin using my app?

EDIT 1:

I tried removing publish_actions and removing and adding app from user tabs while posting on page, still it post with user token. I debugged my access_token and following content I got:

Screen_Shot

EDIT 2:

I tried Passing my token to facebook PHP SDK and its posting on my wall perfectly. How can I use PHP SDK to post on facebook Page?

I've already tried passing page_token and page_id to post on fb page using PHP SDK but it ain't working.

Code I tried to post on User Facebook Wall:

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'];
like image 803
Nehil Mistry Avatar asked Aug 28 '15 10:08

Nehil Mistry


1 Answers

You can have a never expiring token for your fan page, that will solve your problem i guess.

Follow the simple steps:

  • Get the admin's(i.e. your's) extended token (2 months validity). Go though the link to get the long-lived token.

Extending tokens

  • Get the never expiring access token for any page using this token

    facebook->api("/PAGE_ID?fields=access_token");

(You can use Facebook's Debug Tool to check the validity of the token).

Posting as Admin is easy but posting as Page requires more work from your side. To post as Page we need the following permissions:

publish_stream
manage_pages

We need the manage_pages permission to get the page access token so we can post on its behalf. And this is how we do it:

<?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

If you are building some sort of a CMS where the admin wants to select one of the pages to update its status, then using the /me/accounts is better you can list the pages and save their access_token in one API call.

$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!
}

Always communicate with your page fans as Page not as Admin, fans do know (and trust) your page (product) but not necessary you!

like image 155
Navnish Bhardwaj Avatar answered Oct 08 '22 14:10

Navnish Bhardwaj