注册为开发者

注册成为开发者是一项强制性的一次性设置流程,可将您的 Google Cloud 项目与 Merchant Center 账号相关联,并向 Google 注册您的开发者联系信息。这样,Google 便可向您提供的相关技术
联系人发送重要的服务通告和强制性更新。

本文档是关于 Merchant API 使用入门的系列文章中的一篇。如果您已注册 Merchant API,则可以跳到下一部分: 插入您的第一件商品

前提条件

在注册使用 Merchant API 之前,请确保满足以下要求:

  • Merchant Center 账号:您需要拥有现有的 Merchant Center 账号。
  • Merchant Center 账号的管理员访问权限:您用于授权注册调用的电子邮件地址或服务账号必须在您要注册的 Merchant Center 账号中具有 ADMIN 访问权限类型。如需了解详情,请参阅为 Merchant API 请求授权
  • Google Cloud 项目 ID:您的应用必须与专用 Google Cloud 项目相关联,才能提供用于身份验证的凭据。如需详细了解在何处查找项目 ID,请参阅查找项目名称、编号和 ID
  • 您提供的与 Google 账号相关联的有效电子邮件地址,用于接收 Google 发送的更新信息。不得是服务账号电子邮件地址。您可以使用已属于 Merchant Center 账号的电子邮件地址,也可以使用新的电子邮件地址。

使用 Merchant API 注册为开发者

如需使用 Merchant API,您必须通过 registerGcp 方法向您的 Merchant Center 账号注册开发者联系信息和 Google Cloud 项目。

无论您是否使用多个商家账号,对于您打算使用的每个 Google Cloud 项目,您只需执行一次注册操作。如果您有多个 Google Cloud 项目,则可以将任意或所有项目注册到同一 Merchant Center 账号。

注册福利

注册具有以下优势:

  • 技术联系人创建:在 Merchant Center 中创建技术联系人。Google 会向技术联系人发送重要的 API 特定更新,例如服务公告和新功能信息。
  • 多个商家账号管理:您可以代表您管理的所有商家账号的开发者联系人。

除了注册之外,从未注册的 Google Cloud 项目对 Merchant API 的任何调用都会被阻止,并返回状态为 UNAUTHENTICATED401 错误代码以及以下出错提示:

GCP project with id {GCP_ID} and number {GCP_NUMBER} is not registered with the merchant account.
Please follow these steps https://developers.google.com/merchant/api/guides/quickstart#register_as_a_developer
to register the GCP project with the merchant account then try calling the API again in 5 minutes.

重要注意事项

  • 为每个 Google Cloud 项目进行一次性设置:注册是为每个 Google Cloud 项目进行的一次性设置,适用于 Google Cloud 项目中的所有用户和服务账号。确保已在您的 Google Cloud 项目中启用 Merchant API。
  • 每个 Google Cloud 项目在任何给定时间只能注册一个 Merchant Center 账号:如果您尝试同时为一个 Google Cloud 项目注册多个 Merchant Center 账号,系统会显示 ALREADY_REGISTERED 错误。注册时使用相同的开发者电子邮件地址。请注意,多个 Google Cloud 项目可以注册到同一个 Merchant Center 账号。
  • 为管理多个商家的第三方 (3P) 指定正确的账号:代表或管理多个商家的第三方需要在 Google 生态系统中采用适当的账号结构。应使用哪种正确的 ID 取决于您的业务类型:
    • 已拥有高级账号的购物平台:如果您的商家以购物平台形式运营,并且已拥有代表整个平台的高级账号,则应使用此现有账号 ID。
    • 比较购物服务 (CSS):如果您是 CSS,则应使用您的唯一 CSS 账号 ID 或 CSS 组账号 ID。
    • 代理机构、开发者和其他第三方:如果您是代理机构或第三方开发者等第三方企业,管理着多个商家账号,但没有代表您企业的单个 Merchant Center ID,则应创建一个新的主 Merchant Center 账号,并申请将其转换为高级账号。高级账号可以管理子账号,并为第三方运营提供必要的结构。
  • 仅针对主 Merchant Center 执行注册:您仅使用主 Merchant Center 账号执行开发者注册,并成为所有关联的 Merchant Center 子账号的开发者联系人。无需为每个 Merchant Center 子账号分别进行注册。

