/**
  * @param string $accessToken
  *
  * @throws FacebookException
  */
 public function connect($accessToken)
 {
     $this->session = new FacebookSession($accessToken);
     try {
         $this->session->validate();
     } catch (FacebookRequestException $exception) {
         // Session not valid, Graph API returned an exception with the reason.
         throw new FacebookException($exception->getMessage());
     } catch (\Exception $exception) {
         // Graph API returned info, but it may mismatch the current app or have expired.
         throw new FacebookException($exception->getMessage());
     }
 }
 /**
  * Ask for a facebook session 
  * @return boolean
  */
 public final function hasLoggedIn()
 {
     if (is_null($this->fbsession) and !is_null($this->session)) {
         return $this->session->getData("_facebookSession") ?: false;
     }
     return $this->fbsession->validate();
 }
예제 #3
0
 /**
  * Try tlo initialize FacebookSession with a providedd acces token
  *
  * @param String $accessToken Tha external accessToken
  * @throws Exceptions\PhacebookException
  */
 private function tryValidateSession($accessToken)
 {
     $this->facebookSession = new FacebookSession($accessToken);
     try {
         $this->facebookSession->validate();
     } catch (FacebookSDKException $e) {
         throw new PhacebookException($e->getMessage());
     }
 }
예제 #4
0
 public function facebook()
 {
     $facebook_default_scope = explode(',', $this->ci->config->item("facebook_default_scope"));
     $facebook_app_id = $this->ci->config->item("facebook_app_id");
     $facebook_api_secret = $this->ci->config->item("facebook_api_secret");
     // init app with app id and secret
     FacebookSession::setDefaultApplication($facebook_app_id, $facebook_api_secret);
     // login helper with redirect_uri
     $helper = new FacebookRedirectLoginHelper(site_url('login/facebook'));
     // see if a existing session exists
     if (isset($_SESSION) && isset($_SESSION['fb_token'])) {
         // create new session from saved access_token
         $session = new FacebookSession($_SESSION['fb_token']);
         // validate the access_token to make sure it's still valid
         try {
             if (!$session->validate()) {
                 $session = null;
             }
         } catch (Exception $e) {
             // catch any exceptions
             $session = null;
         }
     }
     if (!isset($session) || $session === null) {
         // no session exists
         try {
             $session = $helper->getSessionFromRedirect();
         } catch (FacebookRequestException $ex) {
             // When Facebook returns an error
             // handle this better in production code
             print_r($ex);
         } catch (Exception $ex) {
             // When validation fails or other local issues
             // handle this better in production code
             print_r($ex);
         }
     }
     // see if we have a session
     if (isset($session)) {
         // save the session
         $_SESSION['fb_token'] = $session->getToken();
         // create a session using saved token or the new one we generated at login
         $session = new FacebookSession($session->getToken());
         // graph api request for user data
         //$request = new FacebookRequest($session, 'GET', '/me/friends');
         $request = new FacebookRequest($session, 'GET', '/me?fields=id,name,picture,friends');
         $response = $request->execute();
         // get response
         $graphObject = $response->getGraphObject()->asArray();
         $fb_data = array('me' => $graphObject, 'loginUrl' => $helper->getLoginUrl($facebook_default_scope));
         $this->ci->session->set_userdata('fb_data', $fb_data);
     } else {
         $fb_data = array('me' => null, 'loginUrl' => $helper->getLoginUrl($facebook_default_scope));
         $this->ci->session->set_userdata('fb_data', $fb_data);
     }
     return $fb_data;
 }
 public function isLoggedIn()
 {
     $logged = false;
     if (!empty($this->session)) {
         try {
             $this->session->validate();
             $logged = true;
         } catch (FacebookRequestException $ex) {
             // Session not valid, Graph API returned an exception with the reason.
             Log::warning($ex->getMessage());
         } catch (Exception $ex) {
             // Graph API returned info, but it may mismatch the current app or have expired.
             Log::warning($ex->getMessage());
         }
         return $logged;
     } else {
         return $logged;
     }
 }
