首页 > 解决方案 > 无法在 PHP 中使用 Google 翻译 API

问题描述

我正在尝试在我的 Laravel 项目中使用 Google Translate API。我按照本教程https://cloud.google.com/translate/docs/quickstart-client-libraries?authuser=2#client-libraries-install-php

但是当我尝试运行代码进行翻译时,我得到了这个错误 -

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".

这是我的代码:

 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'];
    }

我不知道问题可能是什么。

标签: phplaravelgoogle-apigoogle-translate

解决方案


您设置客户端库以gcloud~/.config/gcloud/application_default_credentials.json. 这些是最终用户凭据,与您(特定用户)相关联。客户端库需要服务帐户凭据,它不绑定到特定用户。

通过转到APIs and Services > Credentials并选择Create Credentials > Service Account Key创建服务帐户凭据。创建一个新的服务帐户,并在您的情况下为其分配角色Cloud Translation API Admin。这将下载一个包含以下字段的 JSON 文件:

{
  "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": "..."
}

现在将GOOGLE_APPLICATION_CREDENTIALS环境变量设置为此文件的路径。注意“type”字段是“service_account”。在引发错误的凭据中,“类型”字段是“authorized_user”。


推荐阅读