无障碍功能的替代文本

上图展示了使用多个 Google Cloud 项目和一个主要 Merchant Center(可选)以及多个 Merchant Center 子账号时的注册设置。

  • 注册开发者电子邮件地址后
    • 注册后 5 分钟内,您就可以执行 Merchant API 调用。
    • 如果该电子邮件地址属于现有 Merchant Center 用户,系统会向该用户授予 API_DEVELOPER 角色。否则,系统会在 Merchant Center 中创建新用户,新用户必须在 14 天内接受邀请,以免邀请过期并避免必须重新开始注册流程。只有在用户点击邀请链接后,您才能完成注册流程。

拨打注册电话

您可以通过调用 registerGcp 方法进行注册。您可以通过以下两种方式拨打注册电话:

  • 选项 1:直接 API 调用 您可以直接向 API 端点发出原始请求,通常是通过 HTTP(S) 进行。您需要手动处理请求正文的创建、标头的设置(包括身份验证)和响应的解析等事宜。
  • 选项 2:客户端库 您可以使用预建库,以更便捷、更符合语言习惯的方式与 Merchant API 进行交互。它们负责处理身份验证和授权,并提供一种便捷的方式来抽象化底层 HTTP 通信。我们提供了官方代码示例,可帮助您快速入门。

注册通话的授权

授权对 Merchant API 的请求步骤中所述,您会遇到两种不同的身份验证场景:

  • OAuth 2.0:适用于管理多个商家账号的第三方提供商或代理机构
  • 服务账号:用于访问您自己的 Merchant Center 账号

如需详细了解注册调用的授权,请参阅如何对注册调用执行身份验证和授权?

注册通话

在以下示例中,您将使用直接 API 调用或客户端库执行注册调用。

您可以使用 registerGcp 方法执行注册调用。

POST https://merchantapi.googleapis.com/accounts/v1/accounts/{ACCOUNT_ID}/developerRegistration:registerGcp
Content-Type: application/json
Authorization: Bearer {ACCESS_TOKEN}"

{
  "developerEmail": "{DEVELOPER_EMAIL}"
}

替换以下内容:

  • ACCOUNT_ID:您的 Merchant Center ID
  • ACCESS_TOKEN:用于进行 API 调用的授权令牌
  • DEVELOPER_EMAIL:主要技术联系人的电子邮件地址

成功调用会返回 DeveloperRegistration 资源,确认关联状态为成功:

  "name": "accounts/{ACCOUNT_ID}/developerRegistration",
  "gcpIds": ["{GOOGLE_CLOUD_PROJECT_ID}"]

Python

下载示例,然后按照 Google Merchant API Python 示例中的指南设置 Python 客户端库。

from examples.authentication import configuration
from examples.authentication import generate_user_credentials
from google.shopping.merchant_accounts_v1 import DeveloperRegistrationServiceClient
from google.shopping.merchant_accounts_v1 import RegisterGcpRequest


def register_gcp(account_id: str, developer_email: str) -> None:
  """Registers the GCP project used to call the Merchant API with a developer email.

  Args:
    account_id: The ID of your Merchant Center account.
    developer_email: The email address of the developer to register.
  """
  # Get OAuth credentials.
  credentials = generate_user_credentials.main()

  # Create a client to the Developer Registration Service.
  client = DeveloperRegistrationServiceClient(credentials=credentials)

  # The name has the format: accounts/{account}/developerRegistration
  name = f"accounts/{account_id}/developerRegistration"

  # Create the request to register the GCP project.
  request = RegisterGcpRequest(
      name=name,
      developer_email=developer_email,
  )

  # Make the API call and handle potential errors.
  try:
    print("Sending RegisterGcp request:")
    response = client.register_gcp(request=request)
    print("Registered GCP project successfully:")
    print(response)
  except RuntimeError as e:
    print(f"An error occurred: {e}")


