googleアカウントによるログイン機能の実装について紹介します。
通常のログイン画面にグーグルアカウント連携ボタンを追加しました。
GCPへの登録やグーグルAPIの勉強から、既存のDBへの書き込み作業等のデバッグでかなり苦労したので、メモ書きとして記録しておきます。
1.事前準備(GCPの登録)
まずGoogle Cloud Platformのページで左上の「Project」よりプロジェクトを作成を選択します。そのあと「OAuth同意画⾯の設定」に進み、「クライアントID」、「クライアントシークレット」、「URI」を設定します。
詳細は以下リンクを参照ください。
https://qiita.com/kmtym1998/items/768212fe92dbaa384c27
2.composerのインストール
※composerをインストールしておく必要があるので、composerの事前知識がない人は詳細を確認してください。1行目のコマンド(require '../../vendor/autoload.php'; )がgoogleAPIを読み込んでいて、今回のアカウント連携機能に必要になります。
サーバー環境に接続して以下のコマンドを入力します。
(サーバーやローカル環境の接続方法は各自確認ください。)
php composer.phar require google/apiclient
これで事前準備は完了です。
3.redirect.phpの作成
つづいて、実装していきます。
作成するファイルは1つです。
<?php
require '../../vendor/autoload.php';
session_start();
// init configuration
$clientID = '***************************.apps.googleusercontent.com';
$clientSecret = '*************************_';
$redirectUri = '******************/redirect.php';
// create Client Request to access Google API
$client = new Google_Client();
$client->setClientId($clientID);
$client->setClientSecret($clientSecret);
$client->setRedirectUri($redirectUri);
$client->addScope("email");
$client->addScope("profile");
if (isset($_GET['code'])) {
$token = $client->fetchAccessTokenWithAuthCode($_GET['code']);
$client->setAccessToken($token['access_token']);
// get profile info
$google_oauth = new Google_Service_Oauth2($client);
$google_account_info = $google_oauth->userinfo->get();
$email = $google_account_info->email;
$name = $google_account_info->name;
/* now you can get mail and account information*/
require_once("db.php");
$dbh = db_connect(); /* this is connection to exsiting MySQL*/
try {
$statement = $dbh->prepare("SELECT * FROM {$tablename1} WHERE mail= :email and account= :account");
$statement->bindParam( ':email',$email, PDO::PARAM_STR);
$statement->bindParam( ':account',$name, PDO::PARAM_STR);
$statement->execute();
$count = $statement->rowCount();
/* CHECK EMAIL AND NAME IN DATABASE */
if ($count){
$_SESSION["NAME"] = $name;
}else{
/* INSERT USER TO DATABASE */
$statement = $dbh->prepare("INSERT INTO {$tablename1} (account,mail) VALUES (:account,:mail)");
$statement->bindValue(':account', $name, PDO::PARAM_STR);
$statement->bindValue(':mail', $email, PDO::PARAM_STR);
$statement->execute();
$_SESSION["NAME"] = $name;
$dbh->commit();
$dbh = null;
}
} catch (PDOException $e) {
$errors['database'] = 'データベースエラー';
echo $e->getMessage();
}
$_SESSION["NAME"] = $name;
$move="******************************" ;
header("Location: $move"); /* move to redirect page */
}
?>
<html lang="en">
<body>
<p><?php echo "<a href='".$client->createAuthUrl()."'>Google Login</a>" ?></p>
</body>
</html>
解説します。
$clientID = '***************************.apps.googleusercontent.com';
$clientSecret = '*************************_';
$redirectUri = '******************/redirect.php';
この部分でGCPで設定した項目を入力してください。
$redirectUri部分は、移動したいサイトのアドレスを入力するのが本来の使い方のようですが、どうもそれをすると、アカウント情報を処理する前にサイト移動してしまうので、ここでは同じページ(redirect.php)を指定しています。
require_once("db.php");
$dbh = db_connect(); /* this is connection to exsiting MySQL*/
この部分はMySQLへ接続するためのコードです。
/* CHECK EMAIL AND NAME IN DATABASE */
if ($count){
$_SESSION["NAME"] = $name;
}
この部分で既存のアカウントかどうかを判別しています。
既存のアカウントであれば、そのままログインします。
else{
/* INSERT USER TO DATABASE */
$statement = $dbh->prepare("INSERT INTO {$tablename1} (account,mail) VALUES (:account,:mail)");
$statement->bindValue(':account', $name, PDO::PARAM_STR);
$statement->bindValue(':mail', $email, PDO::PARAM_STR);
$statement->execute();
既存アカウントでない場合は、この部分でMySQLにアカウント登録しています。
$_SESSION["NAME"] = $name;
$move="******************************" ;
header("Location: $move"); /* move to redirect page */
最後に、この部分でページ移動しています。
$move=の部分に移動先のページ(https:// )を記載します。
実際に作ったページがこちらです。
https://estacionsuzuki.com/engineering/community/login/index.php