Search code examples
phpgoogle-cloud-platformgoogle-api-php-clientgoogle-translate

How can I authenticate Google Cloud Translate from PHP?


I'm trying to use the google/cloud-translate library (v ^1.5) in Laravel (v ^6.0).

In GoogleController.php:

public function translate(Request $request) {
    $request->validate([
        'source' => 'required|string|min:2|max:5',
        'target' => 'required|string|min:2|max:5',
        'q' => 'required|string',
    ]);

    $translate = new TranslateClient([
        'keyFile' => base_path(config('services.google.json_path')),
        'projectId' => config('services.google.project_id'),
        'suppressKeyFileNotice' => true,
    ]);

    // Translate text from english to french.
    $result = $translate->translate($request->q, [
        'target' => explode($request->target, '-')[0],
        'source' => explode($request->source, '-')[0],
    ]);

    return $result;
}

But calling the route in Postman gives me the error:

Argument 2 passed to Google\Auth\CredentialsLoader::makeCredentials() must be of the type array, string given, called in /[...]/vendor/google/cloud-core/src/RequestWrapperTrait.php on line 155

I've checked that the projectId and the path to the keyFile is correct. Can anyone shed some light on how to get past this error?


Solution

  • You're specifying the path to the key file, so you should use the keyFilePath parameter instead.

    Try this:

    $translate = new TranslateClient([
        'keyFilePath' => base_path(config('services.google.json_path')),
        ...
    ]);
    

    From the TranslateClient.__construct docs:

    • keyFile: The contents of the service account credentials .json file retrieved from the Google Developer's Console. Ex: json_decode(file_get_contents($path), true).
    • keyFilePath: The full path to your service account credentials .json file retrieved from the Google Developers Console.