if __name__ == "__main__":

  # Your Merchant Center account ID.
  # This can be found in the Merchant Center UI.
  _account_id = configuration.Configuration().read_merchant_info()

  # The developer email to associate with the GCP project.
  _developer_email = "YOUR_EMAIL_HERE"

  register_gcp(_account_id, _developer_email)

Java

下载示例,然后按照 Google Merchant API Java 示例中的指南设置 Java 客户端库。

import com.google.api.gax.core.FixedCredentialsProvider;
import com.google.auth.oauth2.GoogleCredentials;
import com.google.shopping.merchant.accounts.v1.DeveloperRegistration;
import com.google.shopping.merchant.accounts.v1.DeveloperRegistrationName;
import com.google.shopping.merchant.accounts.v1.DeveloperRegistrationServiceClient;
import com.google.shopping.merchant.accounts.v1.DeveloperRegistrationServiceSettings;
import com.google.shopping.merchant.accounts.v1.RegisterGcpRequest;
import shopping.merchant.samples.utils.Authenticator;
import shopping.merchant.samples.utils.Config;

/**
 * This class demonstrates how to register the GCP project used to call the Merchant API with a
 * developer email.
 */
public class RegisterGcpSample {

  public static void registerGcp(Config config, String developerEmail) throws Exception {

    // Obtains OAuth token based on the user's configuration.
    GoogleCredentials credential = new Authenticator().authenticate();

    // Creates service settings using the credentials retrieved above.
    DeveloperRegistrationServiceSettings developerRegistrationServiceSettings =
        DeveloperRegistrationServiceSettings.newBuilder()
            .setCredentialsProvider(FixedCredentialsProvider.create(credential))
            .build();

    // Creates DeveloperRegistration name to identify the DeveloperRegistration.
    // The name has the format: accounts/{account}/developerRegistration
    String name =
        DeveloperRegistrationName.newBuilder()
            .setAccount(config.getAccountId().toString())
            .build()
            .toString();

    // Calls the API and catches and prints any network failures/errors.
    try (DeveloperRegistrationServiceClient developerRegistrationServiceClient =
        DeveloperRegistrationServiceClient.create(developerRegistrationServiceSettings)) {

      // Creates a request to register the GCP project with the developer email.
      RegisterGcpRequest request =
          RegisterGcpRequest.newBuilder().setName(name).setDeveloperEmail(developerEmail).build();

      System.out.println("Sending RegisterGcp request:");
      DeveloperRegistration response = developerRegistrationServiceClient.registerGcp(request);

      System.out.println(response);
    } catch (Exception e) {
      System.out.println(e);
    }
  }

  public static void main(String[] args) throws Exception {
    Config config = Config.load();
    String developerEmail = "YOUR_EMAIL_HERE"; // Replace with your email
    registerGcp(config, developerEmail);
  }
}

PHP

下载示例,然后按照 Google Merchant API PHP 示例中的指南设置 PHP 客户端库。

require_once __DIR__ . '/../../../../vendor/autoload.php';
require_once __DIR__ . '/../../../Authentication/Authentication.php';
require_once __DIR__ . '/../../../Authentication/Config.php';

use Google\ApiCore\ApiException;
use Google\Shopping\Merchant\Accounts\V1\Client\DeveloperRegistrationServiceClient;
use Google\Shopping\Merchant\Accounts\V1\RegisterGcpRequest;

/**
 * This class demonstrates how to register the GCP project used to call the
 * Merchant API with a developer email.
 */
class RegisterGcpSample
{
    /**
     * A helper function to create the name string for the
     * DeveloperRegistration.
     *
     * @param string $accountId The merchant account ID.
     * @return string The name, which has the format:
     *     `accounts/{account}/developerRegistration`
     */
    private static function getName(string $accountId): string
    {
        return sprintf("accounts/%s/developerRegistration", $accountId);
    }

    /**
     * Registers the GCP project with a developer email.
     *
     * @param array $config The configuration data for authentication and account ID.
     * @param string $developerEmail The email of the developer to register.
     */
    public static function registerGcpSample(array $config, string $developerEmail): void
    {
        // Obtains OAuth credentials from the configuration file.
        $credentials = Authentication::useServiceAccountOrTokenFile();

        // Creates a configuration object for the client.
        $options = ['credentials' => $credentials];

        // Creates the DeveloperRegistrationServiceClient.
        $developerRegistrationServiceClient = new DeveloperRegistrationServiceClient($options);

        // Creates the name of the developer registration to identify it.
        $name = self::getName($config['accountId']);

        // Calls the API and handles any network failures.
        try {
            // Creates a request to register the GCP project with the developer email.
            $request = new RegisterGcpRequest([
                'name' => $name,
                'developer_email' => $developerEmail
            ]);

            printf("Sending RegisterGcp request:%s", PHP_EOL);
            // The `registerGcp` method returns a `DeveloperRegistration` object
            // upon success.
            $response = $developerRegistrationServiceClient->registerGcp($request);
            print "Successfully registered developer email '$developerEmail' for account {$config['accountId']}.\n";
            print_r($response);
        } catch (ApiException $e) {
            printf("An error occurred: %s%s", $e->getMessage(), PHP_EOL);
        }
    }

    /**
     * Helper to execute the sample.
     */
    public function callSample(): void
    {
        $config = Config::generateConfig();
        // An email address for a developer to register for the API.
        $developerEmail = 'YOUR_EMAIL_HERE'; // Replace with your email
        self::registerGcpSample($config, $developerEmail);
    }
}

// Executes the sample.
$sample = new RegisterGcpSample();
$sample->callSample();

cURL

curl -X POST "https://merchantapi.googleapis.com/accounts/v1/accounts/{ACCOUNT_ID}/developerRegistration:registerGcp" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer {ACCESS_TOKEN}" \
-d '{
  "developerEmail": "{DEVELOPER_EMAIL}"
}'

注册后的最佳实践

为了受益于强大的访问权限管理功能并防止日后出现服务中断,我们建议您在完成初始注册后遵循以下一系列最佳实践:

向 API 开发者授予其他权限

注册开发者联系人后,系统会自动为其分配 API_DEVELOPER 角色。此角色不包含管理 Merchant Center 账号或进行所有 API 调用所需的其他权限。我们建议您为开发者添加 ADMINSTANDARD 角色,以提供全面的访问权限。

如需修改用户的访问权限,请使用 accounts.users.patch 方法。您可以在请求正文的 updateMask 字段中指定访问权限,以添加或移除角色:

PATCH https://merchantapi.googleapis.com/accounts/v1/{ACCOUNT_ID}/users/{DEVELOPER_EMAIL}?update_mask=access_rights
Content-Type: application/json
Authorization: Bearer {ACCESS_TOKEN}"

{
  "name": "accounts/{ACCOUNT_ID}/users/{DEVELOPER_EMAIL}",
  "access_rights": [ "ADMIN", "API_DEVELOPER" ]
}

Python

from examples.authentication import configuration
from examples.authentication import generate_user_credentials
from google.protobuf import field_mask_pb2
from google.shopping.merchant_accounts_v1 import AccessRight
from google.shopping.merchant_accounts_v1 import UpdateUserRequest
from google.shopping.merchant_accounts_v1 import User
from google.shopping.merchant_accounts_v1 import UserServiceClient

FieldMask = field_mask_pb2.FieldMask

_ACCOUNT = configuration.Configuration().read_merchant_info()


def update_user(user_email, user_access_right):
  """Updates a user to make it an admin of the MC account."""

  credentials = generate_user_credentials.main()

  client = UserServiceClient(credentials=credentials)

  # Create user name string
  name = "accounts/" + _ACCOUNT + "/users/" + user_email

  user = User(name=name, access_rights=[user_access_right])

  field_mask = FieldMask(paths=["access_rights"])

  try:
    request = UpdateUserRequest(user=user, update_mask=field_mask)

    print("Sending Update User request")
    response = client.update_user(request=request)
    print("Updated User Name below")
    print(response.name)
  except RuntimeError as e:
    print(e)


if __name__ == "__main__":
  # Modify this email to update the right user
  email = "USER_MAIL_ACCOUNT"
  access_right = AccessRight.ADMIN
  update_user(email, access_right)

Java

import com.google.api.gax.core.FixedCredentialsProvider;
import com.google.auth.oauth2.GoogleCredentials;
import com.google.protobuf.FieldMask;
import com.google.shopping.merchant.accounts.v1.AccessRight;
import com.google.shopping.merchant.accounts.v1.UpdateUserRequest;
import com.google.shopping.merchant.accounts.v1.User;
import com.google.shopping.merchant.accounts.v1.UserName;
import com.google.shopping.merchant.accounts.v1.UserServiceClient;
import com.google.shopping.merchant.accounts.v1.UserServiceSettings;
import shopping.merchant.samples.utils.Authenticator;
import shopping.merchant.samples.utils.Config;

/** This class demonstrates how to update a user to make it an admin of the MC account. */
public class UpdateUserSample {

  public static void updateUser(Config config, String email, AccessRight accessRight)
      throws Exception {

    GoogleCredentials credential = new Authenticator().authenticate();

    UserServiceSettings userServiceSettings =
        UserServiceSettings.newBuilder()
            .setCredentialsProvider(FixedCredentialsProvider.create(credential))
            .build();

    // Creates user name to identify user.
    String name =
        UserName.newBuilder()
            .setAccount(config.getAccountId().toString())
            .setEmail(email)
            .build()
            .toString();

    // Create a user with the updated fields.
    User user = User.newBuilder().setName(name).addAccessRights(accessRight).build();

    FieldMask fieldMask = FieldMask.newBuilder().addPaths("access_rights").build();

    try (UserServiceClient userServiceClient = UserServiceClient.create(userServiceSettings)) {

      UpdateUserRequest request =
          UpdateUserRequest.newBuilder().setUser(user).setUpdateMask(fieldMask).build();

      System.out.println("Sending Update User request");
      User response = userServiceClient.updateUser(request);
      System.out.println("Updated User Name below");
      System.out.println(response.getName());
    } catch (Exception e) {
      System.out.println(e);
    }
  }

  public static void main(String[] args) throws Exception {
    Config config = Config.load();
    String email = "testUser@gmail.com";
    // Give the user admin rights. Note that all other rights, like
    // PERFORMANCE_REPORTING, would be overwritten in this example
    // if the user had those access rights before the update.
    AccessRight accessRight = AccessRight.ADMIN;

    updateUser(config, email, accessRight);
  }
}

PHP

use Google\ApiCore\ApiException;
use Google\Protobuf\FieldMask;
use Google\Shopping\Merchant\Accounts\V1\AccessRight;
use Google\Shopping\Merchant\Accounts\V1\UpdateUserRequest;
use Google\Shopping\Merchant\Accounts\V1\User;
use Google\Shopping\Merchant\Accounts\V1\Client\UserServiceClient;


/**
 * Updates a user.
 *
 * @param array $config The configuration data.
 * @param string $email The email address of the user.
 * @param int $accessRight The access right to grant the user.
 * @return void
 */
