Stay organized with collections
Save and categorize content based on your preferences.
Merchant API code sample to create a user.
Java
// 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.packageshopping.merchant.samples.accounts.users.v1;importcom.google.api.gax.core.FixedCredentialsProvider;importcom.google.auth.oauth2.GoogleCredentials;importcom.google.shopping.merchant.accounts.v1.AccessRight;importcom.google.shopping.merchant.accounts.v1.CreateUserRequest;importcom.google.shopping.merchant.accounts.v1.User;importcom.google.shopping.merchant.accounts.v1.UserServiceClient;importcom.google.shopping.merchant.accounts.v1.UserServiceSettings;importshopping.merchant.samples.utils.Authenticator;importshopping.merchant.samples.utils.Config;/** This class demonstrates how to create a user for a Merchant Center account. */publicclassCreateUserSample{privatestaticStringgetParent(StringaccountId){returnString.format("accounts/%s",accountId);}publicstaticvoidcreateUser(Configconfig,Stringemail)throwsException{// Obtains OAuth token based on the user's configuration.GoogleCredentialscredential=newAuthenticator().authenticate();// Creates service settings using the credentials retrieved above.UserServiceSettingsuserServiceSettings=UserServiceSettings.newBuilder().setCredentialsProvider(FixedCredentialsProvider.create(credential)).build();// Creates parent to identify where to insert the user.Stringparent=getParent(config.getAccountId().toString());// Calls the API and catches and prints any network failures/errors.try(UserServiceClientuserServiceClient=UserServiceClient.create(userServiceSettings)){CreateUserRequestrequest=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");Userresponse=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(Exceptione){System.out.println(e);}}publicstaticvoidmain(String[]args)throwsException{Configconfig=Config.load();// The email address of this user.Stringemail="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\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);
# -*- 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."""fromexamples.authenticationimportconfigurationfromexamples.authenticationimportgenerate_user_credentialsfromgoogle.shopping.merchant_accounts_v1importAccessRightfromgoogle.shopping.merchant_accounts_v1importCreateUserRequestfromgoogle.shopping.merchant_accounts_v1importUserfromgoogle.shopping.merchant_accounts_v1importUserServiceClient_ACCOUNT=configuration.Configuration().read_merchant_info()defget_parent(account_id):returnf"accounts/{account_id}"defcreate_user(user_email):"""Creates a user for a Merchant Center account."""# Get OAuth credentialscredentials=generate_user_credentials.main()# Create a UserServiceClientclient=UserServiceClient(credentials=credentials)# Create parent stringparent=get_parent(_ACCOUNT)# Create the requestrequest=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)exceptRuntimeErrorase:print(e)if__name__=="__main__":# Modify this email to create a new useremail="USER_MAIL_ACCOUNT"create_user(email)
[[["Easy to understand","easyToUnderstand","thumb-up"],["Solved my problem","solvedMyProblem","thumb-up"],["Other","otherUp","thumb-up"]],[["Missing the information I need","missingTheInformationINeed","thumb-down"],["Too complicated / too many steps","tooComplicatedTooManySteps","thumb-down"],["Out of date","outOfDate","thumb-down"],["Samples / code issue","samplesCodeIssue","thumb-down"],["Other","otherDown","thumb-down"]],["Last updated 2025-08-13 UTC."],[[["\u003cp\u003eThis webpage provides code samples in Java, PHP, and Python demonstrating how to create a user for a Merchant Center account using the Merchant API.\u003c/p\u003e\n"],["\u003cp\u003eEach code sample initializes the necessary configurations and credentials for making API requests and creating a \u003ccode\u003eUserServiceClient\u003c/code\u003e.\u003c/p\u003e\n"],["\u003cp\u003eThe \u003ccode\u003ecreateUser\u003c/code\u003e function in each language formats a \u003ccode\u003eCreateUserRequest\u003c/code\u003e, specifying the parent account, user email, and desired access rights, such as \u003ccode\u003eADMIN\u003c/code\u003e and \u003ccode\u003ePERFORMANCE_REPORTING\u003c/code\u003e.\u003c/p\u003e\n"],["\u003cp\u003eThe API response returns the user's name, which is then printed, along with feedback on whether or not the request was successful.\u003c/p\u003e\n"],["\u003cp\u003eEach code example uses a different method to get credentials, whether from a token file or service account.\u003c/p\u003e\n"]]],["The code samples demonstrate creating a user for a Merchant Center account across Java, PHP, and Python. Each script retrieves OAuth credentials, establishes a `UserServiceClient`, and constructs a `CreateUserRequest`. This request specifies the parent account, a user email, and assigns `ADMIN` and `PERFORMANCE_REPORTING` access rights. The scripts then execute the `createUser` method, sending the request to the Merchant Center API. Finally, they print the name of the newly created user, and handle potential API errors.\n"],null,["# Create a user\n\nMerchant API code sample to create a user. \n\n### Java\n\n // Copyright 2024 Google LLC\n //\n // Licensed under the Apache License, Version 2.0 (the \"License\");\n // you may not use this file except in compliance with the License.\n // You may obtain a copy of the License at\n //\n // https://www.apache.org/licenses/LICENSE-2.0\n //\n // Unless required by applicable law or agreed to in writing, software\n // distributed under the License is distributed on an \"AS IS\" BASIS,\n // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n // See the License for the specific language governing permissions and\n // limitations under the License.\n\n package shopping.merchant.samples.accounts.users.v1;\n import com.google.api.gax.core.FixedCredentialsProvider;\n import com.google.auth.oauth2.GoogleCredentials;\n import com.google.shopping.merchant.accounts.v1.AccessRight;\n import com.google.shopping.merchant.accounts.v1.CreateUserRequest;\n import com.google.shopping.merchant.accounts.v1.User;\n import com.google.shopping.merchant.accounts.v1.UserServiceClient;\n import com.google.shopping.merchant.accounts.v1.UserServiceSettings;\n import shopping.merchant.samples.utils.Authenticator;\n import shopping.merchant.samples.utils.Config;\n\n /** This class demonstrates how to create a user for a Merchant Center account. */\n public class CreateUserSample {\n\n private static String getParent(String accountId) {\n return String.format(\"accounts/%s\", accountId);\n }\n\n public static void createUser(Config config, String email) throws Exception {\n\n // Obtains OAuth token based on the user's configuration.\n GoogleCredentials credential = new Authenticator().authenticate();\n\n // Creates service settings using the credentials retrieved above.\n UserServiceSettings userServiceSettings =\n UserServiceSettings.newBuilder()\n .setCredentialsProvider(FixedCredentialsProvider.create(credential))\n .build();\n\n // Creates parent to identify where to insert the user.\n String parent = getParent(config.getAccountId().toString());\n\n // Calls the API and catches and prints any network failures/errors.\n try (UserServiceClient userServiceClient = UserServiceClient.create(userServiceSettings)) {\n\n CreateUserRequest request =\n CreateUserRequest.newBuilder()\n .setParent(parent)\n // This field is the email address of the user.\n .setUserId(email)\n .setUser(\n User.newBuilder()\n .addAccessRights(AccessRight.ADMIN)\n .addAccessRights(AccessRight.PERFORMANCE_REPORTING)\n .build())\n .build();\n\n System.out.println(\"Sending Create User request\");\n User response = userServiceClient.createUser(request);\n System.out.println(\"Inserted User Name below\");\n // The last part of the user name will be the email address of the user.\n // Format: `accounts/{account}/user/{user}`\n System.out.println(response.getName());\n } catch (Exception e) {\n System.out.println(e);\n }\n }\n\n public static void main(String[] args) throws Exception {\n Config config = Config.load();\n // The email address of this user.\n String email = \"testUser@gmail.com\";\n\n createUser(config, email);\n }\n } \n https://github.com/google/merchant-api-samples/blob/c6de994268c785ce22af0065932518a9ac5b3c03/java/src/main/java/shopping/merchant/samples/accounts/users/v1/CreateUserSample.java\n\n### PHP\n\n \u003c?php\n /**\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n /**\n * Demonstrates how to create a user for a Merchant Center account.\n */\n\n require_once __DIR__ . '/../../../../vendor/autoload.php';\n require_once __DIR__ . '/../../../Authentication/Authentication.php';\n require_once __DIR__ . '/../../../Authentication/Config.php';\n use Google\\ApiCore\\ApiException;\n use Google\\Shopping\\Merchant\\Accounts\\V1\\AccessRight;\n use Google\\Shopping\\Merchant\\Accounts\\V1\\CreateUserRequest;\n use Google\\Shopping\\Merchant\\Accounts\\V1\\User;\n use Google\\Shopping\\Merchant\\Accounts\\V1\\Client\\UserServiceClient;\n\n\n /**\n * Creates a user.\n *\n * @param array $config The configuration data.\n * @param string $email The email address of the user.\n * @return void\n */\n function createUser($config, $email): void\n {\n // Gets the OAuth credentials to make the request.\n $credentials = Authentication::useServiceAccountOrTokenFile();\n\n // Creates options config containing credentials for the client to use.\n $options = ['credentials' =\u003e $credentials];\n\n // Creates a client.\n $userServiceClient = new UserServiceClient($options);\n\n // Creates parent to identify where to insert the user.\n $parent = sprintf(\"accounts/%s\", $config['accountId']);\n\n // Calls the API and catches and prints any network failures/errors.\n try {\n $request = new CreateUserRequest([\n 'parent' =\u003e $parent,\n 'user_id' =\u003e $email,\n 'user' =\u003e (new User())\n -\u003esetAccessRights([AccessRight::ADMIN,AccessRight::PERFORMANCE_REPORTING])\n ]);\n\n print \"Sending Create User request\\n\";\n $response = $userServiceClient-\u003ecreateUser($request);\n print \"Inserted User Name below\\n\";\n print $response-\u003egetName() . \"\\n\";\n } catch (ApiException $e) {\n print $e-\u003egetMessage();\n }\n }\n\n $config = Config::generateConfig();\n $email = \"testUser@gmail.com\";\n\n createUser($config, $email);\n\n https://github.com/google/merchant-api-samples/blob/c6de994268c785ce22af0065932518a9ac5b3c03/php/examples/accounts/users/v1/CreateUserSample.php\n\n### Python\n\n # -*- coding: utf-8 -*-\n # Copyright 2024 Google LLC\n #\n # Licensed under the Apache License, Version 2.0 (the \"License\");\n # you may not use this file except in compliance with the License.\n # You may obtain a copy of the License at\n #\n # http://www.apache.org/licenses/LICENSE-2.0\n #\n # Unless required by applicable law or agreed to in writing, software\n # distributed under the License is distributed on an \"AS IS\" BASIS,\n # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n # See the License for the specific language governing permissions and\n # limitations under the License.\n \"\"\"A module to create a user.\"\"\"\n\n\n from examples.authentication import configuration\n from examples.authentication import generate_user_credentials\n from google.shopping.merchant_accounts_v1 import AccessRight\n from google.shopping.merchant_accounts_v1 import CreateUserRequest\n from google.shopping.merchant_accounts_v1 import User\n from google.shopping.merchant_accounts_v1 import UserServiceClient\n\n _ACCOUNT = configuration.Configuration().read_merchant_info()\n\n\n def get_parent(account_id):\n return f\"accounts/{account_id}\"\n\n\n def create_user(user_email):\n \"\"\"Creates a user for a Merchant Center account.\"\"\"\n\n # Get OAuth credentials\n credentials = generate_user_credentials.main()\n\n # Create a UserServiceClient\n client = UserServiceClient(credentials=credentials)\n\n # Create parent string\n parent = get_parent(_ACCOUNT)\n\n # Create the request\n request = CreateUserRequest(\n parent=parent,\n user_id=user_email,\n user=User(\n access_rights=[AccessRight.ADMIN, AccessRight.PERFORMANCE_REPORTING]\n ),\n )\n\n try:\n print(\"Sending Create User request\")\n response = client.create_user(request=request)\n print(\"Inserted User Name below\")\n print(response.name)\n except RuntimeError as e:\n print(e)\n\n\n if __name__ == \"__main__\":\n # Modify this email to create a new user\n email = \"USER_MAIL_ACCOUNT\"\n create_user(email)\n\n https://github.com/google/merchant-api-samples/blob/c6de994268c785ce22af0065932518a9ac5b3c03/python/examples/accounts/users/v1/create_user_sample.py"]]