It looks like you're trying to access a property projects_serviceAccounts that doesn't exist on the Google_Service_Iam class. The correct way to create a service account using the Google PHP client library is to use the projects.serviceAccounts collection.
Here's how you can modify your code to create a service account:
namespace App\Services;
use Google_Client;
use Google_Service_Iam;
use Google_Service_Iam_CreateServiceAccountRequest;
use Google_Service_Iam_ServiceAccount;
class GoogleServiceAccountManager
{
private $service;
private $googleProject;
public function __construct(GoogleProject $googleProject)
{
$client = new Google_Client();
// Set up your Google_Client
$client->useApplicationDefaultCredentials();
$client->addScope(Google_Service_Iam::CLOUD_PLATFORM);
$this->service = new Google_Service_Iam($client);
$this->googleProject = $googleProject;
}
public function createServiceAccount()
{
$serviceAccount = new Google_Service_Iam_ServiceAccount();
$serviceAccount->setDisplayName($this->googleProject->project_display_name);
$serviceAccount->setDescription("Service account for {$this->googleProject->project_display_name}");
$requestBody = new Google_Service_Iam_CreateServiceAccountRequest();
$requestBody->setAccountId($this->googleProject->project_id);
$requestBody->setServiceAccount($serviceAccount);
$name = 'projects/' . $this->googleProject->project_id;
// Use the 'projects.serviceAccounts' collection to create the service account
$serviceAccounts = $this->service->projects_serviceAccounts;
return $serviceAccounts->create($name, $requestBody);
}
}
Make sure to replace the placeholder code where the Google_Client is set up with your actual configuration, including setting the correct credentials and scopes as needed for your application.
The key change here is that we're using $this->service->projects_serviceAccounts to access the projects.serviceAccounts collection, which is the correct way to interact with the service accounts in the Google IAM API.
Also, ensure that you have the latest version of the Google API PHP Client installed, as older versions may not have the correct service definitions. You can update the client library using Composer:
composer require google/apiclient:^2.0
This should resolve the Undefined property error you're encountering.