JREAM
1/22/2014 - 6:11 AM

Example of PhalconPHP with Facebook SDK login using PHP.

Example of PhalconPHP with Facebook SDK login using PHP.

composer.json
-------------
{
    "require": {
        "facebook/php-sdk" : "*"
    }
}


Phalcon Bootstrap index.php
---------------------------
<?php

    $di->setShared('facebook', function() use ($api) {
        return new \Facebook([
            'appId'     => $api->fb->appId,
            'secret'    => $api->fb->secret,
        ]);
    });
    
?>

Your Controller Method:
---------------------
<?php
    /**
     * Logs a user in via facebook
     *
     * @return void
     */
    const REDIRECT_FAILURE = 'login';
    const REDIRECT_SUCCESS = 'dashboard';
        
    public function doFacebookAction()
    {
        $facebookId = $this->facebook->getUser();

        if (!$facebookId)
        {
            $this->flash->error("Invalid Facebook Call.");
            return $this->response->redirect(self::REDIRECT_FAILURE);
        }

        try{
            $facebookUser = $this->facebook->api('/me');
        } catch (\FacebookApiException $e) {
            $this->flash->error("Could not fetch your facebook user.");
            return $this->response->redirect(self::REDIRECT_FAILURE);
        }

        $user = \User::findFirstByFacebookId($facebookId);
        if (!$user) {
            // Save user record in database
            $user = new \User();
            $user->facebook_id = $facebookUser['id'];
            $user->create();

            if ($user->getMessages()) {
                $error = new \Error();
                $error->content = "Error creating facebook user with id {$facebookUser['id']}";
                $this->flash->error('There was an error connecting your facebook user.');
                return $this->response->redirect(self::REDIRECT_FAILURE);
            }
        }

        // This is how I create a Session, do it your own way
        $this->component->user->createSession($user, [
            'facebook_id' => $facebookId,
            'facebook_logout_url' => $this->facebook->getLogoutUrl()
        ]);
        return $this->response->redirect(self::REDIRECT_SUCCESS);
    }
    
?>

Logging Out (In arbitrary controller)
-------------------------------------
<?php

    public function logout() {
        $this->session->destroy();
        $this->facebook->destroySession();
        $this->facebook->setAccessToken('');
        return $this->response->redirect($this->facebook->getLogoutUrl(), true);      
    }
?>