views:

79

answers:

1

Hi

I've followed the instructions on http://developers.facebook.com/docs/api#authorization using the standard PHP library. Everything works fine until it redirects to my site. I'm not sure what I'm meant to be doing here! When the redirection occurs, I can see the key facebook talks about that I use to request an OAuth token in the URL.

However what am I meant to do with this? Do I write a simple script that takes the new 'code' value and place a request to the facebook page with that included in the details? Is there no call in the php library to do this entire process for me?

Any help appreciated.

+1  A: 

Here's how the code looks in my application (simplified for this example)

$code = $_REQUEST['code'];
if ( $code )
{
  $response = $facebook->api( '/oauth/access_token', 'GET', array(
      'client_id'     => $facebook->getAppId()
    , 'client_secret' => $facebook->getApiSecret()
    , 'redirect_uri'  => 'http://example.com/your/redirect/uri'
    , 'code'          => $code
  ) );
  parse_str( $response, $vars );
  $oauthToken = $vars['access_token'];

  // Persist this token in the session, DB, or wherever you want

} else {
  switch ( $_REQUEST['error_reason'] )
  {
    case 'user_denied':
      // some sort of message here
      break;
  }
}

If, like me, you have created a subclass of Facebook, just put some of the above into a new method

/**
 * Exchange an Access Code for an OAuth Token
 *  
 * @param string $accessCode
 * @param string $redirectUrl
 * 
 * @return string OAuth Token
 */
public function getOauthTokenFromAccessCode( $accessCode, $redirectUrl )
{
  $response = $this->api( '/oauth/access_token', 'GET', array(
      'client_id'     => $this->getAppId()
    , 'client_secret' => $this->getApiSecret()
    , 'redirect_uri'  => $redirectUrl
    , 'code'          => $accessCode
  ) );
  parse_str( $response, $vars );
  return $vars['access_token'];
}

Which simplifies the client code to this

$code = $_REQUEST['code'];
if ( $code )
{
  $oauthToken = $facebook->getOauthTokenFromAccessCode(
      $code
    , 'http://example.com/your/redirect/uri'
  );

  // Persist this token in the session, DB, or wherever you want

} else {
  switch ( $_REQUEST['error_reason'] )
  {
    case 'user_denied':
      // some sort of message here
      break;
  }
}
Peter Bailey