注册为开发者

注册成为开发者是一项强制性的一次性设置流程,可将您的 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 方法,将您的开发者联系信息 和 Google Cloud 项目注册到您的 Merchant Center 账号。

无论您是否使用多个商家账号,您都需要为每个打算使用的 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 账号:如果您尝试同时将一个 Google Cloud 项目注册到多个 Merchant Center 账号 ,则会收到 ALREADY_REGISTERED 错误。请使用相同的开发者电子邮件地址进行注册。请注意,多个 Google Cloud 项目可以注册到同一个 Merchant Center 账号。
  • 为管理多个商家的第三方 (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 调用 您可以直接向 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}"
}'

如需完成注册,您必须确保 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 调用所需的其他权限。我们建议向开发者添加 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 界面中的 Access and services 页面添加用户或更新现有用户。通过主动添加备份开发者,您可以创建更具弹性的集成,该集成不依赖于单个个人。

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