Вы можете использовать API учетных записей торговцев, чтобы контролировать, кто имеет доступ к вашей учетной записи продавца и какой у них уровень доступа .
User
— это тот, кто имеет доступ к вашему торговому счету. Вы можете использовать API учетных записей продавцов для просмотра, добавления и удаления пользователей из вашей учетной записи.
Добавьте пользователя в свою учетную запись
Чтобы добавить пользователя, вызовите accounts.users.create
и укажите его уровень доступа в поле access_rights
User
.
В следующем примере запроса показано, как добавить нового пользователя с разрешениями STANDARD
и PERFORMANCE_REPORTING
:
POST https://merchantapi.googleapis.com/accounts/v1beta/accounts/{ACCOUNT_ID}/users?userId={USER_EMAILID}
{
"accessRights": [
"STANDARD",
"PERFORMANCE_REPORTING"
],
"name": "{NAME}"
}
Замените следующее:
- {ACCOUNT_ID} : уникальный идентификатор вашего аккаунта Merchant Center.
- {USER_EMAILID} : адрес электронной почты пользователя, которого вы хотите добавить.
- {NAME} : имя ресурса пользователя в формате
accounts/
{ACCOUNT_ID}/user/
{EMAIL_ADDRESS} .
После успешного запроса возвращается следующий ответ:
{
"name": "accounts/{ACCOUNT_ID}/users/{USER_EMAILID}",
"state": "PENDING",
"accessRights": [
"STANDARD",
"PERFORMANCE_REPORTING"
]
}
Этот запрос отправляет приглашение в учетную запись Google, связанную с новым пользователем, которое необходимо принять, чтобы пользователь мог считаться участником вашей учетной записи.
В следующем примере показано, как можно использовать метод CreateUserRequest
для добавления пользователя в вашу учетную запись.
Ява
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);
}
}
Просмотр пользователей, имеющих доступ к вашей учетной записи
Чтобы просмотреть всех пользователей, имеющих доступ к вашей учетной записи, используйте метод accounts.users.list
.
В следующем примере показано, как можно использовать метод ListUsersRequest
для получения списка всех пользователей данной учетной записи.
Ява
public static void listUsers(Config config) 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 the account from which to list all users.
String parent = getParent(config.getAccountId().toString());
// Calls the API and catches and prints any network failures/errors.
try (UserServiceClient userServiceClient = UserServiceClient.create(userServiceSettings)) {
// The parent has the format: accounts/{account}
ListUsersRequest request = ListUsersRequest.newBuilder().setParent(parent).build();
System.out.println("Sending list users request:");
ListUsersPagedResponse response = userServiceClient.listUsers(request);
int count = 0;
// Iterates over all rows in all pages and prints the user
// in each row.
// `response.iterateAll()` automatically uses the `nextPageToken` and recalls the
// request to fetch all pages of data.
for (User element : response.iterateAll()) {
System.out.println(element);
count++;
}
System.out.print("The following count of elements were returned: ");
System.out.println(count);
} catch (Exception e) {
System.out.println(e);
}
}
Получить одного пользователя для данной учетной записи
В следующем примере показано, как можно использовать метод GetUserRequest
для получения пользователя для заданной учетной записи.
Ява
public static void getUser(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 user name to identify user.
String name =
UserName.newBuilder()
.setAccount(config.getAccountId().toString())
.setEmail(email)
.build()
.toString();
// Calls the API and catches and prints any network failures/errors.
try (UserServiceClient userServiceClient = UserServiceClient.create(userServiceSettings)) {
// The name has the format: accounts/{account}/users/{email}
GetUserRequest request = GetUserRequest.newBuilder().setName(name).build();
System.out.println("Sending Get user request:");
User response = userServiceClient.getUser(request);
System.out.println("Retrieved User below");
System.out.println(response);
} catch (Exception e) {
System.out.println(e);
}
}
Удаление пользователя из определенной учетной записи
Чтобы удалить пользователя из вашей учетной записи, сделайте запрос с помощью метода accounts.users.delete
.
В следующем примере показано, как можно использовать метод DeleteUserRequest
для удаления пользователя из определенной учетной записи.
Ява
public static void deleteUser(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 user name to identify the user.
String name =
UserName.newBuilder()
.setAccount(config.getAccountId().toString())
.setEmail(email)
.build()
.toString();
// Calls the API and catches and prints any network failures/errors.
try (UserServiceClient userServiceClient = UserServiceClient.create(userServiceSettings)) {
DeleteUserRequest request = DeleteUserRequest.newBuilder().setName(name).build();
System.out.println("Sending Delete User request");
userServiceClient.deleteUser(request); // no response returned on success
System.out.println("Delete successful.");
} catch (Exception e) {
System.out.println(e);
}
}
Изменение уровня доступа пользователя
Чтобы изменить уровень доступа пользователя, вызовите метод accounts.users.patch
с новым уровнем доступа.
В следующем примере показано, как можно использовать метод 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);
}
}
Сравнение суперадминистратора, администратора и стандартного доступа
Пользователей с доступом суперадминистратора к Business Manager нельзя удалить из Merchant Center. Дополнительную информацию о доступе суперадминистратора см. в разделе Управление бизнесом в качестве суперадминистратора .
Некоторые методы, например методы записи данных учетной записи, требуют доступа администратора . Чтобы узнать необходимый уровень доступа для каждого метода, смотрите справочную документацию .
Если уровень доступа не указан, вы можете использовать метод со стандартным доступом.
Что дальше
- Узнайте, как создавать дополнительные учетные записи и управлять ими .
- Чтобы понять, как работают отношения между учетными записями продавцов, см. Отношения между учетными записями .