GoogleAnalyticsTechie
GoogleAnalyticsTechie

Reputation: 31

Google API PHP Client - PHP Fatal error: Uncaught exception 'InvalidArgumentException' with message 'Invalid code'

I have uploaded my php application on Google App Engine. It is in the form of a scheduled task or a cron job. Can anyone help me out?

I am getting the following error in logs:

PHP Fatal error: Uncaught exception 'InvalidArgumentException' with message 'Invalid code' in /base/data/home/apps//google-api-php-client/src/Google/Client.php:168

Here is my code:

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

Upvotes: 3

Views: 5892

Answers (2)

Ravin
Ravin

Reputation: 27

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

and try. When you run quickstart.php file first time. The file any_file_name.json will create dynamically. For storing the essential information & cred.

Upvotes: 2

Adam
Adam

Reputation: 6015

For future readers of this question, the cause of the error in this case was due to needing to decode and encode JSON when reading and writing to the credentials file, since that file is in JSON format. It may not have been clear at the time what to do, but the current PHP quickstart examples used in the API docs show how to use json_decode() and json_encode() to handle this.

If you ever get any kind of InvalidArgumentException (or any other exception) when calling a PHP API client function, remember that the details of the error are actually returned by the function, so you can catch InvalidArgumentException and use var_dump() on the result (or log it) to see what the actual error is, like this:

try {
    // ...
    $accessToken = $client->authenticate($authCode);
    // ...
}
catch (InvalidArgumentException $e) {
    var_dump($accessToken)
}

Upvotes: 2

Related Questions