예제 #6
0
 public function exchange_long_lived_token($access_token)
 {
     $session = new FacebookSession($access_token);
     // Check validate token
     if ($session->validate()) {
         $long_lived_session = $session->getLongLivedSession();
         return $long_lived_session->getToken();
     }
     return false;
 }
예제 #7
0
function isLogged()
{
    // Inicializações para autenticação
    // Crie um aplicativo no Facebook e configure aqui o ID e a chave secreta obtidos no site
    $id = '987654321012345';
    $secret = 'aeiou12345qwert98765asdfg1234567';
    FacebookSession::setDefaultApplication($id, $secret);
    // Inicializa sessão PHP
    session_start();
    // Se o cookie foi recebido numa requisição anterior, e o
    // token FB já foi recuperado, necessita apenas autenticar
    // o usuário no FB usando o token
    if (isset($_SESSION['token'])) {
        $session = new FacebookSession($_SESSION['token']);
        try {
            if (!$session->validate($id, $secret)) {
                unset($session);
            }
        } catch (FacebookRequestException $ex) {
            // Facebook retornou um erro
            // return [false, $ex->getMessage()];
            unset($session);
        } catch (\Exception $ex) {
            // return [false, $ex->getMessage()];
            unset($session);
        }
    }
    // Se o cookie ainda não foi recebido (primeira requisição
    // do cliente), recupera e grava na variável de sessão PHP.
    // Executa autenticação no FB
    if (!isset($session)) {
        try {
            $helper = new FacebookJavaScriptLoginHelper();
            $session = $helper->getSession();
            if ($session) {
                $_SESSION['token'] = $session->getToken();
            }
        } catch (FacebookRequestException $ex) {
            // Facebook retornou um erro
            unset($session);
            return [false, $ex->getMessage()];
        } catch (\Exception $ex) {
            // Falha na validação ou outro erro
            unset($session);
            return [false, $ex->getMessage()];
        }
    }
    // Facebook aceitou usuário/senha
    if (isset($session) && $session) {
        return [true, $_SESSION['token']];
    }
    // Facebook rejeitou usuário/senha
    return [false, "Usuário/senha inválida"];
}
예제 #8
0
 public function validate()
 {
     try {
         FacebookSession::setDefaultApplication($this->getParam('APP_ID'), $this->getParam('APP_SECRET'));
         $session = new FacebookSession($this->getParam('TOKEN'));
         $session->validate();
     } catch (FacebookSDKException $f) {
         return false;
     }
     return true;
 }
예제 #9
0
 /**
  * Get the FacebookSession through an access_token.
  *
  * @param  string $accessToken
  * @return FacebookSession
  */
 private function getFacebookSession($accessToken)
 {
     $facebookSession = new FacebookSession($accessToken);
     try {
         $facebookSession->validate();
         return $facebookSession;
     } catch (FacebookRequestException $ex) {
         throw new FacebookException($ex->getMessage());
     } catch (\Exception $ex) {
         throw new FacebookException($ex->getMessage());
     }
 }
예제 #10
0
 public function matchUser($access_token)
 {
     FacebookSession::setDefaultApplication('1594113490874544', 'fca50280932a6065e68a540ac3f2925b');
     $session = new FacebookSession($access_token);
     try {
         $session->validate();
     } catch (FacebookRequestException $ex) {
         return false;
     } catch (\Exception $ex) {
         return false;
     }
     return true;
 }
예제 #11
0
 /**
  * Initializes facebook's connection.
  *
  * @throws FacebookRequestException
  * @throws \Exception
  */
 private function initialize()
 {
     FacebookSession::enableAppSecretProof(false);
     $session = new FacebookSession($this->accessToken);
     try {
         $session->validate();
     } catch (FacebookRequestException $e) {
         $this->entry->addException($e->getMessage());
     } catch (\Exception $e) {
         $this->entry->addException($e->getMessage());
     }
     $this->session = $session;
 }
