• PHP Help PHP Coding
  • [RESOLVED] Trying to use Facebook PHP SDK 5.x, $helper->getAccessToken() returning null

I'm trying to code a script that'll post to a Facebook page. So to that end, I was able to cobble together a script that relies on Facebook's 5.x SDK, which I installed via composer. You'll notice in the below code that it doesn't have app id, app secret, nor page id. In the actual script, it does have the needed values, and it's already activated via Facebook dev center. When I execute the script, it simply fails without throwing up an error, in spite of added code to catch exceptions. I've searched Google and PHPBuilder to see if others ran into the same issue, found a few posts on it on Stack Overflow, but those posters also ran into dead-ends. So I'm hoping one of you have an eagle eye and can see where I'm going wrong. This is actually my first time working with Facebook's SDK.

<?
	error_reporting(E_ALL);
	ini_set('display_errors', '1');

// Pass session data over.
session_start();

// Include the required dependencies.
require_once('../../../vendor/autoload.php');
echo 'Dependencies loaded.<br>';

// Initialize the Facebook PHP SDK v5.
$fb = new Facebook\Facebook([
  'app_id'                => '{app_id}',
  'app_secret'            => '{app_secret}',
  'default_graph_version' => 'v2.3',
]);

echo 'Facebook SDK initialized.<br>';

$pageId = '{page_id}';  # DeafScoop ID

echo 'Attempting to login...<br>';
$helper = $fb->getRedirectLoginHelper();
echo 'LoginHelper loaded, now getting Access Token...<br>';

try {
  $accessToken = $helper->getAccessToken();
  echo 'Done, moving on...<br>';
} catch(Facebook\Exceptions\FacebookSDKException $e) {
  // There was an error communicating with Graph
  echo 'There was an error.<br>';
  echo $e->getMessage();
  exit();
}

if (isset($accessToken)) {

	echo 'Attempting to exchange for long term token...<br>';
	$client = $fb->getOAuth2Client();

	try {
	  $accessToken = $client->getLongLivedAccessToken($accessToken);
	} catch(Facebook\Exceptions\FacebookSDKException $e) {
	  echo 'There was an error.<br>';
	  echo $e->getMessage();
	  exit;
	}

	echo 'Successfully logged in.  Now searching for page ID...<br>';
  $response = $fb->get('/me/accounts', (string) $accessToken);

	foreach ($response->getDecodedBody() as $allPages) {
		foreach ($allPages as $page ) {               

			if (isset($page['id']) && $page['id'] == $pageId) { // Suppose you save it as this variable
				$appAccessToken = (string) $page['access_token'];
				echo 'Found it!.<br>';
				break;
			}
		}
	}

	echo 'Attempting to post...<br>';

	$response = $fb->post(
		'/'.$pageId.'/feed',
		array(
			"message" => "Message",
			"link" => "http://www.example.com",
			"picture" => "http://www.example.net/images/example.png",
			"name" => "Title",
			"caption" => "www.example.com",
			"description" => "Description example"
		),
		$appAccessToken
	);

	// Success
	echo 'Success!  Done.<br>';
	$postId = $response->getGraphNode();
	echo $postId;
	exit();

} elseif ($helper->getError()) {
	echo 'There was a serious error.  Dumping data.<br>';
	var_dump($helper->getError());
	var_dump($helper->getErrorCode());
	var_dump($helper->getErrorReason());
	var_dump($helper->getErrorDescription());
	exit();
}

# Ruh roh
echo 'Should not have ended up here, something went very wrong!<br>';
#echo $e->getMessage();
var_dump($helper->getError());
var_dump($helper->getErrorCode());
var_dump($helper->getErrorReason());
var_dump($helper->getErrorDescription());
exit();
?>

This is what it returns when I run the script:

Dependencies loaded.
Facebook SDK initialized.
Attempting to login...
LoginHelper loaded, now getting Access Token...
Done, moving on...
Should not have ended up here, something went very wrong!
NULL NULL NULL NULL

Based on the debugging text I added to track the flow, it appears it fails at this point:

if (isset($accessToken)) {

Then from there it skips to the end of the script. Obviously it's due to $accessToken not being set/being null, so I'm able to pinpoint the main problem as being this line (because that's where it should have been set):

$accessToken = $helper->getAccessToken();

But what's strange is that I have code put in there to catch an exception; not once is it triggered, which implies it was successfully set.

This is where I've run into a wall and am not sure how to proceed from here. Your input would help. Thanks in advance for your time and consideration in this matter.

    As a typical debugging test, I'd insert a test to see what $helper really is at that point; I don't see any such in your script:

    [code=php]$helper = $fb->getRedirectLoginHelper(); 
    echo 'LoginHelper loaded, now getting Access Token...<br>'; 
    
    if ( 1 ) {
       print_r($helper);
       exit;
    }[/code]

      Added print_r after $helper to dump the data, this is what resulted:

      Facebook\Helpers\FacebookRedirectLoginHelper Object
      (
          [oAuth2Client:protected] => Facebook\Authentication\OAuth2Client Object
              (
                  [app:protected] => Facebook\FacebookApp Object
                      (
                          [id:protected] => XXXXXXXXXXXXXXXXX
                          [secret:protected] => XXXXXXXXXXXXXXXXXXXXXXX
                      )
      
              [client:protected] => Facebook\FacebookClient Object
                  (
                      [enableBetaMode:protected] => 
                      [httpClientHandler:protected] => Facebook\HttpClients\FacebookCurlHttpClient Object
                          (
                              [curlErrorMessage:protected] => 
                              [curlErrorCode:protected] => 0
                              [rawResponse:protected] => 
                              [facebookCurl:protected] => Facebook\HttpClients\FacebookCurl Object
                                  (
                                      [curl:protected] => 
                                  )
      
                          )
      
                  )
      
              [graphVersion:protected] => v2.3
              [lastRequest:protected] => 
          )
      
      [urlDetectionHandler:protected] => Facebook\Url\FacebookUrlDetectionHandler Object
          (
          )
      
      [persistentDataHandler:protected] => Facebook\PersistentData\FacebookSessionPersistentDataHandler Object
          (
              [sessionPrefix:protected] => FBRLH_
          )
      
      [pseudoRandomStringGenerator:protected] => Facebook\PseudoRandomString\McryptPseudoRandomStringGenerator Object
          (
          )
      
      )

      I X'ed out id:protected and secret:protected. The rest of it is intact. It appears there is nothing wrong with $helper, but then I'm no guru when it comes to connecting to Facebook.

      You gave me an idea, and I added print_r to $accessToken, and it's returning as null. So whatever is going on is either at the $accessToken line or before. See anything I may have missed?

        I haven't used the SDK at all, but it would appear that the access code is null when it the helper can't find the code in the redirection URL:
        https://developers.facebook.com/docs/php/FacebookRedirectLoginHelper#get-access-token
        There may be something wrong with your login link.
        I don't see any such URL anywhere in your code, and I'm guessing the empty FacebookUrlDetectionHandler object would mean that it won't be "detected automatically".

          That was it, the login URL was needed.

          I also found out it requires two separate scripts; one for logging in, and one for the callback. I was hoping to combine both into one script and just do a $_REQUEST to grab a parameter I set in the callback url to detect a callback took place, but apparently that triggers a fatal error. Not a big deal for me, I just split it in two files, and added this to the login page:

          	$helper = $fb->getRedirectLoginHelper();
          
          # $permissions = array('email', 'user_location', 'user_birthday'); 		# Example permissions, in addition to the usual
          $permissions = array();  # If permissions are not given, then it will assume default
          $loginUrl = $helper->getLoginUrl('http://www.example.com/logincallback.php', $permissions);
          echo '<a href="' . htmlspecialchars($loginUrl) . '">Log in with Facebook!</a>';
          exit();

          Then in the callback php file, I just used the same code as above that I posted in the first post. It was able to perform the login process, up until it broke when the script tried to post on my page. I'll troubleshoot from there, as the point of this thread was to figure out the login problem. If I have further issues, I'll post in a new thread.

          Thanks ever so much for your help!

          P.S. On an unrelated note; my posts always are held back and put in the moderation queue; is that normal for all posts, or is there a threshold for a person to reach to become a trusted poster?

            P.S. On an unrelated note; my posts always are held back and put in the moderation queue; is that normal for all posts, or is there a threshold for a person to reach to become a trusted poster?

            I do think the mod queue is post-count related and will go away before too long (I know we try to set that up on our VB installs here at work). Mr. Weedpacket could probably tell ya for sure, as he is a moderator. Also a venerable and well-loved member of the forum since time immemorial, and more or less a freakin' genius. But then, there are several of those around here.

            Glad to hear you got it sorted, and welcome to PHPBuilder!

              Write a Reply...