Загрузка клиентской библиотеки API Google для PHP 1.0.0 не работает

Мне не удалось загрузить файл с Google Диска с помощью версии 0.6, и я попытался преобразовать следующую функцию для работы с альфа-версией 1.0.0 клиентской библиотеки Google API для PHP. В частности, я не уверен в одной строке с вызовом getAuth(). Он возвращает объект с пустым ответом http-кода. Я включил ответ ниже. Может ли кто-нибудь дать мне указатель на то, что я делаю неправильно?

Кстати, объект $service (полученный в результате авторизации) хорош, потому что я использую его, чтобы без проблем получить список файлов.

function GetFile($service, $fileId) {
   $fileVars = null;
   try {
      $file = $service->files->get($fileId);
      $fileVars = get_object_vars($file);
      $downloadUrl = $file->getDownloadUrl();

      if ($downloadUrl) {
         $client = $service->getClient();
         $request = new Google_Http_Request($client, $downloadUrl, 'GET', null, null);
         $httpRequest = $client->getAuth()->sign($request);
         drupal_set_message(t("Google_Http_Request: <pre>@status</pre>", array('@status' => print_r($httpRequest, TRUE))));
         error_log(print_r($httpRequest, 1));

         if ($httpRequest->getResponseHttpCode() == 200) {
            $content = $httpRequest->getResponseBody();
            $fileVars['content'] = $content?($content):'';
         } else {
            // An error occurred.
            return null;
         }
      } else {
         // The file doesn't have any content stored on Drive.
         return null;
      }

   } catch (apiServiceException $e) {
      error_log('Error retrieving file from Drive: ' . $e->getMessage());
      throw $e;
   }
   return json_encode($fileVars);
}

Google_Http_Request Object
(
    [batchHeaders:Google_Http_Request:private] => Array
        (
            [Content-Type] => application/http
            [Content-Transfer-Encoding] => binary
            [MIME-Version] => 1.0
        )

    [baseUrl:protected] => https://doc-10-50-docs.googleusercontent.com/docs/securesc/apic76cj8gku48a9ogarn9khpku0s46q/8pk7jcqiirj9bu21a9u2mqa6lmo1887p/1386864000000/08295678552528470768/15372451357194678536/0B6ahcE1NPpIaNE1wRU9TbW1LVU0
    [queryParams:protected] => Array
        (
            [h] => 16653014193614665626
            [e] => download
            [gd] => true
        )

    [requestMethod:protected] => GET
    [requestHeaders:protected] => Array
        (
            [authorization] => Bearer ya29.1.AADtN_V-6HHMTghP6EFc3DD1Ktf3wFyQtxscciNyyJzlu36YPG_oC7iX565RctWgCl9MQ4tB1Q
        )

    [postBody:protected] => 
    [userAgent:protected] =>  google-api-php-client/1.0.1-alpha
    [responseHttpCode:protected] => 
    [responseHeaders:protected] => 
    [responseBody:protected] => 
    [expectedClass:protected] => 
    [client:protected] => Google_Client Object
        (
            [auth:Google_Client:private] => Google_Auth_OAuth2 Object
                (
                    [assertionCredentials:Google_Auth_OAuth2:private] => 
                    [state:Google_Auth_OAuth2:private] => 
                    [token:Google_Auth_OAuth2:private] => Array
                        (
                            [access_token] => xxx
                            [token_type] => Bearer
                            [expires_in] => 3552
                            [created] => 1386868612
                        )

                    [client:Google_Auth_OAuth2:private] => Google_Client Object
 *RECURSION*
                )

            [io:Google_Client:private] => Google_IO_Stream Object
                (
                    [client:protected] => Google_Client Object
 *RECURSION*
                )

            [cache:Google_Client:private] => 
            [config:Google_Client:private] => Google_Config Object
                (
                    [configuration:Google_Config:private] => Array
                        (
                            [application_name] => 
                            [auth_class] => Google_Auth_OAuth2
                            [io_class] => Google_IO_Stream
                            [cache_class] => Google_Cache_File
                            [base_path] => https://www.googleapis.com
                            [classes] => Array
                                (
                                    [Google_Auth_OAuth2] => Array
                                        (
                                            [client_id] => xxx
                                            [client_secret] => xxx
                                            [redirect_uri] => http://flashum.com/goauth/authenticate
                                            [developer_key] => 
                                            [access_type] => online
                                            [approval_prompt] => auto
                                            [request_visible_actions] => 
                                            [federated_signon_certs_url] => https://www.googleapis.com/oauth2/v1/certs
                                        )

                                    [Google_Cache_File] => Array
                                        (
                                            [directory] => C:\Users\CDAVID~1\AppData\Local\Temp/Google_Client
                                        )

                                )

                            [services] => Array
                                (
                                )

                        )

                )

            [deferExecution:Google_Client:private] => 
            [availableScopes:protected] => Array
                (
                    [drive] => Array
                        (
                            [0] => https://www.googleapis.com/auth/drive
                            [1] => https://www.googleapis.com/auth/drive.apps.readonly
                            [2] => https://www.googleapis.com/auth/drive.readonly
                            [3] => https://www.googleapis.com/auth/drive.file
                            [4] => https://www.googleapis.com/auth/drive.scripts
                            [5] => https://www.googleapis.com/auth/drive.metadata.readonly
                            [6] => https://www.googleapis.com/auth/drive.appdata
                        )

                )

            [requestedScopes:protected] => Array
                (
                    [0] => https://www.googleapis.com/auth/drive
                )

            [services:protected] => Array
                (
                )

            [authenticated:Google_Client:private] => 
        )

    [accessKey] => 
    [basePath:Google_Http_Request:private] => https://www.googleapis.com
)

person cdavidyoung    schedule 12.12.2013    source источник


Ответы (1)


я загружаю файл с диска Google, используя следующий код:


        function downloadFiles($downloadUrl) {

    //        $default_opts = array(
    //            'http' => array(
    //                'follow_location' => 1
    //            )
    //        );
    //
    //        stream_context_set_default($default_opts);

            $request = new Google_Http_Request($this->getGoogleClient(), $downloadUrl, 'GET', null, null);
            $SignhttpRequest = $this->getGoogleClient()->getAuth()->sign($request);
            $httpRequest = $this->getGoogleClient()->getIo()->makeRequest($SignhttpRequest);

            if ($httpRequest->getResponseHttpCode() == 200) {
                return array($httpRequest->getResponseHeaders(), $httpRequest->getResponseBody());
            } else {
                return null;
            }
        }

  1. $downloadUrl — это файл->downloadUrl или один из файлов->exportLink
  2. $this->getGoogleClient() возвращает объект Google_Client()
person Ali Zaheer    schedule 27.12.2013
comment
Спасибо, Али. Я надеюсь, что смогу попробовать это в ближайшее время. - person cdavidyoung; 31.12.2013
comment
После нескольких часов борьбы я наконец нашел этот пост, который решил мою проблему, спасибо! - person Yoh; 07.01.2015