Go to the [https://developers.facebook.com/](https://developers.facebook.com/) and create your app.
Click Add product
and choose Facebook Login
Before install this extension, you must install yii2-app. In this example, I use yii2-basic template. Guide for installation in here.
Run
composer require --prefer-dist yiisoft/yii2-authclient
or add
"yiisoft/yii2-authclient": "~2.1.0"
to the require
section of your composer.json
.
Add config authClientCollection
to your config components
:
return [
'components' => [
'authClientCollection' => [
'class' => 'yii\authclient\Collection',
'clients' => [
'facebook' => [
'class' => 'yii\authclient\clients\Facebook',
'clientId' => 'facebook_client_id',
'clientSecret' => 'facebook_client_secret',
],
],
]
],
// ...
];
facebook_client_id
is application id and facebook_client_secret
is app secret.
Login as facebook account
to your login view:Edit site/login.php
in views folder, add theses line to content of page login:
<?= yii\authclient\widgets\AuthChoice::widget([ 'baseAuthUrl' => ['site/auth'], 'popupMode' => false, ]) ?>
Above, we set that auth
action in SiteController
will handler OAuth2 flow.
Now we create it.
class SiteController extends Controller
{
public function actions()
{
return [
'auth' => [
'class' => 'yii\authclient\AuthAction',
'successCallback' => [$this, 'onAuthSuccess'],
],
];
}
public function onAuthSuccess($client)
{
// do many stuff here, save user info to your app database
}
}
We use yii\authclient\AuthAction
for create url and redirect to facebook login page.
Function onAuthSuccess
used to get user info, login to your app.
/**
* @param $client ClientInterface
*/
public function onAuthSuccess($client)
{
//Get user info
/** @var array $attributes */
$attributes = $client->getUserAttributes();
$email = ArrayHelper::getValue($attributes, 'email'); //email info
$id = ArrayHelper::getValue($attributes, 'id'); // id facebook user
$name = ArrayHelper::getValue($attributes, 'name'); // name facebook account
//Login user
//For demo, I will login with admin/admin default account
$admin = User::findByUsername('admin');
Yii::$app->user->login($admin);
}