・共通(google.phpとする)
define('GG_CONSUMER_KEY', '(googleから取得)');
define('GG_CONSUMER_SECRET', '(googleから取得)');
define('GG_AUTHURL', 'https://accounts.google.com/o/oauth2/auth');
define('GG_CALLBACK', '(自分のCALLBACK)');
・呼び出し
session_start();
require_once('google.php');
$google_t = array(
'client_id' => GG_CONSUMER_KEY,
'redirect_uri' => GG_CALLBACK,
'scope' => 'profile email',
'response_type' => 'code',
'access_type' => 'offline'
);
$gg_link = GG_AUTHURL .'?'. http_build_query($google_t);
<a href="<?= htmlspecialchars($gg_link); ?>">google login</a>
・CALLBACK
session_start();
require_once('google.php');
$TOKEN_URL = 'https://accounts.google.com/o/oauth2/token';
$INFO_URL = 'https://www.googleapis.com/oauth2/v1/userinfo';
$APP_URL = $_GET["state"];
$params = array(
'code' => $_GET['code'],
'grant_type' => 'authorization_code',
'redirect_uri' => GG_CALLBACK,
'client_id' => GG_CONSUMER_KEY,
'client_secret' => GG_CONSUMER_SECRET,
);
$options = array('http' => array(
'method' => 'POST',
'content' => http_build_query($params))
);
$res = file_get_contents($TOKEN_URL, false, stream_context_create($options));
$token = json_decode($res, true);
if (isset($token['error'])) {
// エラー処理
// どっかへ戻る。
}
$access_token = $token['access_token'];
$params = array('access_token' => $access_token);
$profile = file_get_contents($INFO_URL . '?' . http_build_query($params));
$profile = json_decode($profile, true);
if (isset($profile['id']) && isset($profile['email'])) {
// 成功
// id, name, emailを書き込もう。
// どっかへ戻る。
}
else {
// エラー処理
// どっかへ戻る。
}
google login