Skip to content

Instantly share code, notes, and snippets.

@nightillusions
Last active February 14, 2018 18:54
Show Gist options
  • Save nightillusions/ff34ca5f21dd9e6380f97805502411ed to your computer and use it in GitHub Desktop.
Save nightillusions/ff34ca5f21dd9e6380f97805502411ed to your computer and use it in GitHub Desktop.
Little class to handle Facebook API authentification with the PHP-SDK
<?php
require './vendor/autoload.php';
use Facebook\Facebook;
use Facebook\Exceptions\FacebookResponseException;
use Facebook\Exceptions\FacebookSDKException;
define( 'FB_GROUP_APP_BASE_URL', 'https://wdj.ac' );
define( 'FB_GROUP_APP_CALLBACK_URL', FB_GROUP_APP_BASE_URL . '/facebook-auth.php?action=verify-user' );
define( 'FB_GROUP_APP_ID', '' );
define( 'FB_GROUP_APP_SECRET', '' );
define( 'FB_GROUP_APP_GRAPH_VERSION', 'v2.10' );
define( 'FB_GROUP_APP_PERMISSION_MANAGED_GROUPS', 'user_managed_groups' );
define( 'FB_GROUP_APP_PERMISSION_PUBLISH_ACTIONS', 'publish_actions' );
define( 'FB_GROUP_APP_ADD_NEW_USER_KEY', '' );
define( 'FB_GROUP_APP_TOKEN_FILENAME', './.fb-token' );
class FacebookAuth {
private $fb;
public $canvasHelper;
public $loginHelper;
public $oAuth2Client;
public $permissions = [ FB_GROUP_APP_PERMISSION_MANAGED_GROUPS, FB_GROUP_APP_PERMISSION_PUBLISH_ACTIONS ];
public $tokenFileName = FB_GROUP_APP_TOKEN_FILENAME;
private $accessToken;
private $validateNewUser;
public $callbackURL = FB_GROUP_APP_CALLBACK_URL;
public function __construct( $user = true, $validateNewUser = false, $appID = FB_GROUP_APP_ID, $appSecret = FB_GROUP_APP_SECRET, $graphVersion = FB_GROUP_APP_GRAPH_VERSION ) {
$app = array(
'app_id' => $appID,
'app_secret' => $appSecret,
'default_graph_version' => $graphVersion,
//'persistent_data_handler' => 'memory' //session
);
$this->fb = new Facebook( $app );
$this->canvasHelper = $this->fb->getCanvasHelper();
$this->loginHelper = $this->fb->getRedirectLoginHelper();
$this->oAuth2Client = $this->fb->getOAuth2Client();
$this->validateNewUser = $validateNewUser;
if ( ! $user ) {
$this->addUser();
} else {
$this->initiate();
}
}
/**
* File based:
* Initial logic to handle access token
*/
private function initiate() {
try {
// Get access token from file
if ( file_exists( $this->tokenFileName ) && ! $this->validateNewUser ) {
$token = file_get_contents( $this->tokenFileName );
$lastTokenRefresh = time() - filemtime( $this->tokenFileName );
// Refresh token after 7 days (60 * 60 * 24 * 7)
if ( $lastTokenRefresh > 604800 ) {
$newToken = $this->refreshToken( $token );
file_put_contents( $this->tokenFileName, (string) $newToken );
$this->setAccessToken( (string) $newToken );
} else {
$this->setAccessToken( (string) $token );
}
} // If new user oAuth
elseif ( file_exists( $this->tokenFileName ) && $this->validateNewUser ) {
unlink( $this->tokenFileName );
$this->setAccessToken( $this->loginHelper->getAccessToken() );
} // Initial app start (never used before)
else {
$this->setAccessToken( $this->loginHelper->getAccessToken() );
//$this->setAccessToken( $this->loginHelper->getAccessToken()->getValue() );
}
}
catch ( FacebookResponseException $e ) {
$this->exceptionHandler( $e->getMessage(), 'Facebook Graph returned an error:' );
}
catch ( FacebookSDKException $e ) {
$this->exceptionHandler( $e->getMessage(), 'Facebook SDK returned an error:' );
}
if ( $this->getAccessToken() ) {
if ( file_exists( $this->tokenFileName ) ) {
$this->fb->setDefaultAccessToken( file_get_contents( $this->tokenFileName ) );
} else {
// OAuth 2.0 client handler
// $oAuth2Client = $this->fb->getOAuth2Client();
// Exchanges a short-lived access token for a long-lived one
try {
$longLivedAccessToken = $this->oAuth2Client->getLongLivedAccessToken( (string) $this->getAccessToken() );
file_put_contents( $this->tokenFileName, (string) $longLivedAccessToken );
$this->fb->setDefaultAccessToken( $longLivedAccessToken );
$this->setAccessToken( $longLivedAccessToken );
}
catch ( FacebookSDKException $e ) {
$this->exceptionHandler( $e->getMessage(), 'Facebook SDK returned an error:' );
}
}
if ( $this->validateNewUser ) { //&& $this->getAccessToken()->isLongLived()
$this->validateNewUser = false;
echo "Succesfully connected!";
echo "<script>window.setTimeout(function() { window.top.location.href='" . FB_GROUP_APP_BASE_URL . "'; }, 5000);</script>";
exit;
}
} else {
$this->exceptionHandler( 'No Facebook Connection!', 'Initiate error:' );
exit();
}
}
/**
* Start Facebook oAuth to connect new user
*/
public function addUser() {
$loginUrl = $this->loginHelper->getLoginUrl( $this->callbackURL, $this->permissions );
echo "<script>window.top.location.href='" . $loginUrl . "'</script>";
}
/**
* Refresh long-lived access token
* New since 2017-12-18
*
* @param $token
*
* @return \Facebook\Authentication\AccessToken
*/
public function refreshToken( $token ) {
try {
return $this->oAuth2Client->getAccessTokenFromCode(
$this->oAuth2Client->getCodeFromLongLivedAccessToken(
$token
)
);
}
catch ( FacebookSDKException $e ) {
$this->exceptionHandler( $e->getMessage(), 'Facebook SDK returned an error:' );
return $token;
}
}
/**
* Validate the access token
*
* @return bool
*/
public function validate() {
try {
$request = $this->fb->get( '/me' );
}
catch ( FacebookResponseException $e ) {
// When Graph returns an error
if ( $e->getCode() == 190 ) {
// When token is expired
unlink( $this->tokenFileName );
$this->exceptionHandler( 'Der Token ist abgelaufen!', 'Graph returned an error:' );
return false;
} else {
// All other Graph errors
$this->exceptionHandler( $e->getMessage(), 'Graph returned an error:' );
return false;
}
}
catch ( FacebookSDKException $e ) {
// When validation fails or other local issues
$this->exceptionHandler( $e->getMessage(), 'Facebook SDK returned an error:' );
return false;
}
return true;
}
}
/************************************
* All the following is for directly calling the file
************************************/
$userAccessKey = FB_GROUP_APP_ADD_NEW_USER_KEY; // Security access key for adding new connected user
// When action parameter is set and key is correct
if (
( $action = filter_input( INPUT_GET, 'action', FILTER_SANITIZE_STRING ) ) &&
( ( $key = filter_input( INPUT_GET, 'key', FILTER_SANITIZE_STRING ) ) && $key === $userAccessKey )
) {
switch ( $action ) {
// Start Facebook oAuth
case 'add-user':
$fb = new FBAutopost( 0 );
break;
}
} // When Facebook oAuth callback
elseif ( isset( $_GET['code'] ) && $action = filter_input( INPUT_GET, 'action', FILTER_SANITIZE_STRING ) && $action === 'verify-user' ) {
$fb = new FBAutopost( 1, 1 );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment