php - 无法在 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'];
}
我不知道问题可能是什么。
解决方案
您设置客户端库以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”。
推荐阅读
- javascript - 如何通过在左侧或右侧添加面板来制作响应式数据表?
- c++ - 执行 C++ 二维数组
- android - 安装没有成功。无法安装应用程序。安装失败,原因是:“设备脱机”
- javascript - 我的 useState 有问题吗?我觉得我的 Array ReactNative 中的值并没有正确
- react-native - react-native-keyboard-aware-scroll-view :当我开始输入时页面向下滚动
- java - 使用 EclEmma 在 equals() 方法中获得完整的分支覆盖
- python-3.x - 如何从移动设备访问 Flask Web 服务器?
- swift - Mac OS 中 AXUIElementCopyAttributeValue 的展开问题
- javascript - 如何将json编码更改为数组字符串
- php - 音频文件多次上传不适用于php