使用PHP的服务帐户访问Google驱动器API

时间:2015-04-14 13:18:56

标签: php google-api google-drive-api

我必须从我的网站上传文件到Google云端硬盘。所以我需要使用谷歌服务帐户。我是在Google Developer Console上创建的。

这是我到目前为止所做的:

    session_start();      

    define('DRIVE_SCOPE', 'https://www.googleapis.com/auth/drive.file');
    define('SERVICE_ACCOUNT_EMAIL', 'xxx@developer.gserviceaccount.com');
    define('SERVICE_ACCOUNT_PKCS12_FILE_PATH', 'xxx.p12');

    function buildService() {
        $key = file_get_contents(SERVICE_ACCOUNT_PKCS12_FILE_PATH);
        $auth = new Google_Auth_AssertionCredentials(
            SERVICE_ACCOUNT_EMAIL,
            array(DRIVE_SCOPE),
            $key);
        $client = new Google_Client();

        $client->setAssertionCredentials($auth);
        return new Google_Service_Drive($client);
    }

    function uploadFile($service, $mime, $src) {            
        $file = new Google_Service_Drive_DriveFile();
        $file->setMimeType($mime);
        $data = file_get_contents($src);

        try {
            $createdFile = $service->files->insert($file,
                array(
                    'data' => $data,
                    'mimeType' => $mime,
                    'convert' => true,
                    'uploadType' => 'media'
                )
            );

            return $createdFile;
        } catch (Exception $e) {
            print "An error occurred: " . $e->getMessage();
        }
    }

    $service = buildService();
    uploadFile($service, "text/plain", "document.txt");

我遇到了以下错误:

  

注意:第212行的D:\ dvlp \ projects \ local \ google_drive_api \ Google \ Service \ Resource.php中的未定义索引:uploadType

     

注意:第212行的D:\ dvlp \ projects \ local \ google_drive_api \ Google \ Service \ Resource.php中的未定义索引:uploadType

UPD 添加了上传类型。错误消失,但没有文件添加到GDrive

请帮帮我。

0 个答案:

没有答案