创建用户

用于创建用户的商家 API 代码示例

// Copyright 2024 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package shopping.merchant.samples.accounts.users.v1beta;
import com.google.api.gax.core.FixedCredentialsProvider;
import com.google.auth.oauth2.GoogleCredentials;
import com.google.shopping.merchant.accounts.v1beta.AccessRight;
import com.google.shopping.merchant.accounts.v1beta.CreateUserRequest;
import com.google.shopping.merchant.accounts.v1beta.User;
import com.google.shopping.merchant.accounts.v1beta.UserServiceClient;
import com.google.shopping.merchant.accounts.v1beta.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
/**
 * Copyright 2025 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * Demonstrates how to create a user for a Merchant Center account.
 */

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\V1beta\AccessRight;
use Google\Shopping\Merchant\Accounts\V1beta\CreateUserRequest;
use Google\Shopping\Merchant\Accounts\V1beta\User;
use Google\Shopping\Merchant\Accounts\V1beta\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);


# -*- coding: utf-8 -*-
# Copyright 2024 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""A module to create a user."""


from examples.authentication import configuration
from examples.authentication import generate_user_credentials
from google.shopping.merchant_accounts_v1beta import AccessRight
from google.shopping.merchant_accounts_v1beta import CreateUserRequest
from google.shopping.merchant_accounts_v1beta import User
from google.shopping.merchant_accounts_v1beta 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)