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

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

问题描述

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

我所理解的工作流程如下所示:1)用户使用Picker选择文件,该文件将所选文件的元数据发送到我的网站客户端(即HTML / Javascript运行在手机/平板电脑上)



2)我通过ajax或只是一个表单隐藏字段发送给我的服务器

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



所以我需要帮助:

>

a)上述步骤是否正确,是否有任何其他方式可以做到这一点,甚至可以使用的服务将允许我的网站用户从其中选择一个文件几个云存储供应商?
$ b $ a)假设我的步骤是正确的,并且这是唯一的方法,我被困在服务器与API交谈的部分。 / p>

到目前为止,我已经按照这里完成了选择器 - 并在google-api的根目录中创建了drive_rest_api_step_3.php(如屏幕所示抢占)



得到致命错误:require_once():无法打开所需的'src / Google_Client.php'(include_path ='。:/ usr /第5行/path/to/google-api/drive_rest_api_step_3.php



没有Google_Client.php ,但是src / Google / Client.php ,所以我编辑require_once来使用它。



现在获取无法打开所需的'src / contrib / Google_DriveService.php' - 再次搜索该文件yeilds没有结果,但有一个src /谷歌/服务/ 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';

现在得到致命错误:类'Google_Service'找不到/ path /到/ google-api / src / Google / Service / Drive.php在第32行



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

解决方案

因为驱动器快速入门指南已过时,它指的是谷歌代码上旧版Google的PHP客户端API库,而不是新版Google GitHub上。因此,快速入门指南不适用于您下载的PHP客户端库。此外,快速入门指南代码旨在以PHP命令行模式而不是在服务器上执行。



要回答这个问题,我已经将一个很少有子答案:


  1. 如何使用PHP客户端库

  2. 如何选择文件使用Google Picker并将文件传输到服务器上



将Google PHP客户端库与Google Drive API一起使用



请尝试此页面: https://developers.google.com/api-client-library/php/auth/web-app ,该示例展示了如何使用新的 列出用户的Google云端硬盘中的文件。包括整个OAuth过程。



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



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



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); $!
$ b 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));
}

?>