function updateUser($config, $email, $accessRights): void
{
    // Gets the OAuth credentials to make the request.
    $credentials = Authentication::useServiceAccountOrTokenFile();

    // Creates options config containing credentials for the client to use.
    $options = ['credentials' => $credentials];

    // Creates a client.
    $userServiceClient = new UserServiceClient($options);

    // Creates user name to identify user.
    $name = 'accounts/' . $config['accountId'] . "/users/" . $email;

    $user = (new User())
        ->setName($name)
        ->setAccessRights($accessRights);

    $fieldMask = (new FieldMask())->setPaths(['access_rights']);

    // Calls the API and catches and prints any network failures/errors.
    try {
        $request = new UpdateUserRequest([
            'user' => $user,
            'update_mask' => $fieldMask,
        ]);

        print "Sending Update User request\n";
        $response = $userServiceClient->updateUser($request);
        print "Updated User Name below\n";
        print $response->getName() . "\n";
    } catch (ApiException $e) {
        print $e->getMessage();
    }
}


$config = Config::generateConfig();
$email = "testUser@gmail.com";
$accessRights = [AccessRight::ADMIN];

updateUser($config, $email, $accessRights);

cURL

curl -X PATCH \
"https://merchantapi.googleapis.com/accounts/v1/{ACCOUNT_ID}/users/{USER_EMAIL}?update_mask=access_rights" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer {ACCESS_TOKEN}" \
-d '{
  "access_rights": [
    "ADMIN",
    "API_DEVELOPER"
  ]
}'

添加更多开发者联系信息

为避免主要开发者联系人离职或失去访问权限时导致业务中断,请务必设置备用联系人。我们建议您在 Merchant Center 中至少再添加一位具有 API_DEVELOPER 角色的用户作为备用。

您可以使用 Merchant API 中的 accounts.users 服务或 Merchant Center 界面中的访问权限和服务页面添加用户或更新现有用户。通过主动添加备用开发者,您可以打造更具弹性的集成,使其不依赖于单个个人。

PATCH https://merchantapi.googleapis.com/products/v1/accounts/{ACCOUNT_ID}/users
Content-Type: application/json
Authorization: Bearer {ACCESS_TOKEN}"
{
  "user_id": {USER_EMAIL},
  "user": { "access_rights": [ "API_DEVELOPER", "ADMIN" ] }
}

Python

from examples.authentication import configuration
from examples.authentication import generate_user_credentials
from google.shopping.merchant_accounts_v1 import AccessRight
from google.shopping.merchant_accounts_v1 import CreateUserRequest
from google.shopping.merchant_accounts_v1 import User
from google.shopping.merchant_accounts_v1 import UserServiceClient

_ACCOUNT = configuration.Configuration().read_merchant_info()


def get_parent(account_id):
  return f"accounts/{account_id}"


def create_user(user_email):
  """Creates a user for a Merchant Center account."""

  # Get OAuth credentials
  credentials = generate_user_credentials.main()

  # Create a UserServiceClient
  client = UserServiceClient(credentials=credentials)

  # Create parent string
  parent = get_parent(_ACCOUNT)

  # Create the request
  request = CreateUserRequest(
      parent=parent,
      user_id=user_email,
      user=User(
          access_rights=[AccessRight.ADMIN, AccessRight.PERFORMANCE_REPORTING]
      ),
  )

  try:
    print("Sending Create User request")
    response = client.create_user(request=request)
    print("Inserted User Name below")
    print(response.name)
  except RuntimeError as e:
    print(e)


if __name__ == "__main__":
  # Modify this email to create a new user
  email = "USER_MAIL_ACCOUNT"
  create_user(email)

Java

