Created
February 19, 2015 17:36
-
-
Save niraj-shah/48ad485026d148ef0ac2 to your computer and use it in GitHub Desktop.
Getting started with the Facebook PHP SDK v4.1. Part c: Login and make a API call
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// login helper with redirect_uri | |
$helper = $fb->getRedirectLoginHelper(); | |
// see if we have a code in the URL | |
if ( isset( $_GET['code'] ) ) { | |
// get new access token if we've been redirected from login page | |
try { | |
// get access token | |
$access_token = $helper->getAccessToken(); | |
// save access token to persistent data store | |
$helper->getPersistentDataHandler()->set( 'access_token', $access_token ); | |
} catch ( Exception $e ) { | |
// error occured | |
} | |
} | |
// get stored access token | |
$access_token = $helper->getPersistentDataHandler()->get( 'access_token' ); | |
// check if we have an access_token, and that it's valid | |
if ( $access_token && !$access_token->isExpired() ) { | |
// set default access_token so we can use it in any requests | |
$fb->setDefaultAccessToken( $access_token ); | |
try { | |
// If you provided a 'default_access_token', second parameter '{access-token}' is optional. | |
$response = $fb->get( '/me' ); | |
// use $fb->post() to make a POST API call | |
} catch( Exception $e ) { | |
// catch any errors and halt script | |
echo $e->getMessage(); | |
exit; | |
} | |
$me = $response->getGraphUser(); | |
echo '<p>Logged in as ' . $me->getName() . '</p>'; | |
echo '<pre>' . print_r( $me, 1 ) . '</pre>'; | |
echo '<p><a href="' . $helper->getLogoutUrl( $access_token, 'http://sites.local/php-sdk-4.1/logout.php' ) . '">Logout of Facebook</a></p>'; | |
} else { | |
// show login link | |
echo '<a href="' . $helper->getLoginUrl( 'http://sites.local/php-sdk-4.1/', ['email'] ) . '">Login using Facebook</a>'; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment