注册为开发者

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

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

前提条件

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

  • Merchant Center 账号:您需要有一个现有的 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 的任何调用都会被屏蔽,并返回 401 错误代码、UNAUTHENTICATED 状态和以下错误消息:

GCP project with id {GCP_ID} and number {GCP_NUMBER} is not registered with the merchant account.
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 账号:如果您尝试同时向多个 Merchant Center 账号注册一个 Google Cloud 项目,则会收到 ALREADY_REGISTERED 错误。请使用相同的开发者邮箱进行注册。请注意,多个 Google Cloud 项目可以注册到同一个 Merchant Center 账号。如需了解如何更改或轮换已注册的 Google Cloud 项目,请参阅管理和转换 Google Cloud 项目。
  • 为管理多个商家的第三方 (3P) 指定正确的账号:为确保长期稳定并避免服务中断,代表或管理多个商家的第三方需要在 Google 生态系统中使用适当的账号结构。我们建议您根据自己的业务类型,注册代表您业务身份的账号:

    • 已有高级账号的购物平台:如果您的业务以购物平台的形式运营,并且已经有一个代表整个平台的高级账号,则应使用此现有账号 ID。
    • 购物比较服务 (CSS):如果您是 CSS,则应使用您唯一的 CSS 账号 ID 或 CSS 组账号 ID。
    • 代理机构、开发者和其他第三方:如果您是管理多个商家账号的第三方企业(例如代理机构或第三方开发者),并且没有代表您企业的单一 Merchant Center ID,则应创建一个新的主 Merchant Center 账号,并请求将其转换为高级账号。高级账号可以管理子账号,并为第三方运营提供必要的结构。

    下表提供了针对不同合作伙伴类型的建议:

    合作伙伴类型 建议注册的账号
    购物平台 您的主要(或最大)高级账号。
    广告代理机构 代表贵公司的独立账号或高级账号。如果您刚开始使用 Merchant API,我们建议您创建独立账号。
    购物比较服务 (CSS) 您的 CSS 组账号 ID 或特定 CSS 账号 ID,具体取决于该账号是代表整个 CSS 组,还是仅代表组内的特定 CSS。请勿使用 CSS 高级账号。
    商家或品牌 代表您品牌的主账号。可以是独立账号,也可以是高级账号。
    销售终端 (POS)/商品目录数据提供商 您的主要(或最大)高级账号。
    其他第三方 如果您有 Merchant Center 账号,可以使用该账号进行注册。否则,请创建公司独立账号。然后验证您的网站。
  • 仅为您的主要 Merchant Center 账号执行注册:您仅使用主要 Merchant Center 账号执行开发者注册,并成为所有关联的 Merchant Center 子账号的开发者联系人。请勿为每个 Merchant Center 子账号分别执行注册。

用于无障碍功能的替代文本

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

  • 身份验证要求:执行注册时,经过身份验证的 Merchant Center 账号(即您的凭据所在的账号)必须与模拟的 Merchant Center 账号(即您要注册的账号)一致。如果您使用单独的父级账号或经理账号进行身份验证,则无法注册子账号。

  • 仅限已验证网站的账号:只有拥有已验证网站的 Merchant Center 账号才能注册。

  • 无法注册测试账号:您无法为测试账号执行注册。

  • 注册开发者邮箱后:

    • 您可以在注册后 5 分钟内执行 Merchant API 调用。
    • 如果该邮箱属于现有 Merchant Center 用户,则该用户会被授予 API developer 角色。否则,系统会在 Merchant Center 中创建新用户,该用户必须在 14 天内接受邀请,以免邀请过期,从而不得不重新开始注册流程。只有在用户点击邀请链接后,您才能完成注册流程。

拨打注册电话

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

  • 选项 1:直接 API 调用:您通常通过 HTTP(S) 直接向 API 端点发出原始请求。您需要手动处理一些方面,例如形成请求正文、设置标头(包括身份验证)以及解析响应。
  • 选项 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 DeveloperRegistration
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
) -> DeveloperRegistration:
  """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.

  Returns:
    The created or updated DeveloperRegistration object.
  """
  # 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)
    return response
  except RuntimeError as e:
    print(f"An error occurred: {e}")
    raise


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 DeveloperRegistration 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 propagates 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);
      return response;
    }
  }

  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}"
}'

如需完成注册,您必须确保 Merchant Center 中至少有一位用户拥有 API developer 角色。为此,您可以执行以下操作之一:

  • 向 registerGcp 方法提供 developerEmail。
  • 在 Merchant Center 界面中添加具有 API developer 角色的新用户。
  • 在 Merchant Center 界面中向现有用户分配 API developer 角色。
  • 调用 accounts.users.create 方法以创建新用户并为其分配 API developer 角色。
  • 使用 accounts.users.patch 方法将 API developer 角色分配给现有用户。

注册后的最佳实践

为了受益于强大的身份和访问管理并防止未来服务中断,我们建议您在完成初始注册后遵循一系列最佳实践:

向 API developer 授予其他权限

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

如需修改用户的访问权限,请使用 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"
  ]
}'