shekwo
shekwo

Reputation: 1447

Unable to use Google translate API In PHP

I am trying to use the Google Translate API on my Laravel project. I followed this tutorial https://cloud.google.com/translate/docs/quickstart-client-libraries?authuser=2#client-libraries-install-php

But when I try to run the code to translate, I get this error -

Your application has authenticated using end user credentials from Google Cloud SDK. We recommend that most server applications use service accounts instead. If your application continues to use end user credentials from Cloud SDK, you might receive a "quota exceeded" or "API not enabled" error. For more information about service accounts, see https://cloud.google.com/docs/authentication/. To disable this warning, set SUPPRESS_GCLOUD_CREDS_WARNING environment variable to "true".

This is my code:

 public static function gcloud(){
        # Your Google Cloud Platform project ID
        $projectId = 'mybot';
        # Instantiates a client
        $translate = new TranslateClient([
            'projectId' => $projectId
        ]);

        # The text to translate
        $text = 'Hello, world!';
        # The target language
        $target = 'ru';

        # Translates some text into Russian
        $translation = $translate->translate($text, [
                    'target' => $target
                ]);

        echo 'Text: ' . $text . '
        Translation: ' . $translation['text'];
    }

I don't know what the problem might be.

Upvotes: 1

Views: 1341

Answers (1)

Brent Shaffer
Brent Shaffer

Reputation: 501

Most likely the credentials you set the client library to use your gcloud credentials at ~/.config/gcloud/application_default_credentials.json. These are End User Credentials, which are tied to YOU, a specific user. The client library requires Service Account Credentials, which are not tied to a specific user.

Create Service Account Credentials by going to APIs and Services > Credentials and selecting Create Credentials > Service Account Key. Create a new service account, and in your case assign it the role Cloud Translation API Admin. This will download a JSON file with the following fields:

{
  "type": "service_account",
  "project_id": "YOUR_PROJECT_ID",
  "private_key_id": "...",
  "private_key": "...",
  "client_email": "...",
  "client_id": "...",
  "auth_uri": "...",
  "token_uri": "...",
  "auth_provider_x509_cert_url": "...",
  "client_x509_cert_url": "..."
}

Now set the GOOGLE_APPLICATION_CREDENTIALS environment variable to the path to this file. Notice the "type" field is "service_account". In the credentials which are throwing the error, the "type" field is "authorized_user".

Upvotes: 1

Related Questions