使用Google File Picker挑选文件



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


  1. 获取访问令牌(认证)

  2. 使用选择器让用户选择文件

  3. 使用从选取器返回的文件ID获取下载URL

  4. 从下载URL下载文件

  5. ol>

    我们可以通过两种方式(客户端或服务器端)执行此操作:方法1:Client- side

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



    下面是一个例子(根据以上链接中的示例代码进行调整, http://webdevrefinery.com/forums/topic/12931-dropbox-google-drive-file -pickers / ):

    picker.html



    文件会在加载页面时启动filepicker并将URL放入表单中。

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


    < script type =text / javascript>

    //从Google Developers Console获取的浏览器API密钥。
    var developerKey ='';

    //从Google Developers Console获取的客户端ID。用您自己的客户ID替换。
    var clientId =

    //替换为您自己的应用程序ID。 (它是您的客户ID中的第一个数字)
    var appId =

    //用于访问用户的云端硬盘项目的范围。
    var scope = ['https://www.googleapis.com/auth/drive'];

    var pickerApiLoaded = false;
    var oauthToken;

    //使用Google API加载程序脚本加载google.picker脚本。
    函数loadPicker(){
    gapi.load('auth',{'callback':onAuthApiLoad});
    gapi.load('picker',{'callback':onPickerApiLoad});


    函数onAuthApiLoad(){
    window.gapi.auth.authorize(
    {
    'client_id':clientId,
    '范围':范围,
    '立即':false
    },
    handleAuthResult);
    }

    函数onPickerApiLoad(){
    pickerApiLoaded = true;
    createPicker();
    }

    函数handleAuthResult(authResult){
    if(authResult&&!authResult.error){
    oauthToken = authResult.access_token;
    createPicker();



    //创建并显示一个Picker对象
    函数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(googleoglecrick.feature.NAV_HIDDEN)
    //.enableFeature(googleoglecricker.Feature .MULTISELECT_ENABLED)
    .setAppId(appId)
    .setOAuthToken(oauthToken)
    .addView(view)
    .setDeveloperKey(developerKey)
    .setCallback(pickerCallback)
    .build();
    picker.setVisible(true);
    }
    }

    //一个简单的回调实现。
    函数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);
    });



    $ b 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.phpmethod =post>
    < label for =fileurl>文件下载URL< / label>< input type =textname =fileurlid =fileurl>
    < input type =submit>
    < / form>

    <! - Google API加载器脚本。 - >
    < script type =text / javascriptsrc =https://apis.google.com/js/api.js?onload=loadPicker>< / script>
    < script type =text / javascriptsrc =https://apis.google.com/js/client.js>< / script>
    < / body>
    < / html>

    然后,我们将表单提交给PHP脚本,以便将文件下载到服务器上。这里的诀窍是,我们还需要将访问令牌从客户端传递到服务器,因为用户在服务器端未经过身份验证。令人惊讶的是,您可以简单地附加 access_token 参数来验证文件的下载,如上所示。 strong> submit.php



    使用 file_get_contents 或CURL,具体取决于您的服务器支持的内容。虽然需要HTTPS支持。

     <?php 

    $ filename =' temp.jpg;

    $ ch = curl_init($ _ POST ['fileurl']);
    curl_setopt($ ch,CURLOPT_RETURNTRANSFER,1);
    //应该在生产中验证!
    curl_setopt($ ch,CURLOPT_SSL_VERIFYPEER,false);
    curl_setopt($ ch,CURLOPT_SSL_VERIFYHOST,false);
    $ data = curl_exec($ ch);
    // echo'卷曲错误:'。 curl_error($ CH);
    curl_close($ ch);

    file_put_contents($ filename,$ data);

    ?>

    更正式的方式( https://developers.google.com/drive/web/manage-downloads#alternate_method_using_downloadurl )将分别发送授权令牌授权标头。修改上面的Javascript以分别发送下载URL和令牌,然后使用类似下面代码的东西代替。如果您想使用 file_get_contents ,请参阅关于如何发送自定义标题的PHP file_get_contents()和标题。请注意,您需要在令牌之前拥有持票人字!

     <?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($ CH);
    curl_close($ ch);

    file_put_contents($ filename,$ data);

    ?>



    方法2:服务器端(使用PHP)



    使用这种方法,第1步,第3步和第4步是在PHP中完成的,并且只有第2步在Javascript中完成。


    $ b

    quickstart.php



    该页面检查会话中是否存在访问令牌,如果没有,则重定向用户进行验证。如果有,则显示选取器和表单。在选择器JavaScript代码中,请注意使用的oAuthToken是从服务器获得的PHP!资料来源:使用Google Picker而不登录Google帐户(使用OAuth)

     <?php 
    require_once'这个表格会提交一个POST请求到这个页面,谷歌的API的PHP客户端/ src目录/谷歌/ autoload.php;

    session_start();

    //参考:https://developers.google.com/drive/v2/reference/files/get
    函数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 {
    //发生错误。
    返回null;
    }
    }其他{
    //文件没有存储在驱动器上的任何内容。
    返回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);

    echofile 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-typecontent =text / html; charset = utf-8/>
    < title> Google Picker示例< / title>


    < script type =text / javascript>

    //从Google Developers Console获取的浏览器API密钥。
    var developerKey ='';

    //替换为您自己的应用程序ID。 (它是您的客户ID中的第一个数字)
    var appId =

    var pickerApiLoaded = false;

    //使用Google API加载程序脚本加载google.picker脚本。
    函数loadPicker(){
    gapi.load('picker',{'callback':onPickerApiLoad});
    }

    函数onPickerApiLoad(){
    pickerApiLoaded = true;
    createPicker();
    }

    //创建并呈现Picker对象
    函数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(googleoglecrick.feature.NAV_HIDDEN)
    //.enableFeature(googleoglecricker.Feature ('<?= json_decode($ client-> getAccessToken()) - > access_token;?>')
    。$ M
    .setAppId(appId)
    .setOAuthToken addView(view)
    .setDeveloperKey(developerKey)
    .setCallback(pickerCallback)
    .build();
    picker.setVisible(true);
    }
    }

    //一个简单的回调实现。
    函数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.phpmethod =post>
    < label for =fileid>文件ID< / label>< input type =textname =fileidid =fileid>
    < input type =submit>
    < / form>

    <! - Google API加载器脚本。 - >
    < script type =text / javascriptsrc =https://apis.google.com/js/api.js?onload=loadPicker>< / script>
    < script type =text / javascriptsrc =https://apis.google.com/js/client.js>< / script>
    < / body>
    < / html>

    oauth2callback.php



    OAuth回调的助手文件。

     <?php 
    require_once'google-api-php -client / src目录/谷歌/ 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); $!
    $ b 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));
    }

    ?>


    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天全站免登陆