用于注册 Google Cloud 项目的 Merchant API 代码示例。
AppsScript
// 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.
/**
* Registers a specific developer's email address on the current GCP project
* Note: every Apps Script project might be associated with a different default
* GCP project.
* Check https://developers.google.com/apps-script/guides/cloud-platform-projects
* for more details.
*/
function registerDeveloper() {
// IMPORTANT:
// Enable the Merchant API Accounts sub-API Advanced Service and call it
// "MerchantApiAccounts"
// Replace this with your Merchant Center ID.
const accountId = '<ACCOUNT_ID>';
// Replace this with your email address.
const developerEmail = '<YOUR_EMAIL>';
// Construct the parent resource name.
const parent = 'accounts/' + accountId + "/developerRegistration";
const requestBody = {
"developerEmail": developerEmail
};
try {
console.log('Sending register GCP request');
const response = MerchantApiAccounts.Accounts.DeveloperRegistration.registerGcp(requestBody, parent);
console.log(response);
} catch (e) {
console.log('ERROR!');
console.log(e);
}
}
C#
// 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.
using System;
using static MerchantApi.Authenticator;
using Google.Api.Gax;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Auth.OAuth2.Flows;
using Google.Apis.Auth.OAuth2.Responses;
using Google.Apis.Http;
using Newtonsoft.Json;
using Google.Shopping.Merchant.Accounts.V1;
namespace MerchantApi
{
public class RegisterGcpSample
{
public void RegisterGcp(string developerEmail)
{
// Registers a specific developer's email address on the current GCP project
Console.WriteLine("=================================================================");
Console.WriteLine("Calling the RegisterGcp method");
Console.WriteLine("=================================================================");
// Authenticate using either oAuth or service account
ICredential auth = Authenticator.Authenticate(
MerchantConfig.Load(),
// Passing the default scope for Merchant API: https://www.googleapis.com/auth/content
AccountsServiceClient.DefaultScopes[0]);
// Create the DeveloperRegistrationServiceClient with the credentials
DeveloperRegistrationServiceClientBuilder DeveloperRegistrationServiceClientBuilder = new DeveloperRegistrationServiceClientBuilder
{
Credential = auth
};
DeveloperRegistrationServiceClient client = DeveloperRegistrationServiceClientBuilder.Build();
// The name of the developer registration resource.
// The format is: accounts/{merchantId}/developerRegistration
// where {merchantId} is the ID of the merchant account.
string name = "accounts/" + MerchantConfig.Load().MerchantId + "/developerRegistration";
// Initialize request argument(s)
RegisterGcpRequest request = new RegisterGcpRequest
{
Name = name,
// Specify the email address of the developer to register
DeveloperEmail = developerEmail
};
// Call the RegisterGcp method
DeveloperRegistration response = client.RegisterGcp(request);
Console.WriteLine(JsonConvert.SerializeObject(response, Formatting.Indented));
}
internal static void Main(string[] args)
{
var registration = new RegisterGcpSample();
string developerEmail = "YOUR_EMAIL";
registration.RegisterGcp(developerEmail);
}
}
}
Java
// 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.
package shopping.merchant.samples.accounts.developerregistration.v1;
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);
}
}
Node.js
// 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.
'use strict';
const fs = require('fs');
const authUtils = require('../../../authentication/authenticate.js');
const {DeveloperRegistrationServiceClient} = require('@google-shopping/accounts').v1;
/**
* Registers the GCP project used to call the Merchant API with a developer email.
*/
async function main() {
try {
// Replace with your developer email
const developerEmail = 'developer@example.com';
const config = authUtils.getConfig();
// Read merchant_id from merchant-info.json
const merchant_info =
JSON.parse(fs.readFileSync(config.merchantInfoFile, 'utf8'));
const merchant_id = merchant_info.merchantId;
// Construct parent. Parent is in the format of accounts/{merchant_id}
const parent = 'accounts/' + merchant_id;
// Construct name. Name is in the format of accounts/{merchant_id}/developerRegistration
const name = parent + "/developerRegistration";
// Get credentials
const authClient = await authUtils.getOrGenerateUserCredentials();
// Create options object for the client
const options = {'authClient' : authClient};
// Create client
const developerRegistrationClient = new DeveloperRegistrationServiceClient(options);
// Construct request.
const request = {
name: name,
developerEmail: developerEmail
};
// Run request
const response = await developerRegistrationClient.registerGcp(request);
console.log('GCP project registered successfully:', response);
} catch (error) {
console.error(error.message);
}
}
main();
PHP
<?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.
*/
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();
Python
# -*- coding: utf-8 -*-
# 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.
"""This example registers a GCP project with a developer email."""
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)