【问题标题】:Unable to use Google translate API In PHP无法在 PHP 中使用 Google 翻译 API
【发布时间】:2019-06-13 10:25:06
【问题描述】:

我正在尝试在我的 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'];
    }

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

【问题讨论】:

    标签: php laravel google-api google-translate


    【解决方案1】:

    您设置客户端库的凭据很可能是在~/.config/gcloud/application_default_credentials.json 使用您的gcloud 凭据。这些是End User Credentials,与您(特定用户)相关联。客户端库需要Service Account Credentials,它不绑定到特定用户。

    转到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”。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-07-14
      • 2020-05-24
      • 2012-11-10
      • 2018-05-06
      • 2019-02-27
      • 2011-06-06
      • 1970-01-01
      相关资源
      最近更新 更多