google-api-php-client
Client ID と Client secret と Redirect URIs が必要です ( APIs Console )
3つ目は、アプリケーションの認証画面ですが、Google のアカウントに登録されます。解除は アカウントページから以下のリンクで一覧が表示されるので削除して下さい。
アカウント権限
Google の解説ページのサンプルが古いからかなんなのか全く動作しないので整理しました。
▼ テストコード( examples/idtoken.php をベースを変更しています )
<?php
/*
* Copyright 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
include_once "templates/base.php";
session_start();
header( "Content-Type: text/html; Charset=utf-8" );
header( "pragma: no-cache" );
header( "Expires: Wed, 31 May 2000 14:59:58 GMT" );
header( "Cache-control: no-cache" );
require_once realpath(dirname(__FILE__) . '/../autoload.php');
$client_id = 'YOUR_CLIENT_ID';
$client_secret = 'YOUR_CLIENT_SECRET';
$redirect_uri = 'YOUR_REDIRECT_URI';
$client = new Google_Client();
$client->setClientId($client_id);
$client->setClientSecret($client_secret);
$client->setRedirectUri($redirect_uri);
$client->setScopes('https://www.googleapis.com/auth/drive');
/************************************************
If we're logging out we just need to clear our
local access token in this case
************************************************/
if (isset($_REQUEST['logout'])) {
unset($_SESSION['access_token']);
}
/************************************************
If we have a code back from the OAuth 2.0 flow,
we need to exchange that with the authenticate()
function. We store the resultant access token
bundle in the session, and redirect to ourself.
************************************************/
if (isset($_GET['code'])) {
$client->authenticate($_GET['code']);
$_SESSION['access_token'] = $client->getAccessToken();
$redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
}
/************************************************
If we have an access token, we can make
requests, else we generate an authentication URL.
************************************************/
if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
$client->setAccessToken($_SESSION['access_token']);
} else {
$authUrl = $client->createAuthUrl();
}
/************************************************
If we're signed in we can go ahead and retrieve
the ID token, which is part of the bundle of
data that is exchange in the authenticate step
- we only need to do a network call if we have
to retrieve the Google certificate to verify it,
and that can be cached.
************************************************/
if ($client->getAccessToken()) {
$_SESSION['access_token'] = $client->getAccessToken();
// $token_data = $client->verifyIdToken()->getAttributes();
}
echo pageHeader("User Query - Retrieving An Id Token");
?>
<div class="box" style='width:100%'>
<div class="request">
<?php
// 接続用リンク
if (isset($authUrl)) {
echo "<a class='login' href='" . $authUrl . "'>Connect Me!</a>";
}
// ログアウト用リンク
else {
echo "<a class='logout' href='?logout'>Logout</a>";
}
?>
</div>
<pre class="data">
<?php
if ( isset($_SESSION['access_token']) ) {
print "セッションの内容\n";
print_r($_SESSION);
// 内容が JSON なのでデコード
$obj = json_decode($_SESSION['access_token']);
print "JSON の内容\n";
print_r($obj);
print "アクセストークン\n";
print "{$obj->{'access_token'}}\n";
$dr_service = new Google_Service_Drive($client);
// とりあえず 10 エントリを取得して検証可能なファイルを探す
$dr_results = $dr_service->files->listFiles(array('maxResults' => 10));
// ファイルのインスタンスの配列を取得
$files = $dr_results->getItems();
// ダウンロード用 URL
// URL から curl でダウンロードも可
$downloadUrl = $files[5]->getDownloadUrl();
// URL を取得できた場合、API を使ってダウンロードプロセスを作成する
if ($downloadUrl) {
// リクエストオブジェクト
$request = new Google_Http_Request($downloadUrl, 'GET', array("Authorization" => "Bearer {$obj->{'access_token'}}"), null);
// ストリームを使ってデータを取得
$httpRequest = $client->getIo()->executeRequest($request);
// $httpRequest は、3つの配列で作成されており、データ / ヘッダ情報 / ステータスコード
print "[0] がデータ\n";
print_r($httpRequest);
}
}
?>
</pre>
</div>
YOUR_REDIRECT_URI は、このソースコードの URL である必要がありますが、localhost で動作します。
autoload.php の読み込みによって、クラスのライブラリは自動的に require_once されます。
前半は、お決まりのアクセストークンを取得する為のプロセスです。
$client->verifyIdToken()->getAttributes() はエラーとなるのでコメントにしています。
$files[5] を使っているのは、内容を確認するのに都合が良いものを選びました。
ダウンロード URL が解れば、Google のクラスを使用しなくても curl で十分可能です。
スコープは https://www.googleapis.com/auth/drive を使用していますが、何でもかんでも取得するので内容のチェックが重要です。
関連する記事