新手 Google Drive API (PHP) 混淆 - 使用什么指南/库? [英] Newbie Google Drive API (PHP) confusion - what guide/library to use?

查看:21
本文介绍了新手 Google Drive API (PHP) 混淆 - 使用什么指南/库?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个移动网站 m.example.com - 我希望访问者通过手机从 Google 云端硬盘中选择一个文件,然后将其发送到托管 m.example.com 的服务器.基本上模拟一个简单的 文件上传,就像在桌面上一样.

据我了解,工作流程如下:

1) 用户使用 Picker 选择文件,它将所选文件的元数据发送到我的网站客户端(即在手机/平板电脑上运行的 HTML/Javascript)

2) 我通过 ajax 或只是表单隐藏字段将其发送到我的服务器

3) 我的服务器向 Google API 发出请求以获取文件,然后将其存储在服务器的文件系统中

所以我需要帮助:

a) 以上步骤是否正确,是否还有其他方法可以做到这一点,或者我可以使用一种服务来让我的站点用户从多个云存储提供商之一中选择他们的文件?

a) 假设我的步骤是正确的,这是唯一的方法,我被困在 3) 部分 - 服务器与 API 通信.

到目前为止,我已经按照此处使用了选择器 - 并在 google-api 的根目录中创建了 drive_rest_api_step_3.php(如屏幕截图所示)

得到 致命错误:require_once(): 在/path/to/google-api/中打开所需的 'src/Google_Client.php' (include_path='.:/usr/local/lib/php') 失败drive_rest_api_step_3.php 第 5 行

库中没有 Google_Client.php,但有src/Google/Client.php,所以我编辑了 require_once 以使用它.

现在得到 Failed opening required 'src/contrib/Google_DriveService.php' - 再次搜索该文件没有结果,但是有一个 src/Google/Service/Drive.php, 所以编辑示例以使用它:

需要(在 https://developers.google.com/drive/web/quickstart/quickstart-php#step_3_set_up_the_sample) 是:

require_once 'google-api-php-client/src/Google_Client.php';require_once 'google-api-php-client/src/contrib/Google_DriveService.php';

现在:

require_once 'src/Google/Client.php';require_once 'src/Google/Service/Drive.php';

现在收到致命错误:在第 32 行的/path/to/google-api/src/Google/Service/Drive.php 中找不到Google_Service"类

所以这就是为什么我认为这两套指南存在问题,要么它们使用不同的库,要么 https://developers.google.com/drive/web/quickstart/quickstart-php#step_3_set_up_the_sample 已过时,尽管说上次更新时间为 3 月 30 日,2015 年.

解决方案

您说得对,驱动器快速入门指南已经过时,它指的是 Google Code 上的旧版 Google 的 PHP 客户端 API 库,而不是GitHub 上较新的一个.因此,快速入门指南不适用于您下载的 PHP 客户端库.此外,快速入门指南代码旨在在 PHP 命令行模式下执行,而不是在服务器上执行.

为了回答这个问题,我提供了几个子答案:

  1. 如何使用 PHP 客户端库
  2. 如何使用 Google Picker 选择文件并将文件传送到服务器

将 Google PHP 客户端库与 Google Drive API 结合使用

试试这个页面:https://developers.google.com/api-client-library/php/auth/web-app,其中有一个示例展示了如何使用 PHP 库列出用户 Google Drive 上的文件,包括整个 OAuth 程序.

不幸的是,即使这样也有点过时(包含路径已经过时,现在已弃用).因此(为了 StackOverflow 的完整性)这里有一些代码.我在我的 Web 服务器根目录中使用了一个子目录 drivetest;根据需要更改网址.

请注意,您需要在 Google 的开发者控制台中获取Web 应用程序"的客户端 ID,并下载 JSON(根据需要替换代码中的 client_secrets.json).

drivetest/quickstart.php

setAuthConfigFile('client_secrets.json');$client->addScope(Google_Service_Drive::DRIVE_METADATA_READONLY);如果 (isset($_SESSION['access_token']) && $_SESSION['access_token']) {$client->setAccessToken($_SESSION['access_token']);$drive_service = new Google_Service_Drive($client);$files_list = $drive_service->files->listFiles(array())->getItems();回声 json_encode($files_list);} 别的 {$redirect_uri = 'http://localhost/drivetest/oauth2callback.php';header('位置:' .filter_var($redirect_uri, FILTER_SANITIZE_URL));}?>

drivetest/oauth2callback.php

setAuthConfigFile('client_secrets.json');$client->setRedirectUri('http://localhost/drivetest/oauth2callback.php');$client->addScope(Google_Service_Drive::DRIVE_METADATA_READONLY);if (!isset($_GET['code'])) {$auth_url = $client->createAuthUrl();header('位置:' .filter_var($auth_url, FILTER_SANITIZE_URL));} 别的 {$client->authenticate($_GET['code']);$_SESSION['access_token'] = $client->getAccessToken();$redirect_uri = 'http://localhost/drivetest/quickstart.php';header('位置:' .filter_var($redirect_uri, FILTER_SANITIZE_URL));}?>

使用 Google 文件选取器选取文件

对于您的用例,您最好使用 Google Picker https://developers.google.com/picker/docs/ 它为您实现了整个浏览和选择文件的功能,并且只为文件提供了一个 ID.所需步骤的摘要:

  1. 获取访问令牌(身份验证)
  2. 使用选择器让用户选择文件
  3. 使用选择器返回的文件 ID 获取下载 URL
  4. 从下载地址下载文件

我们可以通过两种方式(客户端或服务器端)做到这一点:

方法一:客户端

使用这种方法,步骤1-3在Javascript中完成,只有步骤4在PHP中完成.使用这种方法,我们甚至不需要 PHP 客户端库!

这是一个示例(改编自上述链接中的示例代码和 http://webdevrefinery.com/forums/topic/12931-dropbox-google-drive-file-pickers/):

picker.html

此文件在页面加载时启动文件选择器并将 URL 放入表单中.

<html xmlns="http://www.w3.org/1999/xhtml"><头><meta http-equiv="content-type" content="text/html; charset=utf-8"/><title>Google 选择器示例</title><script type="text/javascript">//从 Google Developers Console 获取的浏览器 API 密钥.var developerKey = '';//从 Google Developers Console 获取的客户端 ID.替换为您自己的客户 ID.var clientId = ""//替换为您自己的应用 ID.(它是您客户 ID 中的第一个数字)var appId = ""//用于访问用户的 Drive 项目的范围.var scope = ['https://www.googleapis.com/auth/drive'];var pickerApiLoaded = false;var oauthToken;//使用 Google API Loader 脚本加载 google.picker 脚本.函数 loadPicker() {gapi.load('auth', {'callback': onAuthApiLoad});gapi.load('picker', {'callback': onPickerApiLoad});}函数 onAuthApiLoad() {window.gapi.auth.authorize({'client_id':clientId,范围":范围,'立即':假},handleAuthResult);}函数 onPickerApiLoad() {pickerApiLoaded = true;创建选择器();}函数 handleAuthResult(authResult) {如果 (authResult && !authResult.error) {oauthToken = authResult.access_token;创建选择器();}}//创建并渲染一个 Picker 对象函数 createPicker() {如果(pickerApiLoaded && oauthToken){var view = new google.picker.DocsView();view.setIncludeFolders(true);//view.setMimeTypes("image/png,image/jpeg,image/jpg");var picker = new google.picker.PickerBuilder()//.enableFeature(google.picker.Feature.NAV_HIDDEN)//.enableFeature(google.picker.Feature.MULTISELECT_ENABLED).setAppId(appId).setOAuthToken(oauthToken).addView(视图).setDeveloperKey(developerKey).setCallback(pickerCallback).建造();选择器.setVisible(真);}}//一个简单的回调实现.功能选择器回调(数据){if (data.action == google.picker.Action.PICKED) {var fileId = data.docs[0].id;gapi.client.load('drive', 'v2', function() {var request = gapi.client.drive.files.get({文件 ID:文件 ID});request.execute(processFile);});}}函数处理文件(文件){var token = gapi.auth.getToken();//控制台日志(文件);//console.log(token);document.getElementById("fileurl").value = file.downloadUrl+"&access_token="+token.access_token;}<身体><form action="submit.php" method="post"><label for="fileurl">文件下载地址</label><input type="text" name="fileurl" id="fileurl"><输入类型=提交"></表单><!-- Google API 加载程序脚本.--><script type="text/javascript" src="https://apis.google.com/js/api.js?onload=loadPicker"></script><script type="text/javascript" src="https://apis.google.com/js/client.js"></script></html>

然后我们将表单提交给 PHP 脚本以将文件下载到服务器上.这里的技巧是我们还需要将访问令牌从客户端传递到服务器,因为用户没有在服务器端进行身份验证.令人惊讶的是,您可以简单地附加 access_token 参数来验证文件的下载,如上所示.

submit.php

使用 file_get_contents 或 CURL,具体取决于您的服务器支持的内容.不过,这需要 HTTPS 支持才能正常工作.

更官方的方式(遵循 https://developers.google.com/drive/web/manage-downloads#alternate_method_using_downloadurl) 是使用 Authorization 标头单独发送授权令牌.修改上面的 Javascript 以分别发送下载 URL 和令牌,然后使用类似于下面的代码.如果您想使用 file_get_contents,请参阅 PHP file_get_contents() 和headers 关于如何发送自定义标题.请注意,您需要在标记前有 Bearer 字样!

方法二:服务端(使用PHP)

使用这种方法,第1、3、4步在PHP中完成,只有第2步在Javascript中完成.

quickstart.php

此页面检查会话中是否有访问令牌,如果没有,则重定向用户进行身份验证.如果有,它会显示选择器和一个表单.在picker Javascript代码中,注意使用的oAuthToken是用PHP从服务器获取的!来源:使用 Google Picker 无需登录 Google帐户(使用 OAuth).然后表单向此页面提交 POST 请求并下载文件.

getDownloadUrl();如果($downloadUrl){$request = new Google_Http_Request($downloadUrl, 'GET', null, null);$httpRequest = $service->getClient()->getAuth()->authenticatedRequest($request);如果 ($httpRequest->getResponseHttpCode() == 200) {返回 $httpRequest->getResponseBody();} 别的 {//发生错误.返回空;}} 别的 {//该文件没有存储在 Drive 上的任何内容.返回空;}}$client = new Google_Client();$client->setAuthConfigFile('client_secrets.json');$client->addScope(Google_Service_Drive::DRIVE_READONLY);如果 (isset($_SESSION['access_token']) && $_SESSION['access_token']) {$client->setAccessToken($_SESSION['access_token']);if (isset($_POST['fileid'])){$drive_service = new Google_Service_Drive($client);$file = $drive_service->files->get($_POST['fileid']);$data = downloadFile($drive_service, $file);file_put_contents('temp.jpg', $data);echo "文件上传";出口();}} 别的 {$redirect_uri = 'http://localhost/drivepicker-php/oauth2callback.php';header('位置:' .filter_var($redirect_uri, FILTER_SANITIZE_URL));出口();}?><!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml"><头><meta http-equiv="content-type" content="text/html; charset=utf-8"/><title>Google 选择器示例</title><script type="text/javascript">//从 Google Developers Console 获取的浏览器 API 密钥.var developerKey = '';//替换为您自己的应用 ID.(它是您客户 ID 中的第一个数字)var appId = ""var pickerApiLoaded = false;//使用 Google API Loader 脚本加载 google.picker 脚本.函数 loadPicker() {gapi.load('picker', {'callback': onPickerApiLoad});}函数 onPickerApiLoad() {pickerApiLoaded = true;创建选择器();}//创建并渲染一个 Picker 对象函数 createPicker() {如果(pickerApiLoaded){var view = new google.picker.DocsView();view.setIncludeFolders(true);//view.setMimeTypes("image/png,image/jpeg,image/jpg");var picker = new google.picker.PickerBuilder()//.enableFeature(google.picker.Feature.NAV_HIDDEN)//.enableFeature(google.picker.Feature.MULTISELECT_ENABLED).setAppId(appId).setOAuthToken('<?= json_decode($client->getAccessToken())->access_token;?>').addView(视图).setDeveloperKey(developerKey).setCallback(pickerCallback).建造();选择器.setVisible(真);}}//一个简单的回调实现.功能选择器回调(数据){if (data.action == google.picker.Action.PICKED) {var fileId = data.docs[0].id;document.getElementById("fileid").value = fileId;}}<身体><form action="quickstart.php" method="post"><label for="fileid">文件ID</label><input type="text" name="fileid" id="fileid"><输入类型=提交"></表单><!-- Google API 加载程序脚本.--><script type="text/javascript" src="https://apis.google.com/js/api.js?onload=loadPicker"></script><script type="text/javascript" src="https://apis.google.com/js/client.js"></script></html>

oauth2callback.php

OAuth 回调的帮助文件.

setAuthConfigFile('client_secrets.json');$client->setRedirectUri('http://localhost/drivepicker-php/oauth2callback.php');$client->addScope(Google_Service_Drive::DRIVE_READONLY);if (!isset($_GET['code'])) {$auth_url = $client->createAuthUrl();header('位置:' .filter_var($auth_url, FILTER_SANITIZE_URL));} 别的 {$client->authenticate($_GET['code']);$_SESSION['access_token'] = $client->getAccessToken();$redirect_uri = 'http://localhost/drivepicker-php/quickstart.php';header('位置:' .filter_var($redirect_uri, FILTER_SANITIZE_URL));}?>

I have a mobile site m.example.com - from a phone I want visitors to choose a file from Google Drive, and send it to the server that hosts m.example.com. Essentially emulating a simple <input type="file"> file upload as on a desktop.

From what I understand the workflow is as follows:

1) User picks file with Picker which sends meta data of the chosen file to my website client (i.e. the HTML/Javascript running on the phone/tablet)

2) I send that to my server via ajax or just a form hidden field

3) my server makes a request to the Google API to get the file and then stores it in the server's file system

So I need help on:

a) is the above steps correct, and is there any other way to do this, or even a service I can use that will allow my site users to pick their files from one of several cloud storage providors?

a) assuming my steps are correct and this is the only way, I am stuck on the 3) part - server talking to the API.

