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じゃないとエラー吐くようです
jsのfetchをphpで受け取る
この記事はMojirageアドベントカレンダーの18日目の記事です。
matatsuna.hatenablog.com
PHPからgyazo APIを叩いてアップロード
この記事はMojirageアドベントカレンダーの17日目の記事です。
matatsuna.hatenablog.com
gyazo
gyazoはスクリーンショットを共有するためのサービスです
gyazo.com
APIでプログラムからアップロードすることもできます
https://gyazo.com/api/docs/image
PHPからアップロード
とりあえず試して動いた方法を紹介します
HTTP_Requestを取得
http://pear.php.net/package/HTTP_Request/download/1.4.4/
インストール出来なければ、直接zipをダウンロードしてプログラム以下において呼び出してもいけます
<?php require('HTTP_Request-1.4.4/Request.php'); // $imgはgyazoにアップロードしたい画像ファイル file_put_contents('gyazo.png', $img); $post_data = array( 'access_token' => $token, 'title' => $title, 'desc' => $desc ); // アップロードパラメータ $upload_file = array( 'name' => 'imagedata', 'path' => __DIR__.'/gyazo.png' ); // アップロード $POST_URL = 'https://upload.gyazo.com/api/upload'; $rs = http_send($POST_URL, $post_data, $upload_file); function http_send($url, $params, $upload_file = null) { $req = new HTTP_Request(); $req->setMethod(HTTP_REQUEST_METHOD_POST); foreach ($params as $key => $val) { $req->addPostData($key, $val); } $req->setURL($url); if ($upload_file) { $res = $req->addFile($upload_file["name"], $upload_file["path"]); if (PEAR::isError($res)) { echo $res->getMessage(); exit; } } if (!PEAR::isError($req->sendRequest())) { return $req->getResponseBody(); } else { return false; } }
この方法では書き込み権限が必要なのでchmod叩く必要があるかもです
base64でアップロードできたら楽なんですけどね...