예제 #12
0
 /**
  * Get the FacebookSession through an access_token.
  *
  * @param string $accessToken
  * @return FacebookSession
  */
 public function getFacebookSession($accessToken)
 {
     $session = new FacebookSession($accessToken);
     // Validate the access_token to make sure it's still valid
     try {
         if (!$session->validate()) {
             $session = null;
         }
     } catch (\Exception $e) {
         // Catch any exceptions
         $session = null;
     }
     return $session;
 }
예제 #13
0
 public function loginAction($appId, Request $request)
 {
     $ret = array('success' => false);
     if ($request->request->get('facebook_token') != null && 'POST' === $request->getMethod()) {
         $em = $this->getDoctrine();
         $app = $em->getRepository('KeosuCoreBundle:App')->find($appId);
         $configPackages = $app->getConfigPackages();
         $fbAppId = $configPackages[KeosuGadgetFaceBookBundle::PLUGIN_NAME]['fbAppId'];
         $fbAppSecret = $configPackages[KeosuGadgetFaceBookBundle::PLUGIN_NAME]['fbAppSecret'];
         FacebookSession::setDefaultApplication($fbAppId, $fbAppSecret);
         $session = new FacebookSession($request->request->get('facebook_token'));
         try {
             $session->validate();
             $user_profile = (new FacebookRequest($session, 'GET', '/me'))->execute()->getGraphObject(GraphUser::className());
             // user Email
             $email = $user_profile->getProperty('email');
             $userManager = $this->container->get('fos_user.user_manager');
             $user = $userManager->findUserByUsernameOrEmail($email);
             // the user doesn't have account
             if ($user == null) {
                 $user = $userManager->createUser();
                 $user->setUsername($email);
                 $user->setEnabled(true);
                 $user->setPlainPassword(\md5($email . \rand()));
                 $user->setEmail($email);
                 $user->setAccountType('facebook');
                 $userManager->updateUser($user);
             }
             if ($user->getAccountType() == 'facebook') {
                 // We log the user
                 $token = new UsernamePasswordToken($user, null, 'main', $user->getRoles());
                 $this->get('security.context')->setToken($token);
                 $this->get('session')->set('_security_main', serialize($token));
                 $ret['success'] = true;
             } else {
                 $ret['message'] = "This email is allready used with an other account";
             }
         } catch (FacebookRequestException $ex) {
             echo $ex->getMessage();
         } catch (\Exception $ex) {
             echo $ex->getMessage();
         }
     } else {
         $ret['message'] = 'unable to login with facebook';
     }
     return new JsonResponse($ret);
 }
예제 #14
0
 /**
  * @param string $accessToken
  * @return bool
  */
 public function facebook($accessToken = null)
 {
     if (empty($accessToken)) {
         return false;
     }
     FacebookSession::setDefaultApplication(Config::get('verify::facebook.appId'), Config::get('verify::facebook.appSecret'));
     $session = new FacebookSession($accessToken);
     try {
         $session->validate(Config::get('verify::facebook.appId'), Config::get('verify::facebook.appSecret'));
         $data = $session->getSessionInfo()->asArray();
         return array('valid' => true, 'user_id' => $data['user_id'], 'app_id' => $data['app_id'], 'message' => 'Access Token is valid.');
     } catch (FacebookRequestException $ex) {
         return array('valid' => false, 'messages' => $ex->getMessage());
     } catch (Exception $ex) {
         return array('valid' => false, 'messages' => $ex->getMessage());
     }
 }
 private function getSession()
 {
     $token = get_option($this->tokenOptionsKey, "");
     $session = new FacebookSession($token);
     // To validate the session:
     try {
         $session->validate();
         return $session;
     } catch (FacebookRequestException $ex) {
         // Session not valid, Graph API returned an exception with the reason.
         echo $ex->getMessage();
         return null;
     } catch (\Exception $ex) {
         // Graph API returned info, but it may mismatch the current app or have expired.
         echo $ex->getMessage();
         return null;
     }
 }
