How to create Google Project Service Account using PHP Client Library

188 Views Asked by At

I am trying to create a Google project service account using the PHP client library as demonstrated https://cloud.google.com/iam/docs/reference/rest/v1/projects.serviceAccounts/create but I am getting this error

Undefined property: Google\Service\Iam::$projects_serviceAccounts.

I am not sure but it seems V2 is being loaded but I need to use V1.

Here is my method in my class

public function createServiceAccount()
    {
        $requestBody = new Google_Service_Iam_CreateServiceAccountRequest();

// Required: Set the account ID for the service account
        $requestBody->setAccountId($this->googleProject->project_id);

// Optional: Set additional properties for the service account
        $serviceAccount = new Google_Service_Iam_ServiceAccount();
        $serviceAccount->setDisplayName($this->googleProject->project_display_name);
        $serviceAccount->setDescription("Service account for {$this->googleProject->project_display_name}");
// Assign the service account details to the request body
        $requestBody->setServiceAccount($serviceAccount);


        $name = 'projects/' . $this->googleProject->project_id;
        return $this->service->projects_serviceAccounts->create($name, $requestBody);

    }

I am PHPStorm IDE that is showing me this warning

Property 'projects_serviceAccounts' not found in \Google_Service_Iam

Kindly help me figure out where I am going wrong.

I am creating a Laravel APP that needs to automate Google project creation as well as service accounts for these projects.

2

There are 2 best solutions below

2
On

Check if this line is included on your php:

// Autoload Composer.
require_once __DIR__ . '/vendor/autoload.php';

Since projects_serviceAccounts is included on the following namespace based on the google-api-php-client-services repository:

namespace Google\Service\Iam\Resource;
0
On

It looks like you are using the V2 Google PHP Client library with code that was made for the V1 version.

In V2, Google added class aliases to allow backwards compatibility with class names. Your error seems to come from accessing an class member that does not exist in V2 anymore.

Don't confuse the library version with the API version. With the V2 library you can still make calls to the V1 API, it's just that the code is not the same anymore.

Now coming back to your issue, if you want to make your code work as-is, you need to downgrade your Google PHP Client library:

composer require google/apiclient:1.1.9

The better option would be to migrate your code to use the V2 client library. It does not seem that creating service accounts with the PHP client is well documented outside of Google's own documentation, so you might have to do some research on what changed exactly.

The source for the Iam API in the V2 client library may be found here.