So far I've ceated the picker as per here - Google picker auth popup is being blocked and got the file URL. I've not done 2) yet, I'm just manually putting the file URL into my downlaod script for now.

I'm using PHP and the file I'll want to downlaod to my server could be public or private, that depends on the end user.

I'm lost in the API docs (as in man pages, not a google doc) and am confused with https://developers.google.com/api-client-library/php/start/get_started (call this API docs)and https://developers.google.com/drive/web/quickstart/quickstart-php (call this Drive docs) - are these two different APIs?

I followed the links from the API docs and installed the client from here : https://github.com/google/google-api-php-client, but when trying "Step 3: Set up the sample" on the Drive docs I get many errors such as files not found, class not fount etc, so that makes me think therr is two different APIs/Clients being documented here - can someone please point me in the right direction to get started?

UPDATE

I've re installed the PHP client vis the github linked from this https://developers.google.com/api-client-library/php/start/get_started

This is that it looks like:

I ran the simplefileupload.php in the examples directory - worked first time, only had to put in my project details

So went to https://developers.google.com/drive/web/quickstart/quickstart-php#step_3_set_up_the_sample and created drive_rest_api_step_3.php in root of google-api (as shown in screen grab)

Got Fatal error: require_once(): Failed opening required 'src/Google_Client.php' (include_path='.:/usr/local/lib/php') in /path/to/google-api/drive_rest_api_step_3.php on line 5