예제 #16
0
 public function __construct($app_id, $app_secret, $redirectURI)
 {
     FacebookSession::setDefaultApplication($app_id, $app_secret);
     $this->loginHelper = new FacebookRedirectLoginHelper($redirectURI);
     // see if a existing session exists
     if (isset($_SESSION) && isset($_SESSION['fb_token'])) {
         $session = new FacebookSession($_SESSION['fb_token']);
         // create new session from saved access_token
         // validate the access_token to make sure it's still valid
         try {
             if (!$session->validate()) {
                 $session = null;
             }
         } catch (Exception $e) {
             $session = null;
         }
     } else {
         // no session exists
         try {
             $session = $this->loginHelper->getSessionFromRedirect();
         } catch (FacebookRequestException $ex) {
             $session = null;
             var_dump($ex);
         } catch (Exception $ex) {
             $session = null;
             var_dump($ex);
         }
     }
     // see if we have a session
     if (isset($session)) {
         $_SESSION['fb_token'] = $session->getToken();
         // Save the token
         $session = new FacebookSession($session->getToken());
         // create a session using saved token or the new one we generated at login
     } else {
         $session = null;
     }
     $this->session = $session;
 }
예제 #17
0
function fbe_validate_session($appID,$appSecret){

FacebookSession::setDefaultApplication($appID, $appSecret);

// If you already have a valid access token:
$session = new FacebookSession($appID.'|'.$appSecret);


// To validate the session:
try {
	  $session->validate();
	  echo '<div class="updated" style="color:#222222; font-weight:700; font-size:1em; padding:10px">Settings Saved</div>';	

	} 
		catch (FacebookRequestException $ex) {
		// Session not valid, Graph API returned an exception with the reason.
		echo '<div class="error" style="color:#222222; font-weight:700; font-size:1em; padding:10px">'.$ex->getMessage().'</div>';
	} 
	catch (\Exception $ex) {
		// Graph API returned info, but it may mismatch the current app or have expired.
		echo '<div class="error" style="color:#222222; font-weight:700; font-size:1em; padding:10px">'.$ex->getMessage().'</div>';
	}

}
예제 #18
0
use Facebook\FacebookRedirectLoginHelper;
error_reporting(0);
/**
* here you have to provide your application ID and SECRET
* which are given by facebook after creating the application
*/
//curl_setopt(CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4 );
FacebookSession::setDefaultApplication('482081285307797', 'a3af071bc153c12ef3068510de339754');
$helper = new FacebookRedirectLoginHelper('http://localhost/demo1/index.php');
//$session = $helper->getSessionFromRedirect();
if (isset($_SESSION) && isset($_SESSION['fb_token'])) {
    // create new session from saved access_token
    $session = new FacebookSession($_SESSION['fb_token']);
    try {
        facebook::$CURL_OPTS[CURLOPT_CAINFO] = 'libs/Facebook/HttpClients/fb_ca_chain_bundle.crt';
        if (!$session->validate()) {
            $session = null;
        }
    } catch (Exception $e) {
        // catch any exceptions
        $session = null;
    }
}
if (!isset($session) || $session === null) {
    try {
        $session = $helper->getSessionFromRedirect();
    } catch (FacebookRequestException $ex) {
        print_r($ex);
    } catch (Exception $ex) {
        print_r($ex);
    }
예제 #19
0
use Facebook\FacebookRequestException;
use Facebook\FacebookAuthorizationException;
use Facebook\GraphObject;
use Facebook\GraphUser;
use Facebook\GraphSessionInfo;
FacebookSession::setDefaultApplication(FB_APP_ID, FB_APP_SECRET);
$helper = new FacebookRedirectLoginHelper(FB_REDIRECT_URI);
if (isset($_GET['type']) && $_GET['type'] == 'facebook') {
    $fb_url = $helper->getLoginUrl(array('email'));
    header('Location: ' . $fb_url);
}
$session = $helper->getSessionFromRedirect();
if (isset($_SESSION['token'])) {
    $session = new FacebookSession($_SESSION['token']);
    try {
        $session->validate(FB_APP_ID, FB_APP_SECRET);
    } catch (FacebookAuthorizationException $e) {
        echo $e->getMessage();
    }
}
$data = array();
if (isset($session)) {
    $_SESSION['token'] = $session->getToken();
    $request = new FacebookRequest($session, 'GET', '/me');
    $response = $request->execute();
    $graph = $response->getGraphObject(GraphUser::className());
    $data = $graph->asArray();
    $id = $graph->getId();
    $image = "https://graph.facebook.com/" . $id . "/picture?width=100";
    $data['image'] = $image;
    if ($user_obj->fb_login($data)) {
예제 #20
0
 public function simplefbpost()
 {
     // init app with app id and secret
     FacebookSession::setDefaultApplication($this->facebook_app_id, $this->facebook_api_secret);
     // login helper with redirect_uri
     $helper = new FacebookRedirectLoginHelper(site_url('landing/index'));
     // see if a existing session exists
     if (isset($_SESSION) && isset($_SESSION['fb_token'])) {
         // create new session from saved access_token
         $session = new FacebookSession($_SESSION['fb_token']);
         // validate the access_token to make sure it's still valid
         try {
             if (!$session->validate()) {
                 $session = null;
             }
         } catch (Exception $e) {
             // catch any exceptions
             $session = null;
         }
     }
     if (!isset($session) || $session === null) {
         // no session exists
         try {
             $session = $helper->getSessionFromRedirect();
         } catch (FacebookRequestException $ex) {
             // When Facebook returns an error
             // handle this better in production code
             print_r($ex);
         } catch (Exception $ex) {
             // When validation fails or other local issues
             // handle this better in production code
             print_r($ex);
         }
     }
     if (isset($session)) {
         // save the session
         $_SESSION['fb_token'] = $session->getToken();
         // create a session using saved token or the new one we generated at login
         $session = new FacebookSession($session->getToken());
         try {
             // with this session I will post a message to my own timeline
             $request = new FacebookRequest($session, 'POST', '/me/feed', array('link' => 'www.purnimapro.com', 'message' => 'Complete IT Solutions'));
             $response = $request->execute();
             $graphObject = $response->getGraphObject();
             // the POST response object
             echo '<pre>' . print_r($graphObject, 1) . '</pre>';
             $msgid = $graphObject->getProperty('id');
         } catch (FacebookRequestException $e) {
             // show any error for this facebook request
             echo 'Facebook (post) request error: ' . $e->getMessage();
         }
         if (isset($msgid)) {
             // we only need to the sec. part of this ID
             $parts = explode('_', $msgid);
             try {
                 $request2 = new FacebookRequest($session, 'GET', '/' . $parts[1]);
                 $response2 = $request2->execute();
                 $graphObject2 = $response2->getGraphObject();
                 // the GET response object
                 echo '<pre>' . print_r($graphObject2, 1) . '</pre>';
             } catch (FacebookRequestException $e) {
                 // show any error for this facebook request
                 echo 'Facebook (get) request error: ' . $e->getMessage();
             }
         }
     } else {
         // we need to create a new session, provide a login link
         echo 'No session, please <a href="' . $helper->getLoginUrl(array('publish_actions')) . '">login</a>.';
     }
 }
예제 #21
0
 /**
  * Checking if the user is already signed in with Facebook
  * and get the session data from the Facebook cookie or
  * our current if it is still valid
  *
  * @return  object
  **/
 private function facebook_session()
 {
     // Check if our own session token exists
     if ($this->session->userdata('fb_token')) {
         // Create new session for the token
         $session = new FacebookSession($this->session->userdata('fb_token'));
         // validate the access token to make sure it's still valid
         try {
             if (!$session->validate()) {
                 // Not valid, create new session
                 $session = $this->get_new_session();
             }
         } catch (Exception $e) {
             // Error, create new session
             $session = $this->get_new_session();
         }
     } else {
         // We don't have a session, create a new
         $session = $this->get_new_session();
     }
     // Return session object data
     return $session;
 }
예제 #22
0
파일: login1.php 프로젝트: quocphu/hiragana
<?php

session_start();
require_once "../config/config.properties";
require_once "../autoload.php";
use Facebook\FacebookSession;
use Facebook\FacebookRedirectLoginHelper;
use Facebook\FacebookRequest;
use Facebook\GraphUser;
use Facebook\BaseFacebook;
$redirect_url = 'http://localhost:8888/fb/callback.php';
FacebookSession::setDefaultApplication(FBID, FBS);
$session = new FacebookSession($_SESSION['token1']);
try {
    $session->validate();
    $user_profile = (new FacebookRequest($session, 'GET', '/me'))->execute()->getGraphObject(GraphUser::className());
    echo "Name: " . $user_profile->getName();
} catch (Exception $ex) {
    $helper = new FacebookRedirectLoginHelper($redirect_url, $appId = FBID, $appSecret = FBS);
    echo '<a href="' . $helper->getLoginUrl() . '">Login with Facebook</a>';
}
?>
<!DOCTYPE html>
<html>
<head>
<script>
      window.fbAsyncInit = function() {
        FB.init({
          appId      : '854438244566604',
          xfbml      : true,
          version    : 'v2.1'
예제 #23
0
파일: share.php 프로젝트: Jaesin/zim-web
 public function connect_facebook($in_upload = NULL)
 {
     if (isset($_POST['fb_title']) && isset($_POST['fb_desc'])) {
         $fb_title = $_POST['fb_title'];
         $fb_desc = $_POST['fb_desc'];
         $_SESSION['fb_title'] = $fb_title;
         $_SESSION['fb_desc'] = $fb_desc;
     } else {
         $fb_title = $_SESSION['fb_title'];
         $fb_desc = $_SESSION['fb_desc'];
     }
     FacebookSession::setDefaultApplication('406642542819370', 'da80c93b500711ba60c79cf943e776e5');
     $helper = new FacebookRedirectLoginHelper("https://sso.zeepro.com/redirectfb.ashx?sn=" . ZimAPI_getSerial());
     $this->load->helper(array('zimapi', 'corestatus', 'printerlog'));
     if (isset($_SESSION) && isset($_SESSION['fb_token'])) {
         // create new session from the existing PHP sesson
         $session = new FacebookSession($_SESSION['fb_token']);
         try {
             // validate the access_token to make sure it's still valid
             if (!$session->validate()) {
                 // try to pick session from redirection if session is invalid or expired, it returns null if it's not a valid redirect
                 // that avoid when we have set session value, but we need re-authenticate from redirection - Peng
                 // 					$session = null;
                 $session = $helper->getSessionFromRedirect();
             }
         } catch (Exception $e) {
             // catch any exceptions and set the sesson null
             $session = null;
             echo 'No session: ' . $e->getMessage();
         }
     } else {
         // the session is empty, we create a new one
         try {
             // the visitor is redirected from the login, let's pickup the session
             $session = $helper->getSessionFromRedirect();
         } catch (FacebookRequestException $e) {
             // Facebook has returned an error
             echo 'Facebook (session) request error: ' . $e->getMessage();
         } catch (Exception $e) {
             // Any other error
             echo 'Other (session) request error: ' . $e->getMessage();
         }
     }
     if (isset($session)) {
         PrinterLog_logDebug('Facebook upload with session');
         // store the session token into a PHP session
         $_SESSION['fb_token'] = $session->getToken();
         // 			// and create a new Facebook session using the cururent token
         // 			// or from the new token we got after login
         // 			$session = new FacebookSession($session->getToken());
         // connect succeeded, check if we are in uploading call or not (redirection doesn't have in_upload variable in extra path) - Peng
         if ($in_upload == NULL) {
             PrinterLog_logDebug('Facebook connect by getting session from redirection');
             $this->facebook_upload();
             return;
         } else {
             try {
                 $this->lang->load('share/facebook_form', $this->config->item('language'));
                 $this->upload_facebookVideo($fb_title == "" ? t('fb_title') : $fb_title, $fb_desc == "" ? t('fb_desc') : $fb_desc);
             } catch (FacebookRequestException $e) {
                 // show any error for this facebook request
                 echo 'Facebook (post) request error: ' . $e->getMessage();
                 PrinterLog_logDebug('Facebook (post) request error: ' . $e->getMessage());
             }
         }
     } else {
         $loginUrl = $helper->getLoginUrl(array('publish_actions'));
         $prefix = CoreStatus_checkTromboning() ? 'https://' : 'http://';
         $data = array('printersn' => ZimAPI_getSerial(), 'URL' => $prefix . $_SERVER['HTTP_HOST'] . '/share/connect_facebook');
         $options = array('http' => array('header' => "Content-type: application/x-www-form-urlencoded\r\n", 'method' => 'POST', 'content' => http_build_query($data)));
         $context = stream_context_create($options);
         @file_get_contents('https://sso.zeepro.com/url.ashx', false, $context);
         $result = substr($http_response_header[0], 9, 3);
         echo "{$loginUrl}";
         PrinterLog_logDebug('Facebook login url: ' . $loginUrl);
         $this->output->set_status_header(202);
     }
 }
 public function testInvalidCredentialsException()
 {
     $bogusSession = new FacebookSession('invalid-token');
     $this->setExpectedException('Facebook\\FacebookAuthorizationException', 'Invalid OAuth access token');
     $bogusSession->validate('invalid-app-id', 'invalid-app-secret');
 }
예제 #25
0
//2.Use app id,secret and redirect url
$app_id = '1119371311414975';
$app_secret = 'b1deed597b5fa3b766e3c3c04d4ca20a';
$redirect_url = 'http://localhost:63342/dukanonline/facebook.php';
//3.Initialize application, create helper object and get fb sess
FacebookSession::setDefaultApplication($app_id, $app_secret);
$helper = new FacebookRedirectLoginHelper($redirect_url);
try {
    $sess = $helper->getSessionFromRedirect();
} catch (Exception $e) {
}
//check if facebook session exists
if (isset($_SESSION['fb_token'])) {
    $sess = new FacebookSession($_SESSION['fb_token']);
    try {
        $sess->validate($app_id, $app_secret);
    } catch (FacebookAuthorizationException $e) {
        $sess = '';
    }
}
//logout
//$logout = 'http://localhost:63342/newfblogin&logout=true';
$logout = 'http://localhost:63342/dukanonline/facebook.php?logout=true';
//$logout = 'http://localhost:63342/facebook/index.php?logout=true';
//4. if fb sess exists echo name
if (isset($sess)) {
    //store the token in the php session
    $_SESSION['fb_token'] = $sess->getToken();
    //create request object,execute and capture response
    $request = new FacebookRequest($sess, 'GET', '/me');
    // from response get graph object
예제 #26
0
 private function getSession()
 {
     $helper = $this->getHelper();
     if (isset($_SESSION) && isset($_SESSION['fb_token'])) {
         $session = new FacebookSession($_SESSION['fb_token']);
         try {
             if (!$session->validate()) {
                 $session = null;
             }
         } catch (Exception $e) {
             $session = null;
         }
     }
     if (!isset($session) || $session === null) {
         try {
             $session = $helper->getSessionFromRedirect();
         } catch (FacebookRequestException $ex) {
             print_r($ex);
         } catch (Exception $ex) {
             print_r($ex);
         }
     }
     return $session;
 }
예제 #27
0
 public static function userRegister($params)
 {
     $loger = new CLoger('register');
     if (!$params["NAME"]) {
         $params["NAME"] = $params["LOGIN"];
     }
     if ($params["EXTERNAL_AUTH_ID"] == "socservices") {
         CModule::IncludeModule("socialservices");
         if (strpos($params["PERSONAL_WWW"], "://twitter.com/") !== false) {
             $serv_name = "twitter";
             $appID = trim(self::GetOption("twitter_key"));
             $appSecret = trim(self::GetOption("twitter_secret"));
         } elseif (strpos($params["PERSONAL_WWW"], "://www.facebook.com/") !== false) {
             require_once FACEBOOK_SDK_V4_SRC_AUTOLOAD;
             $serv_name = "facebook";
             $appID = trim(CSocServFacebook::GetOption("facebook_appid"));
             $appSecret = trim(CSocServFacebook::GetOption("facebook_appsecret"));
             echo FACEBOOK_SDK_V4_SRC_AUTOLOAD;
             FacebookSession::setDefaultApplication($appID, $appSecret);
             $session = new FacebookSession($params["OATOKEN"]);
             $session->validate();
             $fbreq = new Facebook\FacebookRequest($session, 'GET', '/me', array("fields" => "token_for_business,link,email,name"));
             $token_for_business = $fbreq->execute()->getGraphObject(GraphUser::className())->getProperty('token_for_business');
             $social_info = '{"' . $serv_name . '": {"social_app_id": "' . $appID . '", "social_id": "' . $params["XML_ID"] . '","token_for_business":"' . $token_for_business . '"}}';
             //$loger->Add('social_info'.$social_info);
         } elseif (strpos($params["PERSONAL_WWW"], "://vk.com/") !== false) {
             $serv_name = "vkontakte";
             $appID = trim(CSocServVKontakte::GetOption("vkontakte_appid"));
             $appSecret = trim(CSocServVKontakte::GetOption("vkontakte_appsecret"));
         } elseif (strpos($params["PERSONAL_WWW"], "://odnoklassniki.ru/") !== false) {
             $serv_name = "odnoklassniki";
             $appID = trim(self::GetOption("odnoklassniki_appid"));
             $appSecret = trim(self::GetOption("odnoklassniki_appsecret"));
             $appKey = trim(self::GetOption("odnoklassniki_appkey"));
         }
         $params_vm = array("authorization" => "true", "name" => $params["NAME"], "social_info" => '{"' . $serv_name . '": {"social_app_id": "' . $appID . '", "social_id": "' . $params["XML_ID"] . '"}}');
         if ($social_info) {
             $params_vm["social_info"] = $social_info;
         }
     } else {
         $params_vm = array("authorization" => "true", "name" => $params["NAME"], "email" => $params["EMAIL"], "password" => $params["CONFIRM_PASSWORD"]);
     }
     $loger->Add('q', $params_vm);
     return self::getInstance()->buildRequest("register_user", $params_vm, 'json', 'post');
 }
 private function _getFacebookSessionFromCode()
 {
     try {
         $session = new FacebookSession(Input::get('code'));
         $session->validate();
         return $session;
     } catch (FacebookRequestException $ex) {
         // When Facebook returns an error
         //if (APPLICATION_ENV=="dev") {
         Log::error($ex->getMessage());
         //}
         return false;
     } catch (\Exception $ex) {
         // When validation fails or other local issues
         if (App::environment('dev')) {
             Log::error($ex->getMessage());
         }
         return false;
     }
 }
예제 #29
0
function validToken($token)
{
    FacebookSession::setDefaultApplication('399558776852663', '240b7a471130f9c9cc75dbcd634933b3');
    // If you already have a valid access token:
    $session = new FacebookSession($token);
    // To validate the session:
    try {
        $session->validate();
        return true;
    } catch (FacebookRequestException $ex) {
        // Session not valid, Graph API returned an exception with the reason.
        //echo $ex->getMessage();
        return false;
    } catch (\Exception $ex) {
        // Graph API returned info, but it may mismatch the current app or have expired.
        //echo $ex->getMessage();
        return false;
    }
}