0

My requirement: Publish a link in a facebook fan page automatically when a form is submmited in my web application.

So I have the following code (copy/paste from the facebook suggestion )

        $appId = "...";
        $appSecret = "...";


        $fb = new Facebook\Facebook([
            'app_id' => $appId,
            'app_secret' => $appSecret,
        ]);

        $helper = $fb->getRedirectLoginHelper();

        try {
            $accessToken = $helper->getAccessToken();
        } catch (Facebook\Exceptions\FacebookResponseException $e) {
            // When Graph returns an error  
            echo 'Graph returned an error: ' . $e->getMessage();
            exit;
        } catch (Facebook\Exceptions\FacebookSDKException $e) {
            // When validation fails or other local issues  
            echo 'Facebook SDK returned an error: ' . $e->getMessage();
            exit;
        }

        if (!isset($accessToken)) {
            if ($helper->getError()) {
                header('HTTP/1.0 401 Unauthorized');
                echo "Error: " . $helper->getError() . "\n";
                echo "Error Code: " . $helper->getErrorCode() . "\n";
                echo "Error Reason: " . $helper->getErrorReason() . "\n";
                echo "Error Description: " . $helper->getErrorDescription() . "\n";
            } else {
                header('HTTP/1.0 400 Bad Request');
                echo 'Bad request';
            }
            exit;
        }

// Logged in  
        echo '<h3>Access Token</h3>';
        var_dump($accessToken->getValue());

// The OAuth 2.0 client handler helps us manage access tokens  
        $oAuth2Client = $fb->getOAuth2Client();

// Get the access token metadata from /debug_token  
        $tokenMetadata = $oAuth2Client->debugToken($accessToken);
        echo '<h3>Metadata</h3>';
        var_dump($tokenMetadata);

// Validation (these will throw FacebookSDKException's when they fail)  
        $tokenMetadata->validateAppId($config['app_id']);
// If you know the user ID this access token belongs to, you can validate it here  
// $tokenMetadata->validateUserId('123');  
        $tokenMetadata->validateExpiration();

        if (!$accessToken->isLongLived()) {
            // Exchanges a short-lived access token for a long-lived one  
            try {
                $accessToken = $oAuth2Client->getLongLivedAccessToken($accessToken);
            } catch (Facebook\Exceptions\FacebookSDKException $e) {
                echo "<p>Error getting long-lived access token: " . $helper->getMessage() . "</p>";
                exit;
            }
            echo '<h3>Long-lived</h3>';
            var_dump($accessToken->getValue());
        }

        $_SESSION['fb_access_token'] = (string) $accessToken;

But the output is Bad request. I tried with another appId but keeps the error.

Cristhian Boujon
  • 4,060
  • 13
  • 51
  • 90

3 Answers3

1

According to the Facebook docs:

The FacebookRedirectLoginHelper makes use of sessions to store a CSRF value. You need to make sure you have sessions enabled before invoking the getLoginUrl() method. This is usually done automatically in most web frameworks, but if you're not using a web framework you can add session_start(); to the top of your login.php & login-callback.php scripts. You can overwrite the default session handling - see extensibility points below.

Make sure there is a valid session, or use session_start() at the top of your scripts.

Donal.Lynch.Msc
  • 3,365
  • 12
  • 48
  • 78
0

That code is for login with facebook.

for post to a fanpage as an admin try something like:

$appid = 'XXX'; //your app id
$appsecret = 'XXX'; //your app secret
$pageId = 'XXX'; //your page id
use Facebook\FacebookRequest;
require  'your_path/Facebook/autoload.php';
$facebook = new Facebook(array(
  'appId' => $appid,
  'secret' => $appsecret,
  'cookie' => false,
));

$user = $facebook->getUser();

if ($user) {
  try {
    $page_info = $facebook->api("/$pageId?fields=access_token");
    if (!empty($page_info['access_token'])) {
      $args = array(
        'access_token' => $page_info['access_token'],
        'message' => 'www.test.com' /example
      );

      $postId = $facebook->api("/$pageId/feed", "post", $args);
    }
  } catch (FacebookApiException $e) {
    error_log($e);
    $user = null;
 }
}
Nico
  • 6,259
  • 4
  • 24
  • 40
0

I had a problem with access token to. I am not sure if it is the same problem.

My facebook login didn't work cause $accessToken = $helperget->AccessToken(); return on error (code 401).

To correct my code I needed to add at my AccessToken(), my callback url. (The same into my URI configuration in facebook developper website).

$accessToken = $helper->getAccessToken('www.domain.com/callback');
rollstuhlfahrer
  • 3,988
  • 9
  • 25
  • 38