PHP code example of contributte / facebook

1. Go to this page and download the library: Download contributte/facebook library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

contributte / facebook example snippets


namespace App\Presenters;

use Contributte\Facebook\Exceptions\FacebookLoginException;
use Contributte\Facebook\FacebookLogin;
use Nette\Application\Responses\RedirectResponse;
use Nette\Application\UI\Presenter;
use Nette\Security\AuthenticationException;

final class SignPresenter extends Presenter
{

	/** @var FacebookLogin @inject */
	public $facebookLogin;

	public function actionFacebook()
	{
		// Redirect to FB and ask customer to grant access to his account
		$url = $this->facebookLogin->getLoginUrl($this->link('//facebookAuthorize'), ['email', 'public_profile']);
		$this->sendResponse(new RedirectResponse($url));
	}

	/**
	 * Log in user with accessToken obtained after redirected from FB
	 *
	 * @return void
	 */
	public function actionFacebookAuthorize()
	{
		// Fetch User data from FB and try to login
		try {
			$token = $this->facebookLogin->getAccessToken();

			$this->user->login('facebook', $this->facebookLogin->getMe($token->getValue(), ['first_name', 'last_name', 'email', 'gender']));
			$this->flashMessage('Login successful :-).', 'success');
		} catch (FacebookLoginException | AuthenticationException $e) {
			$this->flashMessage('Login failed. :-( Try again.', 'danger');
		}
	}

}


/**
 * Log in user with accessToken from cookie/session after javascript authorization
 */
public function actionFacebookCookie()
{
	// Fetch User data from FB and try to login
	try {
		$token = $this->facebookLogin->getAccessTokenFromCookie();

		$this->user->login('facebook', $this->facebookLogin->getMe($token, ['first_name', 'last_name', 'email', 'gender']));
		$this->flashMessage('Login successful :-).', 'success');
	} catch (FacebookLoginException | AuthenticationException $e) {
		$this->flashMessage('Login failed. :-( Try again.', 'danger');
	}
}