In my previous tutorial How to Auto Post on Facebook Using PHP, I have explained Auto Post on Facebook using PHP SDK v3.2.3. Now in this post I will show you, how you get Facebook Access Token using PHP SDK v5.0. Facebook access token is required to post on user’s Facebook timeline/wall.
Create Facebook APP:
To get the Facebook Access token you need to create Facebook App. To create a Facebook App please follow the steps of previous post How to Auto Post on Facebook Using PHP and get the App ID and App secret key.
Get Facebook Access Token:
Now to get Facebook Access Token you need to use a PHP SDK (v5.0) to communicate with Facebook API. You can download PHP SDK 5.0 from following link Download Facebook PHP SDK v5.0.
System Requirements:
1. PHP 5.4 or greater
2. The Curl extension
3. The mbstring extension
Now create a file getAccessToken.php and write the code as below to request for Facebook Access Token.
require_once __DIR__ . '/FacebookSDK/src/Facebook/autoload.php'; $fbData = array( 'consumer_key' => APP_ID, 'consumer_secret' => APP_SECRET, 'default_graph_version' => 'v2.2' ); $fb = new Facebook\Facebook($fbData); $params = array('req_perms' => 'publish_actions'); $helper = $fb->getRedirectLoginHelper(); $loginUrl = $helper->getLoginUrl('callback.php', $params); header('Location: '. $loginUrl); exit;
You will see the screen like below. Now you need to allow permission by click on Okay.
Before click on Okay, create a callback.php page with following code:
require_once __DIR__ . '/FacebookSDK/src/Facebook/autoload.php'; $fbData = array( 'consumer_key' => APP_ID, 'consumer_secret' => APP_SECRET, 'default_graph_version' => 'v2.2' ); $fb = new Facebook\Facebook($fbData); $helper = $fb->getRedirectLoginHelper(); try { $accessToken = $helper->getAccessToken(); // this token will be valid for next 2 hours } 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; }
Now to extend the validity of this access token use following code after getting access token.
// OAuth 2.0 client handler $oAuth2Client = $fb->getOAuth2Client(); // Exchanges a short-lived access token for a long-lived one $accessToken = $oAuth2Client->getLongLivedAccessToken($accessToken);
Now the access toke will be valid for next 60 days. You can save this access token and use for the auto post on user’s facebook timeline.
I hope this tutorial will help you to get the Facebook Access Token of the user using PHP SDK v5.