更新用户

用于更新用户的商家 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.protobuf.FieldMask;
import com.google.shopping.merchant.accounts.v1beta.AccessRight;
import com.google.shopping.merchant.accounts.v1beta.UpdateUserRequest;
import com.google.shopping.merchant.accounts.v1beta.User;
import com.google.shopping.merchant.accounts.v1beta.UserName;
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 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
/**
 * 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 update a user to make it an admin of the MC 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\Protobuf\FieldMask;
use Google\Shopping\Merchant\Accounts\V1beta\AccessRight;
use Google\Shopping\Merchant\Accounts\V1beta\UpdateUserRequest;
use Google\Shopping\Merchant\Accounts\V1beta\User;
use Google\Shopping\Merchant\Accounts\V1beta\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);
# -*- 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 update a user."""


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