There is no Google_Client.php in the library, but there is src/Google/Client.php so I edit the require_once to use that.

Now get Failed opening required 'src/contrib/Google_DriveService.php' - again a search for that file yeilds no results, but there is a src/Google/Service/Drive.php, so edit example to use that:

Requires (on https://developers.google.com/drive/web/quickstart/quickstart-php#step_3_set_up_the_sample) was:

require_once 'google-api-php-client/src/Google_Client.php';
require_once 'google-api-php-client/src/contrib/Google_DriveService.php';

Now:

require_once 'src/Google/Client.php';
require_once 'src/Google/Service/Drive.php';

Now getting Fatal error: Class 'Google_Service' not found in /path/to/google-api/src/Google/Service/Drive.php on line 32

So this is why I think there is an issues with the two sets of guides, either they use different libraries, or https://developers.google.com/drive/web/quickstart/quickstart-php#step_3_set_up_the_sample is out of date, even though is says Last updated March 30, 2015.

解决方案

You are right in that the drive quickstart guide is outdated, it refers to the old version of Google's PHP Client API Library that is on Google Code, rather than the newer one on GitHub. Hence the quickstart guide doesn't work with the PHP Client Library you downloaded. In addition, the quickstart guide code is intended to be executed in PHP command-line mode rather than on the server.

To answer the question, I've put in a few sub-answers:

  1. How to use the PHP Client Library
  2. How to pick a file with the Google Picker and get the file onto the server

Using the Google PHP Client Library with the Google Drive API

Try this page instead: https://developers.google.com/api-client-library/php/auth/web-app which has an example showing how to list files on a user's Google Drive using the new PHP library, including the whole OAuth procedure.

Unfortunately, even that is a bit outdated (the include path is outdated and is now deprecated). As such (and for StackOverflow's completeness sake) here's some code. I used a subdirectory drivetest in my web server root; change the URLs as necessary.

Do note that you need to get the client ID for "Web applications" in Google's Developer Console, and download the JSON (replacing the client_secrets.json in the code as necessary).

drivetest/quickstart.php

<?php
    require_once 'google-api-php-client/src/Google/autoload.php';

    session_start();

    $client = new Google_Client();
    $client->setAuthConfigFile('client_secrets.json');
    $client->addScope(Google_Service_Drive::DRIVE_METADATA_READONLY);

    if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
        $client->setAccessToken($_SESSION['access_token']);
        $drive_service = new Google_Service_Drive($client);
        $files_list = $drive_service->files->listFiles(array())->getItems();
        echo json_encode($files_list);
    } else {
        $redirect_uri = 'http://localhost/drivetest/oauth2callback.php';
        header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
    }   

?>

drivetest/oauth2callback.php

<?php
    require_once 'google-api-php-client/src/Google/autoload.php';

    session_start();

    $client = new Google_Client();
    $client->setAuthConfigFile('client_secrets.json');
    $client->setRedirectUri('http://localhost/drivetest/oauth2callback.php');
    $client->addScope(Google_Service_Drive::DRIVE_METADATA_READONLY);

    if (! isset($_GET['code'])) {
        $auth_url = $client->createAuthUrl();
        header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL));
    } else {
        $client->authenticate($_GET['code']);
        $_SESSION['access_token'] = $client->getAccessToken();
        $redirect_uri = 'http://localhost/drivetest/quickstart.php';
        header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
    }

