PHPでGoogleログイン機能

この記事はMojirageアドベントカレンダーの19日目の記事です。
matatsuna.hatenablog.com

Googleログイン機能

よくWebサービスであるgoogleのログインの実装の仕方です
gyazo.com

Google consoleでkeyを発行する

https://console.cloud.google.com/?hl=ja
APIとサービス」の認証情報を作成すれば、クライアントIDが取得できます
制限などはお好きに
今回はGmailのアドレスとユーザー名を取得するだけなので特別なAPIの有効化はいりません

indexとcallback

index.php

<?php
$AUTH_URL = 'https://accounts.google.com/o/oauth2/auth';
$params = array(
  'client_id' => $CONSUMER_KEY,
  'redirect_uri' => 'http://~~~~~~~~~~~~~~~~~~~~~~~/callback.php',
  'scope' => 'profile email',
  'response_type' => 'code',
  'access_type' => 'offline'
);
header("Location: " . $AUTH_URL. '?' . http_build_query($params));

callback.php

<?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' => 'http://~~~~~~~~~~~~~~~~~~~~~~~~/callback.php',
    'client_id' => $CONSUMER_KEY,
    'client_secret' => $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'])) {
    echo 'エラー発生';
    exit;
}
$access_token = $token['access_token'];
$params = array('access_token' => $access_token);
$res = file_get_contents($INFO_URL . '?' . http_build_query($params));
$res = json_decode($res, true);
var_dump($res);
//    $res["email"] email
//    $res["name"] ユーザー名

これで取得できます
ただし、ローカル環境でする場合127.0.0.1ではなくてlocalhostじゃないとエラー吐くようです