无法使用API​​ for service account将文件上传到Google云端硬盘

时间:2014-02-15 13:08:24

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

要使用服务帐户将文件上传到Google云端硬盘,我已编写以下代码来自此链接:https://developers.google.com/drive/web/service-accounts

我的代码:

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

 session_start();

 $DRIVE_SCOPE = 'https://www.googleapis.com/auth/drive';
 $SERVICE_ACCOUNT_EMAIL = '<some-id>@developer.gserviceaccount.com';
 $SERVICE_ACCOUNT_PKCS12_FILE_PATH = '/path/to/<public_key_fingerprint>-privatekey.p12';

/**
 * Build and returns a Drive service object authorized with the service accounts.
 *
 * @return Google_DriveService service object.
 */
 function buildService() {
  $key = file_get_contents($SERVICE_ACCOUNT_PKCS12_FILE_PATH);
  $auth = new Google_AssertionCredentials(
      SERVICE_ACCOUNT_EMAIL,
      array(DRIVE_SCOPE),
      $key);
  $client = new Google_Client();
  $client->setUseObjects(true);
  $client->setAssertionCredentials($auth);
  return new Google_DriveService($client);
 }

 function uploadFile($service, $mime, $src) {
    //Insert a file
    $file = new Google_DriveFile();
    $file->setMimeType($mime);
    $data = file_get_contents($src);

    try {
    //ERROR HERE: cannot insert (upload) file
        $createdFile = $service->files->insert($file,
            array(
                'data' => $data,
                'mimeType' => $mime,
                'convert' => true,
            )
        );

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

 $service = buildService();

当我调用buildService()方法时,它会给我一个错误:

  

导致致命错误:第197行的/opt/lampp/htdocs/ajaxGoogleDrive/google-api-php-client/src/auth/Google_OAuth2.php中无法将类Google_AssertionCredentials的对象转换为字符串

我哪里错了?

0 个答案:

没有答案