?>

Use the Google File Picker to pick files

For your use case, you are probably better off using the Google Picker https://developers.google.com/picker/docs/ which implements the whole browse-and-select-file thing for you, and just gives an ID to the file. A summary of the steps required:

  1. Get access token (authentication)
  2. Use picker to let user pick file
  3. Use file ID returned from picker to get download URL
  4. Download file from download URL

We can do this in two ways (client-side or server-side):

Method 1: Client-side

Using this method, steps 1 - 3 are done in Javascript, and only step 4 is done in PHP. With this method we don't even need the PHP client library!

Here's an example (adapted from sample code in the above link and http://webdevrefinery.com/forums/topic/12931-dropbox-google-drive-file-pickers/):

picker.html

This file launches the filepicker upon page load and puts the URL into a form.

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
        <title>Google Picker Example</title>


        <script type="text/javascript">

            // The Browser API key obtained from the Google Developers Console.
            var developerKey = '';

            // The Client ID obtained from the Google Developers Console. Replace with your own Client ID.
            var clientId = ""

            // Replace with your own App ID. (Its the first number in your Client ID)
            var appId = ""

            // Scope to use to access user's Drive items.
            var scope = ['https://www.googleapis.com/auth/drive'];

            var pickerApiLoaded = false;
            var oauthToken;

            // Use the Google API Loader script to load the google.picker script.
            function loadPicker() {
                gapi.load('auth', {'callback': onAuthApiLoad});
                gapi.load('picker', {'callback': onPickerApiLoad});
            }

            function onAuthApiLoad() {
                window.gapi.auth.authorize(
                {
                    'client_id': clientId,
                    'scope': scope,
                    'immediate': false
                },
                handleAuthResult);
            }

            function onPickerApiLoad() {
                pickerApiLoaded = true;
                createPicker();
            }

            function handleAuthResult(authResult) {
                if (authResult && !authResult.error) {
                    oauthToken = authResult.access_token;
                    createPicker();
                }
            }

            // Create and render a Picker object
            function createPicker() {
                if (pickerApiLoaded && oauthToken) {                
                    var view = new google.picker.DocsView();
                    view.setIncludeFolders(true);
                    //view.setMimeTypes("image/png,image/jpeg,image/jpg");

                    var picker = new google.picker.PickerBuilder()
                    //.enableFeature(google.picker.Feature.NAV_HIDDEN)
                    //.enableFeature(google.picker.Feature.MULTISELECT_ENABLED)
                    .setAppId(appId)
                    .setOAuthToken(oauthToken)
                    .addView(view)
                    .setDeveloperKey(developerKey)
                    .setCallback(pickerCallback)
                    .build();
                    picker.setVisible(true);
                }
            }

            // A simple callback implementation.
            function pickerCallback(data) {
                if (data.action == google.picker.Action.PICKED) {
                    var fileId = data.docs[0].id;

                    gapi.client.load('drive', 'v2', function() {
                        var request = gapi.client.drive.files.get({
                            fileId: fileId
                        });
                        request.execute(processFile);           
                    });

                }
            }

            function processFile(file) {
                var token = gapi.auth.getToken();
                // console.log(file);
                // console.log(token);
                document.getElementById("fileurl").value = file.downloadUrl+"&access_token="+token.access_token;
            }
        </script>
    </head>
    <body>
        <form action="submit.php" method="post">
            <label for="fileurl">File Download URL</label><input type="text" name="fileurl" id="fileurl">
            <input type="submit">
        </form>

        <!-- The Google API Loader script. -->
        <script type="text/javascript" src="https://apis.google.com/js/api.js?onload=loadPicker"></script>
        <script type="text/javascript" src="https://apis.google.com/js/client.js"></script>
    </body>
