Google API PHP客户端 - PHP致命错误:未捕获的异常“InvalidArgumentException”,消息“无效代码”

时间:2015-12-23 03:22:40

标签: google-app-engine google-api-php-client

我已将我的php应用程序上传到Google App Engine上。它是计划任务或计算任务的形式。任何人都可以帮助我吗?

我在日志中收到以下错误:

PHP致命错误:在/base/data/home/apps//google-api-php-client/src/Google/Client.php:168

中显示消息'InvalidArgumentException'并显示消息“无效代码”

这是我的代码:

function uploadData ($responseData){

require __DIR__ . '/google-api-php-client/vendor/autoload.php';

define('APPLICATION_NAME', 'Drive API PHP Quickstart');
define('CREDENTIALS_PATH', '~/.credentials/drive-php-quickstart.json');
define('CLIENT_SECRET_PATH', __DIR__ . '/client_secret.json');
define('SCOPES', implode(' ', array(
        Google_Service_Drive::DRIVE_FILE)
));

/**
 * Returns an authorized API client.
 * @return Google_Client the authorized client object
 */
function getClient() {
    $client = new Google_Client();
    $client->setApplicationName(APPLICATION_NAME);
    $client->setScopes(SCOPES);
    $client->setAuthConfigFile(CLIENT_SECRET_PATH);
    $client->setAccessType('offline');

    // Load previously authorized credentials from a file.
    $credentialsPath = expandHomeDirectory(CREDENTIALS_PATH);
    if (file_exists($credentialsPath)) {
        $accessToken = file_get_contents($credentialsPath);
    } else {
        // Request authorization from the user.
        $authUrl = $client->createAuthUrl();
        printf("Open the following link in your browser:\n%s\n", $authUrl);
        print 'Enter verification code: ';
        $authCode = trim(fgets(STDIN));

        // Exchange authorization code for an access token.
        $accessToken = $client->authenticate($authCode);

        // Store the credentials to disk.
        if(!file_exists(dirname($credentialsPath))) {
            mkdir(dirname($credentialsPath), 0700, true);
        }
        file_put_contents($credentialsPath, $accessToken);
        printf("Credentials saved to %s\n", $credentialsPath);
    }
    $client->setAccessToken($accessToken);

    // Refresh the token if it's expired.
    if ($client->isAccessTokenExpired()) {
        $client->refreshToken($client->getRefreshToken());
        file_put_contents($credentialsPath, $client->getAccessToken());
    }
    return $client;
}

/**
 * Expands the home directory alias '~' to the full path.
 * @param string $path the path to expand.
 * @return string the expanded path.
 */
function expandHomeDirectory($path) {
    $homeDirectory = getenv('HOME');
    if (empty($homeDirectory)) {
        $homeDirectory = getenv("HOMEDRIVE") . getenv("HOMEPATH");
    }
    return str_replace('~', realpath($homeDirectory), $path);
}


// Get the API client and construct the service object.
$client = getClient();
$service = new Google_Service_Drive($client);

$title = 'ordersMonthly30Days';

$file = new Google_Service_Drive_DriveFile($client);
$file->setTitle($title);

/*
$result = $service->files->insert($file, array(
    'data' => $responseData,
    'mimeType' => 'application/octet-stream',
    'uploadType' => 'media',
    'convert' => true,
));*/

$result = updateFile($service,'file id',$title,'testing update','application/octet-stream',$responseData,true);
}

/**
* Update an existing file's metadata and content.
*
* @param Google_Service_Drive $service Drive API service instance.
* @param string $fileId ID of the file to update.
* @param string $newTitle New title for the file.
* @param string $newDescription New description for the file.
* @param string $newMimeType New MIME type for the file.
* @param string $newFilename Filename of the new content to upload.
* @param bool $newRevision Whether or not to create a new revision for this     file.
* @return Google_Servie_Drive_DriveFile The updated file. NULL is returned   if
*     an API error occurred.
*/
function updateFile($service, $fileId, $newTitle, $newDescription, $newMimeType, $newFileName, $newRevision) {
try {
    // First retrieve the file from the API.
    $file = $service->files->get($fileId);

    // File's new metadata.
    $file->setTitle($newTitle);
    $file->setDescription($newDescription);
    $file->setMimeType($newMimeType);

    // File's new content.
    $data = $newFileName;

    $additionalParams = array(
        'newRevision' => $newRevision,
        'data' => $data,
        'mimeType' => $newMimeType
    );

    // Send the request to the API.
    $updatedFile = $service->files->update($fileId, $file, $additionalParams);
    return $updatedFile;
} catch (Exception $e) {
    print "An error occurred: " . $e->getMessage();
}
}

2 个答案:

答案 0 :(得分:3)

对于此问题的未来读者,在这种情况下错误的原因是由于在读取和写入凭证文件时需要解码和编码JSON,因为该文件是JSON格式。当时可能还不清楚该怎么做,但the current PHP quickstart examples used in the API docs显示如何使用json_decode()json_encode()来处理此问题。

如果在调用PHP API客户端函数时遇到任何类型的InvalidArgumentException(或任何其他异常),请记住该函数实际返回错误的详细信息,因此您可以捕获{{1并在结果上使用InvalidArgumentException(或记录它)以查看实际错误是什么,如下所示:

var_dump()

答案 1 :(得分:2)

define('CREDENTIALS_PATH', '~/.credentials/drive-php-quickstart.json');
replace the above line with 
define('CREDENTIALS_PATH', '/any_file_name.json');

然后试试。当您第一次运行quickstart.php文件时。文件any_file_name.json将动态创建。用于存储基本信息和名气。