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