</html>

We then submit the form to a PHP script to download the file on the server. The trick here is that we also need to pass the access token from the client to the server, since the user is not authenticated on the server side. Surprisingly, you can simply append the access_token parameter to authenticate the download of the file, as shown above.

submit.php

Use file_get_contents or CURL, depending on what your server supports. HTTPS support is required for this to work though.

<?php

    $filename = 'temp.jpg';

    $ch = curl_init($_POST['fileurl']);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    // Should verify in production!
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    $data = curl_exec($ch);
    //echo 'Curl error: ' . curl_error($ch);
    curl_close($ch);

    file_put_contents($filename, $data);

?>

A more official way (following https://developers.google.com/drive/web/manage-downloads#alternate_method_using_downloadurl) is to send the authorization token separately using the Authorization header. Modify the Javascript above to send the download URL and token separately, then use something like the code below instead. If you want to use file_get_contents, see PHP file_get_contents() and headers on how to send custom headers. Note that you need to have the Bearer word before the token!

<?php

    $filename = 'temp.jpg';

    $ch = curl_init($_POST['fileurl']);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: Bearer '.$_POST['authtoken']));

    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

    $data = curl_exec($ch);
    echo 'Curl error: ' . curl_error($ch);
    curl_close($ch);

    file_put_contents($filename, $data);

?>

Method 2: Server-side (using PHP)

Using this method, steps 1, 3 and 4 are done in PHP, and only step 2 is done in Javascript.

quickstart.php

This page checks if there is an access token in the session, if there is not it redirects the user for authentication. If there is, it shows the picker and a form. In the picker Javascript code, note that the oAuthToken used is obtained with PHP from the server! Source: Use Google Picker without logging in with Google account (with OAuth). The form then submits a POST request to this page and the file is downloaded.

<?php
    require_once 'google-api-php-client/src/Google/autoload.php';

    session_start();

    // Ref: https://developers.google.com/drive/v2/reference/files/get
    function downloadFile($service, $file) {
        $downloadUrl = $file->getDownloadUrl();
        if ($downloadUrl) {
            $request = new Google_Http_Request($downloadUrl, 'GET', null, null);
            $httpRequest = $service->getClient()->getAuth()->authenticatedRequest($request);
            if ($httpRequest->getResponseHttpCode() == 200) {
                return $httpRequest->getResponseBody();
                } else {
                // An error occurred.
                return null;
            }
            } else {
            // The file doesn't have any content stored on Drive.
            return null;
        }
    }

    $client = new Google_Client();
    $client->setAuthConfigFile('client_secrets.json');
    $client->addScope(Google_Service_Drive::DRIVE_READONLY);

    if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
        $client->setAccessToken($_SESSION['access_token']);
        if (isset($_POST['fileid'])){           
            $drive_service = new Google_Service_Drive($client);
            $file = $drive_service->files->get($_POST['fileid']);
            $data = downloadFile($drive_service, $file);
            file_put_contents('temp.jpg', $data);

            echo "file uploaded";
            exit();
        }
    } else {
        $redirect_uri = 'http://localhost/drivepicker-php/oauth2callback.php';
        header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
        exit();
    }   

