【Laravel】Facebookログインを実装する方法
LaravelにFacebookログインを実装する方法をまとめました。「Laravelってなに?」って人は以下の記事あわせてご覧ください。
» 【アメリカで人気なPHPフレームワーク】Laravelの使い方メモ
記事の内容
- Facebook SDKをLaravelにインストールする方法
- Facebookログインボタンを実装して、プロフィール情報を表示する方法
- FacebookとLaravelを繋いで、FacebookのプロフィールデータをDBに保存する方法
LaravelでFacebookログインするアプリケーションの仕様
【1】『Facebookログインボタン』をおすとFacebookのユーザー認証が表示される。
【2】ユーザー認証が通った場合、ユーザーはLaravelのアプリケーションにリダイレクトされ、ユーザーデータはLaravelにわたされる。
【3】ユーザーデータを使って、ユーザー情報が表示される。それと同時に、ユーザー情報がDBに保存される。
完成版のイメージは以下。
Facebookログイン後に以下のように表示されます。
では、さっそくまとめてきます。
Laravelをインストール
$ composer create-project laravel/laravel laravel-facebook-login --prefer-dist
FacebookSDKをインストール
$ cd laravel-facebook-login/
$ composer require facebook/php-sdk
Facebookアプリの作成
以下のリンクから作成してください。
Facebookアプリの作成( ◜◡‾)
configファイルの作成
新規作成ファイル:app/config/facebook.php
<?php
return array(
'appId' => '[app_id]',
'secret' => '[app_secret]'
);
DBの作成
マイグレーションします。
$ php artisan migrate:make create_users_table
$ php artisan migrate:make create_profiles_table
生成されたファイルを以下のように編集します。
編集ファイル:app/database/migration/create_users_table.php
public function up()
{
Schema::create('users', function($table)
{
$table->increments('id');
$table->string('email')->unique();
$table->string('photo');
$table->string('name');
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
public function down()
{
Schema::drop('users');
}
編集ファイル:app/database/migration/create_profiles_table.php
public function up()
{
Schema::create('profiles', function($table)
{
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->string('username');
$table->biginteger('uid')->unsigned();
$table->string('access_token');
$table->string('access_token_secret');
$table->timestamps();
});
}
public function down()
{
Schema::drop('profiles');
}
つぎに、DBを作成し、configファイルに情報を記入します。
編集ファイル:app/config/database.php
'mysql' => array(
'driver' => 'mysql',
'host' => 'localhost',
'database' => 'fblogin_laravel',
'username' => 'root',
'password' => 'root',
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
),
モデルの作成
まずはProfileモデルを作成します。
新規作成ファイル:app/models/People.php
<?php
class Profile extends Eloquent {
public function user(){
return $this->belongsTo('User');
}
}
次にUserモデルを作成します。
編集ファイル:app/models/User.php
public function profiles(){
return $this->hasMany('Profile');
}
ルーティングの設定
編集ファイル:app.routes.php
Route::get('login/fb', function() {
$facebook = new Facebook(Config::get('facebook'));
$params = array(
'redirect_uri' => url('/login/fb/callback'),
'scope' => 'email',
);
return Redirect::to($facebook->getLoginUrl($params));
});
つぎに、コールバックの設定をします。
※取得した情報をデバッグします。
Route::get('login/fb/callback', function() {
$code = Input::get('code');
if (strlen($code) == 0) return Redirect::to('/')->with('message', 'Facebookとの接続でエラーが発生しました。');
$facebook = new Facebook(Config::get('facebook'));
$uid = $facebook->getUser();
if ($uid == 0) return Redirect::to('/')->with('message', 'エラーが発生しました。');
$me = $facebook->api('/me');
// 取得した情報のデバッグ
dd($me);
});
完成版のスクリプトがこちら
Route::get('login/fb/callback', function() {
$code = Input::get('code');
if (strlen($code) == 0) return Redirect::to('/')->with('message', 'Facebookとの接続でエラーが発生しました。');
$facebook = new Facebook(Config::get('facebook'));
$uid = $facebook->getUser();
if ($uid == 0) return Redirect::to('/')->with('message', 'エラーが発生しました。');
$me = $facebook->api('/me');
$profile = Profile::whereUid($uid)->first();
if (empty($profile)) {
$user = new User;
$user->name = $me['first_name'].' '.$me['last_name'];
$user->email = $me['email'];
$user->photo = 'https://graph.facebook.com/'.$me['username'].'/picture?type=large';
$user->save();
$profile = new Profile();
$profile->uid = $uid;
$profile->username = $me['username'];
$profile = $user->profiles()->save($profile);
}
$profile->access_token = $facebook->getAccessToken();
$profile->save();
$user = $profile->user;
Auth::login($user);
return Redirect::to('/')->with('message', 'Facebookログインしました');
});
以上で完成ですが、ログイン後のリダイレクト先も一応つくっておきます。
Route::get('/', function()
{
$data = array();
if (Auth::check()) {
$data = Auth::user();
}
return View::make('user', array('data'=>$data));
});
Route::get('logout', function() {
Auth::logout();
return Redirect::to('/');
});
最後にビューをつくります。
@if(Session::has('message'))
{{ Session::get('message')}}
@endif
<br>
@if (!empty($data))
こんにちは, {{{ $data['name'] }}}
<img src="{{ $data['photo']}}">
<br>
メールアドレス:{{ $data['email']}}
<br>
<a href="logout">ログアウト</a>
@else
Facebookログインしますか?⇒<a href="login/fb">Facebookログイン</a>?
@endif
以上となります( ◜◡‾)参考になれば幸いです。
参考記事
» Integrating Facebook Login into Laravel application – Maks Surguy’s blog on PHP and Laravel