2

I have defined an access token and have the required permissions to 'like' a facebook page, but firebug keeps giving me the error in the title. Please don't mark this post as duplicate, because I've looked on the posts regarding the problem and I couldn't find an answer that would fit my particular case in any way. I can't understand why or how should I solve it. My code is the following:

utils.php

    <?php
require_once('sdk/src/facebook.php');
require_once("AppInfo.php");
/**
 * @return the value at $index in $array or $default if $index is not set.
 */
function idx(array $array, $key, $default = null) {
  return array_key_exists($key, $array) ? $array[$key] : $default;
}

function he($str) {
  return htmlentities($str, ENT_QUOTES, "UTF-8");
}
$facebook = new Facebook(array(
'appId'  => AppInfo::appID(),
'secret' => AppInfo::appSecret(),
'sharedSession' => true,
'trustForwarded' => true,
'file_upload' =>true
));
$user_id = $facebook->getUser();
if($user_id)
{
  $logoutUrl =$facebook->getLogoutUrl();
}
  else
  {
      $loginUrl=$facebook->getLoginUrl();
  }
if ($user_id) {
try {
  // Fetch the viewer's basic information
  $user_profile = $facebook->api('/me');
} catch (FacebookApiException $e) {
  // If the call fails we check if we still have a user. The user will be
  // cleared if the error is because of an invalid accesstoken
  if (!$facebook->getUser()) {
    header('Location: '. AppInfo::getUrl($_SERVER['REQUEST_URI']));
    exit();
  }
}
}
?>

likes.php

      <?php

require_once("sdk/src/facebook.php"); 
require_once("utils.php");
require_once("AppInfo.php");
$permissions = $facebook->api('/me/permissions    ');
if( array_key_exists('publish_actions', $permissions['data'][0]) ) {
    // Permission is granted!
    // Do the related task
    //$post_id = $facebook->api('/me/feed', 'post', array('message'=>'Hello World!'));
} else {
    // We don't have the permission
    // Alert the user or ask for the permission!
    header( "Location: " . $facebook->getLoginUrl(array("scope" => "publish_actions")) );
}
?>
    <!DOCTYPE html>
    <html xmlns:fb="http://ogp.me/ns/fb#">
    <head>

      <style type="text/css">
      li{ 
        vertical-align: middle;
        padding-top: 1em; 
      }
    </style>
    <div id="fb-root"></div>
      <script type="text/javascript" src="/javascript/jquery-1.7.1.min.js"></script>
     <script type="text/javascript">

      (function(d, debug){
         var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
         if (d.getElementById(id)) {return;}
         js = d.createElement('script'); js.id = id; js.async = true;
         js.src = "//connect.facebook.net/en_US/all" + (debug ? "/debug" : "") + ".js";
         ref.parentNode.insertBefore(js, ref);
       }(document, false)); //loads javascript-sdk

        $(function() {
          // Set up so we handle click on the buttons
          $('#like_but').click(function(){
          FB.api(
      'me/og.likes',
      'post',
      {
        object: "http://facebook.com/216730015024772"
      },
      function(response) {
        alert(response);
      });});}); // they are closed properly, don't bother checking it. (!) Should like the 'object'
     </script>
    </head>
    <body> 
    <div style="position:fixed; display:block">
      <input type="button" value="Like" id="like_but"/>
 </div>    
</body>
</html>

Does anyone have any idea why does the error appear or how can I solve this? Any hint would be appreciated.

Note: the user logs in from another index.php, but I won't post it here, because there is no problem with it, and the access token is still gathered in utils.php. Also when checking if permissions are granted in "likes.php", it works fine.

Julian H. Lam
  • 25,501
  • 13
  • 46
  • 73
MihaiB
  • 129
  • 1
  • 4
  • 17

1 Answers1

8

Assuming that the access_token you received from Facebook is indeed valid... it looks like your implementation of the Facebook javascript SDK isn't complete.

You've included the library loader, but you don't have an FB.init(); section to initialize the library. I see no reference to any appId in the second code block, so there's way for Facebook to know what app your code is in reference to.

Please refer to the following documentation from Facebook.

Specifically, this may solve your problem:

window.fbAsyncInit = function() {
    // init the FB JS SDK
    FB.init({
        appId      : 'YOUR_APP_ID', // App ID from the App Dashboard
        channelUrl : '//WWW.YOUR_DOMAIN.COM/channel.html', // Channel File for x-domain communication
        status     : true, // check the login status upon init?
        cookie     : true, // set sessions cookies to allow your server to access the session?
        xfbml      : true  // parse XFBML tags on this page?
    });

    // Additional initialization code such as adding Event Listeners goes here
    document.getElementById('like_but').addEventListener('click', function() {
        FB.api('me/og.likes', 'post', {
            object: "http://facebook.com/216730015024772"
        }, function(response) {
            console.log(response);
        });
    }, false);
};

(function(d, debug){
    var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
    if (d.getElementById(id)) {return;}
    js = d.createElement('script'); js.id = id; js.async = true;
    js.src = "//connect.facebook.net/en_US/all" + (debug ? "/debug" : "") + ".js";
    ref.parentNode.insertBefore(js, ref);
}(document, /*debug*/ false));
Julian H. Lam
  • 25,501
  • 13
  • 46
  • 73
  • I will edit the question, I forgot to specify. The fb.init is called in another .php file, and everything is initialized. "likes.php" is the popped up from that page – Mihai Bujanca Mar 17 '13 at 20:40
  • You are mixing the roles of javascript and php. It doesn't matter if the `FB` object was initialized in *another* .php file. You're in the current .php file, and your browser's DOM has reset, meaning you'll have to reinitialize the FB object. – Julian H. Lam Mar 17 '13 at 20:42
  • I'm quite new to this. Ok, but then, if I initialize it in my utils.php, will this remain valid for both? – Mihai Bujanca Mar 17 '13 at 20:44
  • The initialization of the PHP SDK does not mean the JS SDK is ready to go. On any page that you require Facebook functionality via javascript, you'll need the `FB.init` block. Merge what I've pasted into `likes.php`, and as long as the user is authenticated, it should work. – Julian H. Lam Mar 17 '13 at 20:48
  • 2
    The PHP and JS SDKs are separate entities. Both are a means to connect a Facebook user to your application, but they **do not** talk to one another. Treat them separately. – Julian H. Lam Mar 17 '13 at 20:48
  • Response: {"error":{"message":"(#100) Like actions are not yet supported against objects of this type.","type":"OAuthException","code":100}}; Do you have any idea why or how to deal with this? (the object above is a facebook page-https://www.facebook.com/Jacksavoretti) – Mihai Bujanca Mar 17 '13 at 22:04
  • It looks like you cannot "like" a facebook page using an open graph action. Try using the Graph API instead. – Julian H. Lam Mar 17 '13 at 22:07
  • How can I do this using js? I got the js from this link: https://developers.facebook.com/docs/reference/opengraph/action-type/og.likes How can i do this with graph api **in** javascript code? – Mihai Bujanca Mar 17 '13 at 22:20
  • Isn't actually what I am doing a graph API call? – Mihai Bujanca Mar 17 '13 at 23:06
  • You're probably right. However, it looks like you are unable to push facebook pages through the *Open Graph* API. Off-hand, I don't know if it is possible to have a user "like" a page outside of Facebook. You may have to ask the user to visit the page itself. I may be wrong, so feel free to ask this question as a new question, as it does not relate to this current question. You'll get a fresh set of eyes, too :) – Julian H. Lam Mar 18 '13 at 00:41
  • Just that this might help future visitors, stackoverflow.com/a/11126712/1786117 states that "To like Facebook Pages or websites that do not integrate with Facebook Authentication, developers should continue to use the Like button social plugin." Thank you for your help. Unfortunately that leads me to a stuck point, what I wanted to do was to allow the user like a couple of pages at the same time, given some checkboxes – Mihai Bujanca Mar 18 '13 at 04:56
  • I will award the bounty as soon as stackoverflow lets me – Mihai Bujanca Mar 18 '13 at 08:55
  • Hello again - I figured that was the case. Facebook strives to provide only organic likes (initiated by users on the page itself), and does not allow automated liking simply because it would be too easy for a malicious app to have all of its app visitors like anything and everything. With no way to control it, Facebook has to limit it that way. – Julian H. Lam Mar 18 '13 at 12:20