?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
        <title>Google Picker Example</title>


        <script type="text/javascript">

            // The Browser API key obtained from the Google Developers Console.
            var developerKey = '';

            // Replace with your own App ID. (Its the first number in your Client ID)
            var appId = ""

            var pickerApiLoaded = false;

            // Use the Google API Loader script to load the google.picker script.
            function loadPicker() {
                gapi.load('picker', {'callback': onPickerApiLoad});
            }

            function onPickerApiLoad() {
                pickerApiLoaded = true;
                createPicker();
            }

            // Create and render a Picker object
            function createPicker() {
                if (pickerApiLoaded) {              
                    var view = new google.picker.DocsView();
                    view.setIncludeFolders(true);
                    //view.setMimeTypes("image/png,image/jpeg,image/jpg");

                    var picker = new google.picker.PickerBuilder()
                    //.enableFeature(google.picker.Feature.NAV_HIDDEN)
                    //.enableFeature(google.picker.Feature.MULTISELECT_ENABLED)
                    .setAppId(appId)
                    .setOAuthToken('<?= json_decode($client->getAccessToken())->access_token; ?>')
                    .addView(view)
                    .setDeveloperKey(developerKey)
                    .setCallback(pickerCallback)
                    .build();
                    picker.setVisible(true);
                }
            }

            // A simple callback implementation.
            function pickerCallback(data) {
                if (data.action == google.picker.Action.PICKED) {
                    var fileId = data.docs[0].id;
                    document.getElementById("fileid").value = fileId;

                }
            }
        </script>
    </head>
    <body>
        <form action="quickstart.php" method="post">
            <label for="fileid">File ID</label><input type="text" name="fileid" id="fileid">
            <input type="submit">
        </form>

        <!-- The Google API Loader script. -->
        <script type="text/javascript" src="https://apis.google.com/js/api.js?onload=loadPicker"></script>
        <script type="text/javascript" src="https://apis.google.com/js/client.js"></script>
    </body>
</html>

oauth2callback.php

Helper file for the OAuth callback.

<?php
    require_once 'google-api-php-client/src/Google/autoload.php';

    session_start();

    $client = new Google_Client();
    $client->setAuthConfigFile('client_secrets.json');
    $client->setRedirectUri('http://localhost/drivepicker-php/oauth2callback.php');
    $client->addScope(Google_Service_Drive::DRIVE_READONLY);

    if (!isset($_GET['code'])) {
        $auth_url = $client->createAuthUrl();
        header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL));
    } else {
        $client->authenticate($_GET['code']);
        $_SESSION['access_token'] = $client->getAccessToken();
        $redirect_uri = 'http://localhost/drivepicker-php/quickstart.php';
        header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
    }

?>

这篇关于新手 Google Drive API (PHP) 混淆 - 使用什么指南/库?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