我需要启动谷歌云实例,如果我的进程结束,我就会停止。 所以我尝试了来自 https://cloud.google.com/compute/docs/reference/rest/v1/instances/get 的 api 调用
为相同的 API 密钥和 oAuth 客户端 ID 创建,并尝试在邮递员应用程序中进行测试。
在标头Authorization : Bearer <api_key>
和 URL 中使用 API 密钥作为key=<api_key>
但是这两种方法都给出了错误401 login required
.
然后我找到了 API 资源管理器
https://developers.google.com/apis-explorer/
我也遇到了同样的错误。
我犯了什么错误。 我需要通过 PHP 代码实现实例启动和停止,因为它是后台进程。
PHP curl 响应
{
"error": {
"errors": [
{
"domain": "global",
"reason": "authError",
"message": "Invalid Credentials",
"locationType": "header",
"location": "Authorization"
}
],
"code": 401,
"message": "Invalid Credentials"
}
}
我认为使用env变量实际执行此操作的最简单方法,因为Google API php客户端库有一个简洁的方法。
require_once __DIR__ . '/vendor/autoload.php';
putenv('GOOGLE_APPLICATION_CREDENTIALS=/path/to/service-account.json');
$client = new Google_Client();
$client->setApplicationName('RandomNameYouNeedToInsert/0.1');
$client->addScope(array('https://www.googleapis.com/auth/compute'));
$client->useApplicationDefaultCredentials();
$service = new Google_Service_Compute($client);
// TODO: Update placeholder values.
project = 'my-project';
$zone = 'my-zone';
$instance = 'my-instance';
$response = $service->instances->start($project, $zone, $instance);
// TODO: Check if the response satisfies your request.