带有服务帐户的Google云端硬盘API无效

时间:2014-05-06 07:48:36

标签: php google-drive-api

我正在尝试使用我的服务帐户实施google drive api。

  

警告:file_get_contents()[function.file-get-contents]:       / home / logic5nv / public_html / projects /中的文件名不能为空       第18行的google_drive /gservice.php       致命错误:带有消息

的未捕获异常'Google_AuthException'
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 =
'842613324525-6veubhkhrurplpshiuagmdvk1rtm1q1g@developer.gserviceaccount.com';
$SERVICE_ACCOUNT_PKCS12_FILE_PATH = '8447ce76bbb4956f9cbecd6779371ad3ab8f8e7e-
privatekey.p12';
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);
}
$service = buildService();
$file = new Google_DriveFile();
$file->setTitle('My document');
$file->setDescription('A test document');
$file->setMimeType('text/plain');
$data = file_get_contents('document.txt');
$createdFile = $service->files->insert($file, array(
    'data' => $data,
    'mimeType' => 'text/plain',
));
print_r($createdFile);

1 个答案:

答案 0 :(得分:0)

尝试:

function buildService() {

global  $SERVICE_ACCOUNT_PKCS12_FILE_PATH,$SERVICE_ACCOUNT_EMAIL,$DRIVE_SCOPE ;

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