import com.google.api.gax.core.FixedCredentialsProvider;
import com.google.auth.oauth2.GoogleCredentials;
import com.google.shopping.merchant.accounts.v1.AccessRight;
import com.google.shopping.merchant.accounts.v1.CreateUserRequest;
import com.google.shopping.merchant.accounts.v1.User;
import com.google.shopping.merchant.accounts.v1.UserServiceClient;
import com.google.shopping.merchant.accounts.v1.UserServiceSettings;
import shopping.merchant.samples.utils.Authenticator;
import shopping.merchant.samples.utils.Config;

/** This class demonstrates how to create a user for a Merchant Center account. */
public class CreateUserSample {

  private static String getParent(String accountId) {
    return String.format("accounts/%s", accountId);
  }

  public static void createUser(Config config, String email) throws Exception {

    // Obtains OAuth token based on the user's configuration.
    GoogleCredentials credential = new Authenticator().authenticate();

    // Creates service settings using the credentials retrieved above.
    UserServiceSettings userServiceSettings =
        UserServiceSettings.newBuilder()
            .setCredentialsProvider(FixedCredentialsProvider.create(credential))
            .build();

    // Creates parent to identify where to insert the user.
    String parent = getParent(config.getAccountId().toString());

    // Calls the API and catches and prints any network failures/errors.
    try (UserServiceClient userServiceClient = UserServiceClient.create(userServiceSettings)) {

      CreateUserRequest request =
          CreateUserRequest.newBuilder()
              .setParent(parent)
              // This field is the email address of the user.
              .setUserId(email)
              .setUser(
                  User.newBuilder()
                      .addAccessRights(AccessRight.ADMIN)
                      .addAccessRights(AccessRight.PERFORMANCE_REPORTING)
                      .build())
              .build();

      System.out.println("Sending Create User request");
      User response = userServiceClient.createUser(request);
      System.out.println("Inserted User Name below");
      // The last part of the user name will be the email address of the user.
      // Format: `accounts/{account}/user/{user}`
      System.out.println(response.getName());
    } catch (Exception e) {
      System.out.println(e);
    }
  }

  public static void main(String[] args) throws Exception {
    Config config = Config.load();
    // The email address of this user.
    String email = "testUser@gmail.com";

    createUser(config, email);
  }
}

PHP

use Google\ApiCore\ApiException;
use Google\Shopping\Merchant\Accounts\V1\AccessRight;
use Google\Shopping\Merchant\Accounts\V1\CreateUserRequest;
use Google\Shopping\Merchant\Accounts\V1\User;
use Google\Shopping\Merchant\Accounts\V1\Client\UserServiceClient;


/**
 * Creates a user.
 *
 * @param array $config The configuration data.
 * @param string $email The email address of the user.
 * @return void
 */
function createUser($config, $email): void
{
    // Gets the OAuth credentials to make the request.
    $credentials = Authentication::useServiceAccountOrTokenFile();

    // Creates options config containing credentials for the client to use.
    $options = ['credentials' => $credentials];

    // Creates a client.
    $userServiceClient = new UserServiceClient($options);

    // Creates parent to identify where to insert the user.
    $parent = sprintf("accounts/%s", $config['accountId']);

    // Calls the API and catches and prints any network failures/errors.
    try {
        $request = new CreateUserRequest([
            'parent' => $parent,
            'user_id' => $email,
            'user' => (new User())
                ->setAccessRights([AccessRight::ADMIN,AccessRight::PERFORMANCE_REPORTING])
        ]);

        print "Sending Create User request\n";
        $response = $userServiceClient->createUser($request);
        print "Inserted User Name below\n";
        print $response->getName() . "\n";
    } catch (ApiException $e) {
        print $e->getMessage();
    }
}

$config = Config::generateConfig();
$email = "testUser@gmail.com";

createUser($config, $email);

cURL

curl -X PATCH \
"https://merchantapi.googleapis.com/products/v1/accounts/{ACCOUNT_ID}/users/{USER_EMAIL}?update_mask=access_rights" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer {ACCESS_TOKEN}" \
-d '{
  "access_rights": [
    "ADMIN",
    "API_DEVELOPER"
  ]
}'