本教程介绍了如何使用 Reseller API。
正确配置客户涉及几个相互依赖的步骤, 支持多种 API
上图显示了每个步骤使用哪些 API 来预配 客户:
- 使用 Site Verification API 放置网域验证令牌。
- 使用 Reseller API 创建客户。
- 使用 Directory API 创建第一个用户并将其设为管理员。
- 使用 Reseller API 创建订阅。
- 使用 Site Verification API 来验证网域。
前提条件
- 一个 Google 转销商网域实例。
- 具有完整效力的 Google Workspace 合作伙伴协议。
- Google 账号。
- 在 Partner Sales Console 中接受《服务条款》。
- 下载不同语言的客户端库。
设置环境
如需完成本教程,请设置您的环境。
启用 API
在使用 Google API 之前,您需要先在 Google Cloud 项目中启用这些 API。 您可以在单个 Google Cloud 项目中启用一个或多个 API。在 Google Cloud 控制台中,启用 Reseller API、Site Verification API 和 Admin SDK API 。
创建服务账号
服务账号是供应用使用的特殊账号, 您可以使用服务账号来访问数据或执行操作 或代表 Google Workspace 访问数据 或 Cloud Identity 用户如需了解详情,请参阅 了解服务账号。Google Cloud 控制台
- 在 Google Cloud 控制台中,点击“菜单”图标 > IAM 和管理 > 服务账号。
- 点击创建服务账号。
- 填写服务账号详细信息,然后点击创建并继续。
- 可选:向您的服务账号分配角色,以授予对 Google Cloud 项目资源的访问权限。如需了解详情,请参阅授予、更改和撤消对资源的访问权限。
- 点击继续。
- 可选:输入可以使用此服务账号管理和执行操作的用户或群组。如需了解详情,请参阅管理服务账号模拟。
- 点击完成。记下服务账号的电子邮件地址。
gcloud CLI
- 创建服务账号:
gcloud iam service-accounts create
SERVICE_ACCOUNT_NAME
\ --display-name="SERVICE_ACCOUNT_NAME
" - 可选:向您的服务账号分配角色,以授予对 Google Cloud 项目资源的访问权限。如需了解详情,请参阅授予、更改和撤消对资源的访问权限。
为服务账号创建凭据
您需要以公钥/私钥对的形式获取凭据。这些 您的代码使用凭据来授权 。 <ph type="x-smartling-placeholder">- </ph>
- 在 Google Cloud 控制台中,点击“菜单”图标 > IAM 和管理 > 服务账号。
- 选择您的服务账号。
- 依次点击密钥 > 添加密钥 > 创建新密钥。
- 选择 JSON,然后点击创建。
您的新公钥/私钥对已生成并下载到 作为新文件将下载的 JSON 文件另存为
credentials.json
,位于 工作目录此文件是此密钥的唯一副本。有关如何存储 确保您的密钥安全无虞,请参阅 管理服务账号密钥。 - 点击关闭。
为服务账号设置全网域授权
如需代表 Google Workspace 组织中的用户调用 API,请执行以下操作: 您需要在 Google Cloud 中 超级用户账号访问 Google Workspace 管理控制台。有关 请参阅 将全网域授权委派给服务账号。- 在 Google Cloud 控制台中,点击“菜单”图标 > IAM 和管理 > 服务账号。
- 选择您的服务账号。
- 点击显示高级设置。
- 在“全网域授权”下找到您的服务账号的“Client ID”(客户端 ID)。点击“复制”图标 以将客户端 ID 值复制到剪贴板。
如果您对相关 Google Workspace 账号拥有超级用户访问权限,请点击 查看 Google Workspace 管理控制台,然后以超级用户的身份登录 然后继续按以下步骤操作。
如果您没有相关 Google Workspace 账号的超级用户访问权限, 请与该账号的超级用户联系,并将您的服务账号的客户端 ID 发送给对方 和 OAuth 范围列表,以便他们在管理控制台中完成以下步骤。
- 在 Google 管理控制台中,点击“菜单”图标 > 安全 > 访问权限和数据控制 > API 控件。
- 点击管理全网域授权。
- 点击新增。
- 在“Client ID”(客户端 ID)中,字段中,粘贴您之前复制的客户端 ID。
- 在“OAuth 范围”中字段中,输入应用所需的范围列表(以英文逗号分隔)。这组范围与您在配置 OAuth 权限请求页面时定义的范围相同。
- 点击授权。
使用经过身份验证的凭据创建服务对象
若要开始使用任何 Google API,您首先需要设置身份验证 和凭据Google 客户端库 代您处理此问题。所有库都有用于创建 凭据对象,您可以向所有 API 授予访问权限并将其传递 。一个应用通常应该有一组 凭据,并且仅使用一个云项目来执行所有 Google API 交互。
使用您在创建服务账号时生成的 JSON 密钥文件。
Python
import sys from apiclient.discovery import build from apiclient.http import HttpError from oauth2client.service_account import ServiceAccountCredentials ############## REPLACE WITH YOUR OWN VALUES #################### JSON_PRIVATE_KEY_FILE = 'path/to/json_key_file.json' RESELLER_ADMIN_USER = 'admin@yourresellerdomain.com' CUSTOMER_DOMAIN = 'example.com' CUSTOMER_SITE = 'https://www.example.com' ################################################################ # Full List of scopes: # https://developers.google.com/identity/protocols/googlescopes OAUTH2_SCOPES = [ 'https://reseller.googleapis.com/auth/apps.order', 'https://reseller.googleapis.com/auth/siteverification', 'https://reseller.googleapis.com/auth/admin.directory.user', ] credentials = ServiceAccountCredentials.from_json_keyfile_name( JSON_PRIVATE_KEY_FILE, OAUTH2_SCOPES).create_delegated(RESELLER_ADMIN_USER) reseller_service = build( serviceName='reseller', version='v1', credentials=credentials) directory_service = build( serviceName='admin', version='directory_v1', credentials=credentials) verification_service = build( serviceName='siteVerification', version='v1', credentials=credentials)
Java
// OAuth2 and HTTP import com.google.api.client.googleapis.auth.oauth2.GoogleCredential; import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport; import com.google.api.client.http.HttpResponseException; import com.google.api.client.json.jackson2.JacksonFactory; // Directory API import com.google.api.services.admin.directory.Directory; import com.google.api.services.admin.directory.DirectoryScopes; import com.google.api.services.admin.directory.model.User; import com.google.api.services.admin.directory.model.UserMakeAdmin; import com.google.api.services.admin.directory.model.UserName; // Reseller API import com.google.api.services.reseller.Reseller; import com.google.api.services.reseller.ResellerScopes; import com.google.api.services.reseller.model.Address; import com.google.api.services.reseller.model.Customer; import com.google.api.services.reseller.model.RenewalSettings; import com.google.api.services.reseller.model.Seats; import com.google.api.services.reseller.model.Subscription; // Site Verification API import com.google.api.services.siteVerification.SiteVerification; import com.google.api.services.siteVerification.SiteVerificationScopes; import com.google.api.services.siteVerification.model.SiteVerificationWebResourceGettokenRequest; import com.google.api.services.siteVerification.model.SiteVerificationWebResourceGettokenResponse; import com.google.api.services.siteVerification.model.SiteVerificationWebResourceResource; // Java library imports import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.security.GeneralSecurityException; import java.util.Arrays; import java.util.List; /** * This is a basic example of provisioning a Google Workspace customer. */ public class CodelabExample { // Full List of scopes: // https://developers.google.com/identity/protocols/googlescopes private static final List<String> OAUTH2_SCOPES = Arrays.asList( ResellerScopes.APPS_ORDER, SiteVerificationScopes.SITEVERIFICATION, DirectoryScopes.ADMIN_DIRECTORY_USER ); /***************** REPLACE WITH YOUR OWN VALUES ********************************/ public static final String JSON_PRIVATE_KEY_FILE = "path/to/json_key_file.json"; public static final String RESELLER_ADMIN_USER = "admin@yourresellerdomain.com"; public static final String CUSTOMER_DOMAIN = "example.com"; public static final String CUSTOMER_SITE = "https://www.example.com/"; /*******************************************************************************/ public static void main(String[] args) throws IOException, GeneralSecurityException, FileNotFoundException { // Instantiate services with authenticated credentials GoogleCredential jsonCredentials = GoogleCredential .fromStream(new FileInputStream(JSON_PRIVATE_KEY_FILE)); GoogleCredential credentials = new GoogleCredential.Builder() .setTransport(GoogleNetHttpTransport.newTrustedTransport()) .setJsonFactory(JacksonFactory.getDefaultInstance()) .setServiceAccountScopes(OAUTH2_SCOPES) .setServiceAccountUser(RESELLER_ADMIN_USER) .setServiceAccountPrivateKey(jsonCredentials.getServiceAccountPrivateKey()) .setServiceAccountId(jsonCredentials.getServiceAccountId()) .build(); Reseller resellerService = new Reseller.Builder( credentials.getTransport(), credentials.getJsonFactory(), credentials).setApplicationName("Google Workspace Creator").build(); Directory directoryService = new Directory.Builder( credentials.getTransport(), credentials.getJsonFactory(), credentials).setApplicationName("Google Workspace Creator").build(); SiteVerification verificationService = new SiteVerification.Builder( credentials.getTransport(), credentials.getJsonFactory(), credentials).setApplicationName("Google Workspace Creator").build();
C#
// OAuth2 and HTTP using Google.Apis.Auth.OAuth2; using Google.Apis.Services; // Reseller API using Google.Apis.Reseller.v1; using Google.Apis.Reseller.v1.Data; // Directory API using Google.Apis.Admin.Directory.directory_v1; using User = Google.Apis.Admin.Directory.directory_v1.Data.User; using UserName = Google.Apis.Admin.Directory.directory_v1.Data.UserName; using UserMakeAdmin = Google.Apis.Admin.Directory.directory_v1.Data.UserMakeAdmin; //Site Verification API using Google.Apis.SiteVerification.v1; using Google.Apis.SiteVerification.v1.Data; // System imports using System; using System.IO; class CodelabExample { // Full List of scopes: // https://developers.google.com/identity/protocols/googlescopes static string[] OAUTH2_SCOPES = { ResellerService.Scope.AppsOrder, DirectoryService.Scope.AdminDirectoryUser, SiteVerificationService.Scope.Siteverification }; /***************** REPLACE WITH YOUR OWN VALUES ********************************/ public static String JSON_PRIVATE_KEY_FILE = "path/to/json_key_file.json"; public static String RESELLER_ADMIN_USER = "admin@yourresellerdomain.com"; public static String CUSTOMER_DOMAIN = "example.com"; public static String CUSTOMER_SITE = "https://www.example.com/"; /*******************************************************************************/ static void Main(string[] args) { GoogleCredential credential; using (var stream = new FileStream(JSON_PRIVATE_KEY_FILE, FileMode.Open, FileAccess.Read)) { credential = GoogleCredential .FromStream(stream) .CreateScoped(OAUTH2_SCOPES) .CreateWithUser(RESELLER_ADMIN_USER); } var resellerService = new ResellerService(new BaseClientService.Initializer() { HttpClientInitializer = credential, }); var directoryService = new DirectoryService(new BaseClientService.Initializer() { HttpClientInitializer = credential, }); var verificationService = new SiteVerificationService(new BaseClientService.Initializer() { HttpClientInitializer = credential, });
PHP
// https://developers.google.com/api-client-library/php/ require_once 'vendor/autoload.php'; // Full List of scopes: // https://developers.google.com/identity/protocols/googlescopes $OAUTH2_SCOPES = [ Google_Service_Reseller::APPS_ORDER, Google_Service_SiteVerification::SITEVERIFICATION, Google_Service_Directory::ADMIN_DIRECTORY_USER, ]; ######### REPLACE WITH YOUR OWN VALUES ############### $JSON_PRIVATE_KEY_FILE = 'path/to/json_key_file.json'; $RESELLER_ADMIN_USER = 'admin@yourresellerdomain.com'; $CUSTOMER_DOMAIN = 'example.com'; $CUSTOMER_SITE = 'https://www.example.com/'; ###################################################### $client = new Google_Client(); $client->setAuthConfig($JSON_PRIVATE_KEY_FILE); $client->setSubject($RESELLER_ADMIN_USER); $client->setScopes($OAUTH2_SCOPES); $resellerService = new Google_Service_Reseller($client); $directoryService = new Google_Service_Directory($client); $verificationService = new Google_Service_SiteVerification($client);
Ruby
require 'googleauth' require 'google/apis/reseller_v1' require 'google/apis/site_verification_v1' require 'google/apis/admin_directory_v1' # Full List of scopes: # https://developers.google.com/identity/protocols/googlescopes OAUTH2_SCOPES = [ 'https://reseller.googleapis.com/auth/apps.order', 'https://reseller.googleapis.com/auth/admin.directory.user', 'https://reseller.googleapis.com/auth/siteverification', ] ####### REPLACE WITH YOUR OWN VALUES ############### JSON_PRIVATE_KEY_FILE = 'path/to/json_key_file.json' RESELLER_ADMIN_USER = 'admin@yourresellerdomain.com' CUSTOMER_DOMAIN = 'example.com' CUSTOMER_SITE = 'https://www.example.com/' #################################################### credentials = Google::Auth::ServiceAccountCredentials.make_creds( json_key_io: File.open(JSON_PRIVATE_KEY_FILE), scope: OAUTH2_SCOPES) credentials.sub = RESELLER_ADMIN_USER Google::Apis::RequestOptions.default.authorization = credentials reseller_service = Google::Apis::ResellerV1::ResellerService.new directory_service = Google::Apis::AdminDirectoryV1::DirectoryService.new verification_service = Google::Apis::SiteVerificationV1::SiteVerificationService.new
Node.js
// NOTE: This script needs googleapis 28.0.0 or later as it uses promises const {google} = require('googleapis'); // ############## REPLACE WITH YOUR OWN VALUES #################### const JSON_PRIVATE_KEY_FILE = 'path/to/json_key_file.json'; const RESELLER_ADMIN_USER = 'admin@yourresellerdomain.com'; const CUSTOMER_DOMAIN = 'example.com'; const CUSTOMER_SITE = 'https://www.example.com/'; // ################################################################ // Full List of scopes: https://developers.google.com/identity/protocols/googlescopes const OAUTH2_SCOPES = [ 'https://reseller.googleapis.com/auth/apps.order', 'https://reseller.googleapis.com/auth/siteverification', 'https://reseller.googleapis.com/auth/admin.directory.user', ]; const authJWT = new google.auth.JWT({ keyFile: JSON_PRIVATE_KEY_FILE, scopes: OAUTH2_SCOPES, subject: RESELLER_ADMIN_USER, }); const resellerService = google.reseller({version: 'v1', auth: authJWT}); const directoryService = google.admin({version: 'directory_v1', auth: authJWT}); const verificationService = google.siteVerification({version: 'v1', auth: authJWT});
开始域名验证流程
此步骤为可选步骤,但我们建议您执行 客户域名。在本教程结束时,您需要完成此步骤 验证该网域。
如果您不验证客户的域名,他们将获得以下权限 限制:
- 他们只能访问管理控制台,并在引导下完成 手动域名验证流程。
- 它们可能会在创建 21 天后被暂停。
如需检索网站验证令牌,请执行以下操作:
要检索网站验证令牌,请使用 Site Verification API。 您无法验证域之前是否经过验证,但可以 多次验证网站而不会出现任何问题。取决于 而您要验证的是
INET_DOMAIN
或SITE
类型,verificationMethod
参数各不相同。请从下列选项中选择一项:对于
INET_DOMAIN
类型,请使用以下verificationMethod
之一 参数:DNS_TXT
DNS_CNAME
以下令牌检索示例使用了
INET_DOMAIN
类型:Python
# Retrieve the site verification token and place it according to: # https://developers.google.com/site-verification/v1/getting_started#tokens response = verification_service.webResource().getToken( body={ 'site': { 'type': 'INET_DOMAIN', 'identifier': CUSTOMER_DOMAIN }, 'verificationMethod': 'DNS_TXT' }).execute() print(response)
Java
// Retrieve the site verification token and place it according to: // https://developers.google.com/site-verification/v1/getting_started#tokens SiteVerificationWebResourceGettokenRequest.Site getTokenSite = new SiteVerificationWebResourceGettokenRequest.Site() .setType("INET_DOMAIN") .setIdentifier(CUSTOMER_DOMAIN); SiteVerificationWebResourceGettokenRequest request = new SiteVerificationWebResourceGettokenRequest() .setVerificationMethod("DNS_TXT") .setSite(getTokenSite); SiteVerificationWebResourceGettokenResponse getTokenResponse = verificationService.webResource().getToken(request).execute(); System.out.println("Site Verification Token: " + getTokenResponse.getToken());
C#
// Retrieve the site verification token and place it according to: // https://developers.google.com/site-verification/v1/getting_started#tokens SiteVerificationWebResourceGettokenRequest.SiteData getTokenSite = new SiteVerificationWebResourceGettokenRequest.SiteData() { Type = "INET_DOMAIN", Identifier = CUSTOMER_DOMAIN }; SiteVerificationWebResourceGettokenRequest request = new SiteVerificationWebResourceGettokenRequest() { VerificationMethod = "DNS_TXT", Site = getTokenSite }; SiteVerificationWebResourceGettokenResponse getTokenResponse = verificationService.WebResource.GetToken(request).Execute(); Console.WriteLine("Site Verification Token: {0}", getTokenResponse.Token);
PHP
// Retrieve the site verification token and place it according to: // https://developers.google.com/site-verification/v1/getting_started#tokens $body = new Google_Service_SiteVerification_SiteVerificationWebResourceGettokenRequest([ 'verificationMethod' => 'DNS_TXT', 'site' => [ 'type' => 'INET_DOMAIN', 'identifier' => $CUSTOMER_DOMAIN ] ]); $response = $verificationService->webResource->getToken($body); print_r ($response);
Ruby
# Retrieve the site verification token and place it according to: # https://developers.google.com/site-verification/v1/getting_started#tokens request = Google::Apis::SiteVerificationV1::GetWebResourceTokenRequest.new( site: { type: 'INET_DOMAIN', identifier: CUSTOMER_DOMAIN }, verification_method: 'DNS_TXT' ) response = verification_service.get_web_resource_token(request) puts response.inspect
Node.js
/** * Retrieve the site verification token and place it according to: * https://developers.google.com/site-verification/v1/getting_started#tokens */ const getTokenPromise = verificationService.webResource.getToken({ requestBody: { site: { type: 'INET_DOMAIN', identifier: CUSTOMER_DOMAIN, }, verificationMethod: 'DNS_TXT', } }).then(({data}) => { console.log(data); return data; });
对于
SITE
类型,请使用以下verificationMethod
之一 参数:FILE
META
以下令牌检索示例使用带有
FILE
的SITE
类型 验证方法。使用SITE
验证类型时,您必须 为标识符添加http://
或https://
前缀。Python
# Retrieve the site verification token and place it according to: # https://developers.google.com/site-verification/v1/getting_started#tokens response = verification_service.webResource().getToken( body={ 'site': { 'type': 'SITE', 'identifier': CUSTOMER_SITE }, 'verificationMethod': 'FILE' }).execute() print(response)
Java
// Retrieve the site verification token and place it according to: // https://developers.google.com/site-verification/v1/getting_started#tokens SiteVerificationWebResourceGettokenRequest.Site getTokenSite = new SiteVerificationWebResourceGettokenRequest.Site() .setType("SITE") .setIdentifier(CUSTOMER_SITE); SiteVerificationWebResourceGettokenRequest request = new SiteVerificationWebResourceGettokenRequest() .setVerificationMethod("FILE") .setSite(getTokenSite); SiteVerificationWebResourceGettokenResponse getTokenResponse = verificationService.webResource().getToken(request).execute(); System.out.println("Site Verification Token: " + getTokenResponse.getToken());
C#
// Retrieve the site verification token and place it according to: // https://developers.google.com/site-verification/v1/getting_started#tokens SiteVerificationWebResourceGettokenRequest.SiteData getTokenSite = new SiteVerificationWebResourceGettokenRequest.SiteData() { Type = "SITE", Identifier = CUSTOMER_SITE }; SiteVerificationWebResourceGettokenRequest request = new SiteVerificationWebResourceGettokenRequest() { VerificationMethod = "FILE", Site = getTokenSite }; SiteVerificationWebResourceGettokenResponse getTokenResponse = verificationService.WebResource.GetToken(request).Execute(); Console.WriteLine("Site Verification Token: {0}", getTokenResponse.Token);
PHP
// Retrieve the site verification token and place it according to: // https://developers.google.com/site-verification/v1/getting_started#tokens $body = new Google_Service_SiteVerification_SiteVerificationWebResourceGettokenRequest([ 'verificationMethod' => 'FILE', 'site' => [ 'type' => 'SITE', 'identifier' => $CUSTOMER_DOMAIN ] ]); $response = $verificationService->webResource->getToken($body); print_r($response);
Ruby
# Retrieve the site verification token and place it according to: # https://developers.google.com/site-verification/v1/getting_started#tokens request = Google::Apis::SiteVerificationV1::GetWebResourceTokenRequest.new( site: { type: 'SITE', identifier: CUSTOMER_SITE }, verification_method: 'FILE' ) response = verification_service.get_web_resource_token(request) puts response.inspect
Node.js
/** * Retrieve the site verification token and place it according to: * https://developers.google.com/site-verification/v1/getting_started#tokens */ const getTokenPromise = verificationService.webResource.getToken({ requestBody: { site: { type: 'SITE', identifier: CUSTOMER_SITE, }, verificationMethod: 'FILE', } }).then(({data}) => { console.log(data); return data; });
使用 Reseller API 创建客户
使用 Customers.Get 确定客户是否已存在于 Google Workspace 中的方法:
Python
# Determine if customer domain already has Google Workspace try: response = reseller_service.customers().get( customerId=CUSTOMER_DOMAIN).execute() print('Customer already exists if call succeeds') sys.exit() except HttpError as error: if int(error.resp['status']) == 404: print('Domain available for Google Workspace creation') else: raise
Java
// Determine if customer domain already has Google Workspace try { resellerService.customers().get(CUSTOMER_DOMAIN).execute(); System.out.println("Customer already exists if call succeeds"); System.exit(0); } catch (HttpResponseException e) { if (e.getStatusCode() == 404) { System.out.println("Domain available for Google Workspace creation"); } else { throw e; } }
C#
// Determine if customer domain already has Google Workspace try { resellerService.Customers.Get(CUSTOMER_DOMAIN).Execute(); Console.WriteLine("Customer already exists if call succeeds"); Environment.Exit(0); } catch (Google.GoogleApiException e) { if (e.Error.Code == 404) { Console.WriteLine("Domain available for Google Workspace creation"); } else throw e; }
PHP
// Determine if customer domain already has Google Workspace try { $response = $resellerService->customers->get($CUSTOMER_DOMAIN); exit('Customer already exists if call succeeds'); } catch(Google_Service_Exception $e) { if ($e->getErrors()[0]['reason'] == 'notFound'){ print ("Domain available for Google Workspace creation\n"); } else { throw $e; } }
Ruby
# Determine if customer domain already has Google Workspace begin reseller_service.get_customer(CUSTOMER_DOMAIN) abort('Customer already exists if call succeeds') rescue Google::Apis::ClientError => ex if ex.status_code == 404 puts 'Domain available for Google Workspace creation' else raise ex end end
Node.js
// Determine if customer domain already has Google Workspace const getCustomerPromise = resellerService.customers.get({ customerId: CUSTOMER_DOMAIN }).then(() => { throw new Error('Customer already exists'); }, resErr => { if (resErr.code === 404) { console.log('Domain available for Google Workspace creation'); } else { throw resErr; } });
根据收到的响应,执行以下操作:
如果客户不存在,
customers.get
方法会返回HTTP 404
错误代码。请继续执行下一步,创建 Google Workspace 中的客户记录。如果
customers.get
方法没有返回任何错误,请确定 通过检查响应正文中的alternateEmail
属性。如果缺少alternateEmail
属性, 您必须 转移客户及其订阅。
在 Google Workspace 中创建客户记录。您必须创建一个客户 记录,然后才能使用 以下指南:
alternateEmail
不能与customerDomain
位于同一网域中。postalAddress.countryCode
必须是两个字符的 ISO 国家/地区 代码。
以下示例展示了如何创建客户记录:
Python
# Create customer resource response = reseller_service.customers().insert( body={ 'customerDomain': CUSTOMER_DOMAIN, 'alternateEmail': 'marty.mcfly@gmail.com', 'postalAddress': { 'contactName': 'Marty McFly', 'organizationName': 'Acme Corp', 'postalCode': '10009', 'countryCode': 'US', } }).execute() print(response)
Java
// Create customer resource Address address = new Address() .setContactName("Marty McFly") .setOrganizationName("Acme Corp") .setCountryCode("US") .setPostalCode("10009"); Customer customer = new Customer() .setCustomerDomain(CUSTOMER_DOMAIN) .setAlternateEmail("marty.mcfly@gmail.com") .setPostalAddress(address); Customer customerResponse = resellerService.customers() .insert(customer).execute(); System.out.println("Created Customer:\n" + customerResponse);
C#
// Create customer resource Address address = new Address() { ContactName = "Marty McFly", OrganizationName = "Acme Corp", CountryCode = "US", PostalCode = "10009" }; Customer customer = new Customer() { CustomerDomain = CUSTOMER_DOMAIN, AlternateEmail = "marty.mcfly@gmail.com", PostalAddress = address }; Customer customerResponse = resellerService.Customers.Insert(customer).Execute(); Console.WriteLine("Created Customer:\n{0}", customerResponse);
PHP
// Create customer resource $customer = new Google_Service_Reseller_Customer([ 'customerDomain' => $CUSTOMER_DOMAIN, 'alternateEmail' => 'marty.mcfly@gmail.com', 'postalAddress' => [ 'contactName' => 'Marty McFly', 'organizationName' => 'Acme Corp', 'countryCode' => 'US', 'postalCode' => '10009' ] ]); $response = $resellerService->customers->insert($customer); print_r ($response);
Ruby
# Create customer resource customer = Google::Apis::ResellerV1::Customer.new( customer_domain: CUSTOMER_DOMAIN, alternate_email: 'marty.mcfly@gmail.com', postal_address: { contact_name: 'Marty McFly', organization_name: 'Acme Corp', country_code: 'US', postal_code: '10009'}) response = reseller_service.insert_customer(customer) puts response.inspect
Node.js
// Create customer resource const insertCustomerPromise = resellerService.customers.insert({ requestBody: { customerDomain: CUSTOMER_DOMAIN, alternateEmail: 'marty.mcfly@gmail.com', postalAddress: { contactName: 'Marty McFly', organizationName: 'Acme Corp', postalCode: '10009', countryCode: 'US', } } }).then(({data}) => { console.log(data); return data; });
使用 Admin SDK API 创建首个管理员用户
配置客户后,您必须立即创建第一个用户 请将用户升级为网域超级用户,以便客户可以 访问其新服务并接受所有适用的服务条款。
创建第一个用户并设置其密码。密码必须符合要求 且必须至少包含 8 个字符。如需更多信息 请参阅
user
资源。Python
# Create first admin user response = directory_service.users().insert( body={ 'primaryEmail': 'marty.mcfly@' + CUSTOMER_DOMAIN, 'name': { 'givenName': 'Marty', 'familyName': 'McFly', }, 'password': 'Timecircuit88' }).execute() print(response)
Java
// Create first admin user String userEmail = "marty.mcfly@" + CUSTOMER_DOMAIN; UserName name = new UserName(); name.setGivenName("Marty"); name.setFamilyName("McFly"); User user = new User(); user.setPrimaryEmail(userEmail); user.setPassword("TimeCircuit88"); user.setName(name); User userResponse = directoryService.users().insert(user).execute(); System.out.println("Created User:\n" + userResponse);
C#
// Create first admin user String userEmail = "marty.mcfly@" + CUSTOMER_DOMAIN; UserName name = new UserName() { GivenName = "Marty", FamilyName = "McFly" }; User user = new User() { PrimaryEmail = userEmail, Password = "TimeCircuit88", Name = name }; User userResponse = directoryService.Users.Insert(user).Execute(); Console.WriteLine("Created User:\n{0}", userResponse);
PHP
// Create first admin user $user = new Google_Service_Directory_User([ 'primaryEmail' => 'marty.mcfly@' . $CUSTOMER_DOMAIN, 'password' => 'Timecircuit88', 'name' => [ 'givenName' => 'Marty', 'familyName' => 'McFly', 'fullName' => 'Marty McFly' ] ]); $response = $directoryService->users->insert($user); print_r ($response);
Ruby
# Create first admin user user = Google::Apis::AdminDirectoryV1::User.new( name: { given_name: 'Marty', family_name: 'McFly', full_name: 'Marty McFly' }, password: 'Timecircuit88', primary_email: 'marty.mcfly@' + CUSTOMER_DOMAIN, ) response = directory_service.insert_user(user) puts response.inspect
Node.js
// Create first admin user const insertUserPromise = directoryService.users.insert({ requestBody: { primaryEmail: `marty.mcfly@${CUSTOMER_DOMAIN}`, name: { givenName: 'Marty', familyName: 'McFly', }, password: 'Timecircuit88', } }).then(({data}) => { console.log(data); return data; });
如果创建用户的调用返回
HTTP 409
,则用户名可能 已经属于消费者 Google 账号。将该用户升级为超级用户角色:
Python
# Promote user to admin status response = directory_service.users().makeAdmin( userKey='marty.mcfly@' + CUSTOMER_DOMAIN, body={ 'status': True }).execute()
Java
// Promote user to admin status UserMakeAdmin admin = new UserMakeAdmin(); admin.setStatus(true); directoryService.users().makeAdmin(userEmail, admin).execute(); System.out.println("User promoted to Admin");
C#
// Promote user to admin status UserMakeAdmin admin = new UserMakeAdmin() { Status = true }; directoryService.Users.MakeAdmin(admin, userEmail).Execute(); Console.WriteLine("User promoted to Admin");
PHP
// Promote user to admin status $makeAdmin = new Google_Service_Directory_UserMakeAdmin([ 'status' => true ]); $directoryService->users->makeAdmin( 'marty.mcfly@' . $CUSTOMER_DOMAIN, $makeAdmin );
Ruby
# Promote user to admin status admin_status = Google::Apis::AdminDirectoryV1::UserMakeAdmin.new( status: true ) response = directory_service.make_user_admin('marty.mcfly@' + CUSTOMER_DOMAIN, admin_status)
Node.js
// Promote user to admin status const makeAdminPromise = directoryService.users.makeAdmin({ userKey: `marty.mcfly@${CUSTOMER_DOMAIN}`, requestBody: { status: true } });
为客户创建 Google Workspace 订阅
为客户创建订阅时,您应该将内部
purchaseOrderId
字段中为此客户的交易 ID 或标识符。
如需详细了解特定参数和值,请参阅
管理订阅。
如需创建订阅,请使用 Subscriptions.Insert 调用。以下示例使用了
ANNUAL_YEARLY_PAY
订阅:Python
# Create subscription resource response = reseller_service.subscriptions().insert( customerId=CUSTOMER_DOMAIN, body={ 'customerId': CUSTOMER_DOMAIN, 'skuId': '1010020027', 'plan': { 'planName': 'ANNUAL_MONTHLY_PAY', }, 'seats': { 'numberOfSeats': 5, }, 'renewalSettings': { # only relevant for annual plans 'renewalType': 'RENEW_CURRENT_USERS_MONTHLY_PAY' } }).execute() print(response)
Java
// Create subscription resource Seats seats = new Seats() .setNumberOfSeats(5); Subscription.Plan plan = new Subscription.Plan() .setPlanName("ANNUAL_YEARLY_PAY"); RenewalSettings renewalSettings = new RenewalSettings() .setRenewalType("RENEW_CURRENT_USERS_MONTHLY_PAY"); Subscription subscription = new Subscription() .setCustomerId(CUSTOMER_DOMAIN) .setSeats(seats) .setPlan(plan) .setSkuId("1010020027") .setRenewalSettings(renewalSettings); Subscription subscriptionResponse = resellerService.subscriptions() .insert(CUSTOMER_DOMAIN, subscription).execute(); System.out.println("Created Subscription:\n" + subscriptionResponse);
C#
// Create subscription resource Seats seats = new Seats() { NumberOfSeats = 5 }; Subscription.PlanData plan = new Subscription.PlanData() { PlanName = "ANNUAL_YEARLY_PAY" }; RenewalSettings renewalSettings = new RenewalSettings() { RenewalType = "RENEW_CURRENT_USERS_MONTHLY_PAY" }; Subscription subscription = new Subscription() { CustomerId = CUSTOMER_DOMAIN, Seats = seats, Plan = plan, SkuId = "1010020027", RenewalSettings = renewalSettings }; Subscription subscriptionResponse = resellerService.Subscriptions .Insert(subscription, CUSTOMER_DOMAIN).Execute(); Console.WriteLine("Created Subscription:\n" + subscriptionResponse);
PHP
// Create subscription resource $subscription = new Google_Service_Reseller_Subscription([ 'customerId' => $CUSTOMER_DOMAIN, 'skuId' => '1010020027', 'plan' => [ 'planName' => 'ANNUAL_MONTHLY_PAY' ], 'seats' => [ 'numberOfSeats' => '5' ], 'renewalSettings' => [ 'renewalType' => 'RENEW_CURRENT_USERS_MONTHLY_PAY' ] ]); $response = $resellerService->subscriptions->insert( $CUSTOMER_DOMAIN, $subscription ); print_r ($response);
Ruby
# Create subscription resource subscription = Google::Apis::ResellerV1::Subscription.new( customer_id: CUSTOMER_DOMAIN, sku_id: '1010020027', plan: { plan_name: 'ANNUAL_MONTHLY_PAY' }, seats: { number_of_seats: 5, }, renewal_settings: { renewal_type: 'RENEW_CURRENT_USERS_MONTHLY_PAY' } ) response = reseller_service.insert_subscription(CUSTOMER_DOMAIN, subscription) puts response.inspect
Node.js
// Create subscription resource const insertSubscriptionPromise = resellerService.subscriptions.insert({ customerId: CUSTOMER_DOMAIN, requestBody: { customerId: CUSTOMER_DOMAIN, skuId: '1010020027', plan: { planName: 'ANNUAL_MONTHLY_PAY', }, seats: { numberOfSeats: 5, }, renewalSettings: { // only relevant for annual plans renewalType: 'RENEW_CURRENT_USERS_MONTHLY_PAY', } } }).then(({data}) => { console.log(data); return data; });
在客户管理员完成设置之前,订阅会处于
SUSPENDED
状态 登录并接受服务条款。客户管理员 在首次登录时重定向到服务条款 Google 产品和服务(例如 Gmail 或 Google 云端硬盘)。
验证网域并指定网域所有者
此步骤为可选步骤,但我们建议您执行
客户域名。Site Verification API webResource.insert()
会调用
验证域,并将您在
请求正文的 owners[]
参数。
以下示例展示了如何验证 INET_DOMAIN
:
Python
# Verify domain and designate domain owners response = verification_service.webResource().insert( verificationMethod='DNS_TXT', body={ 'site': { 'type': 'INET_DOMAIN', 'identifier': CUSTOMER_DOMAIN }, 'owners': ['marty.mcfly@' + CUSTOMER_DOMAIN] }).execute() print(response)
Java
// Verify domain and designate domain owners SiteVerificationWebResourceResource.Site verifySite = new SiteVerificationWebResourceResource.Site() .setIdentifier(CUSTOMER_DOMAIN) .setType("INET_DOMAIN"); List<String> owners = Arrays.asList(userEmail); SiteVerificationWebResourceResource resource = new SiteVerificationWebResourceResource() .setSite(verifySite) .setOwners(owners); SiteVerificationWebResourceResource verifyResponse = verificationService.webResource().insert("DNS_TXT", resource).execute(); System.out.println("Site Verification Web Resource:\n" + verifyResponse);
C#
// Verify domain and designate domain owners SiteVerificationWebResourceResource.SiteData verifySite = new SiteVerificationWebResourceResource.SiteData() { Identifier = CUSTOMER_DOMAIN, Type = "INET_DOMAIN" }; string[] owners = { userEmail }; SiteVerificationWebResourceResource resource = new SiteVerificationWebResourceResource() { Site = verifySite, Owners = owners }; SiteVerificationWebResourceResource verifyResponse = verificationService.WebResource.Insert(resource, "DNS_TXT").Execute(); Console.WriteLine("Site Verification Web Resource:\n" + verifyResponse);
PHP
// Verify domain and designate domain owners $body = new Google_Service_SiteVerification_SiteVerificationWebResourceResource([ 'site' => [ 'type' => 'INET_DOMAIN', 'identifier' => $CUSTOMER_DOMAIN, ], 'owners' => ['marty.mcfly@' . $CUSTOMER_DOMAIN] ]); $response = $verificationService->webResource->insert('DNS_TXT', $body); print_r ($response);
Ruby
# Verify domain and designate domain owners webResource = Google::Apis::SiteVerificationV1::SiteVerificationWebResourceResource.new( site: { type: 'INET_DOMAIN', identifier: CUSTOMER_DOMAIN }, owners: ['marty.mcfly@' + CUSTOMER_DOMAIN] ) response = verification_service.insert_web_resource('DNS_TXT', webResource) puts response.inspect
Node.js
// Verify domain and designate domain owners const verifyDomainPromise = verificationService.webResource.insert({ verificationMethod: 'DNS_TXT', requestBody: { site: { type: 'INET_DOMAIN', identifier: CUSTOMER_DOMAIN, }, owners: [`marty.mcfly@${CUSTOMER_DOMAIN}`], } }).then(({data}) => { console.log(data); return data; });
如果成功,此调用将返回 HTTP 200
代码。如果webResource.insert()
无法验证网域,则返回 HTTP 400
级错误代码。重新尝试
带有退避延迟的 webResource.insert()
调用,直到域
已成功通过验证。
总结
以下示例显示了预配 Google Workspace 客户:
Python
"""This is a basic example of provisioning a Google Workspace customer. """ import sys from apiclient.discovery import build from apiclient.http import HttpError from oauth2client.service_account import ServiceAccountCredentials ############## REPLACE WITH YOUR OWN VALUES #################### JSON_PRIVATE_KEY_FILE = 'path/to/json_key_file.json' RESELLER_ADMIN_USER = 'admin@yourresellerdomain.com' CUSTOMER_DOMAIN = 'example.com' CUSTOMER_SITE = 'https://www.example.com' ################################################################ # Full List of scopes: # https://developers.google.com/identity/protocols/googlescopes OAUTH2_SCOPES = [ 'https://reseller.googleapis.com/auth/apps.order', 'https://reseller.googleapis.com/auth/siteverification', 'https://reseller.googleapis.com/auth/admin.directory.user', ] credentials = ServiceAccountCredentials.from_json_keyfile_name( JSON_PRIVATE_KEY_FILE, OAUTH2_SCOPES).create_delegated(RESELLER_ADMIN_USER) reseller_service = build( serviceName='reseller', version='v1', credentials=credentials) directory_service = build( serviceName='admin', version='directory_v1', credentials=credentials) verification_service = build( serviceName='siteVerification', version='v1', credentials=credentials) # Retrieve the site verification token and place it according to: # https://developers.google.com/site-verification/v1/getting_started#tokens response = verification_service.webResource().getToken( body={ 'site': { 'type': 'INET_DOMAIN', 'identifier': CUSTOMER_DOMAIN }, 'verificationMethod': 'DNS_TXT' }).execute() print(response) # Determine if customer domain already has Google Workspace try: response = reseller_service.customers().get( customerId=CUSTOMER_DOMAIN).execute() print('Customer already exists if call succeeds') sys.exit() except HttpError as error: if int(error.resp['status']) == 404: print('Domain available for Google Workspace creation') else: raise # Create customer resource response = reseller_service.customers().insert( body={ 'customerDomain': CUSTOMER_DOMAIN, 'alternateEmail': 'marty.mcfly@gmail.com', 'postalAddress': { 'contactName': 'Marty McFly', 'organizationName': 'Acme Corp', 'postalCode': '10009', 'countryCode': 'US', } }).execute() print(response) # Create first admin user response = directory_service.users().insert( body={ 'primaryEmail': 'marty.mcfly@' + CUSTOMER_DOMAIN, 'name': { 'givenName': 'Marty', 'familyName': 'McFly', }, 'password': 'Timecircuit88' }).execute() print(response) # Promote user to admin status response = directory_service.users().makeAdmin( userKey='marty.mcfly@' + CUSTOMER_DOMAIN, body={ 'status': True }).execute() # Create subscription resource response = reseller_service.subscriptions().insert( customerId=CUSTOMER_DOMAIN, body={ 'customerId': CUSTOMER_DOMAIN, 'skuId': '1010020027', 'plan': { 'planName': 'ANNUAL_MONTHLY_PAY', }, 'seats': { 'numberOfSeats': 5, }, 'renewalSettings': { # only relevant for annual plans 'renewalType': 'RENEW_CURRENT_USERS_MONTHLY_PAY' } }).execute() print(response) # Verify domain and designate domain owners response = verification_service.webResource().insert( verificationMethod='DNS_TXT', body={ 'site': { 'type': 'INET_DOMAIN', 'identifier': CUSTOMER_DOMAIN }, 'owners': ['marty.mcfly@' + CUSTOMER_DOMAIN] }).execute() print(response)
Java
// OAuth2 and HTTP import com.google.api.client.googleapis.auth.oauth2.GoogleCredential; import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport; import com.google.api.client.http.HttpResponseException; import com.google.api.client.json.jackson2.JacksonFactory; // Directory API import com.google.api.services.admin.directory.Directory; import com.google.api.services.admin.directory.DirectoryScopes; import com.google.api.services.admin.directory.model.User; import com.google.api.services.admin.directory.model.UserMakeAdmin; import com.google.api.services.admin.directory.model.UserName; // Reseller API import com.google.api.services.reseller.Reseller; import com.google.api.services.reseller.ResellerScopes; import com.google.api.services.reseller.model.Address; import com.google.api.services.reseller.model.Customer; import com.google.api.services.reseller.model.RenewalSettings; import com.google.api.services.reseller.model.Seats; import com.google.api.services.reseller.model.Subscription; // Site Verification API import com.google.api.services.siteVerification.SiteVerification; import com.google.api.services.siteVerification.SiteVerificationScopes; import com.google.api.services.siteVerification.model.SiteVerificationWebResourceGettokenRequest; import com.google.api.services.siteVerification.model.SiteVerificationWebResourceGettokenResponse; import com.google.api.services.siteVerification.model.SiteVerificationWebResourceResource; // Java library imports import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.security.GeneralSecurityException; import java.util.Arrays; import java.util.List; /** * This is a basic example of provisioning a Google Workspace customer. */ public class CodelabExample { // Full List of scopes: // https://developers.google.com/identity/protocols/googlescopes private static final List<String> OAUTH2_SCOPES = Arrays.asList( ResellerScopes.APPS_ORDER, SiteVerificationScopes.SITEVERIFICATION, DirectoryScopes.ADMIN_DIRECTORY_USER ); /***************** REPLACE WITH YOUR OWN VALUES ********************************/ public static final String JSON_PRIVATE_KEY_FILE = "path/to/json_key_file.json"; public static final String RESELLER_ADMIN_USER = "admin@yourresellerdomain.com"; public static final String CUSTOMER_DOMAIN = "example.com"; public static final String CUSTOMER_SITE = "https://www.example.com/"; /*******************************************************************************/ public static void main(String[] args) throws IOException, GeneralSecurityException, FileNotFoundException { // Instantiate services with authenticated credentials GoogleCredential jsonCredentials = GoogleCredential .fromStream(new FileInputStream(JSON_PRIVATE_KEY_FILE)); GoogleCredential credentials = new GoogleCredential.Builder() .setTransport(GoogleNetHttpTransport.newTrustedTransport()) .setJsonFactory(JacksonFactory.getDefaultInstance()) .setServiceAccountScopes(OAUTH2_SCOPES) .setServiceAccountUser(RESELLER_ADMIN_USER) .setServiceAccountPrivateKey(jsonCredentials.getServiceAccountPrivateKey()) .setServiceAccountId(jsonCredentials.getServiceAccountId()) .build(); Reseller resellerService = new Reseller.Builder( credentials.getTransport(), credentials.getJsonFactory(), credentials).setApplicationName("Google Workspace Creator").build(); Directory directoryService = new Directory.Builder( credentials.getTransport(), credentials.getJsonFactory(), credentials).setApplicationName("Google Workspace Creator").build(); SiteVerification verificationService = new SiteVerification.Builder( credentials.getTransport(), credentials.getJsonFactory(), credentials).setApplicationName("Google Workspace Creator").build(); // Retrieve the site verification token and place it according to: // https://developers.google.com/site-verification/v1/getting_started#tokens SiteVerificationWebResourceGettokenRequest.Site getTokenSite = new SiteVerificationWebResourceGettokenRequest.Site() .setType("INET_DOMAIN") .setIdentifier(CUSTOMER_DOMAIN); SiteVerificationWebResourceGettokenRequest request = new SiteVerificationWebResourceGettokenRequest() .setVerificationMethod("DNS_TXT") .setSite(getTokenSite); SiteVerificationWebResourceGettokenResponse getTokenResponse = verificationService.webResource().getToken(request).execute(); System.out.println("Site Verification Token: " + getTokenResponse.getToken()); // Determine if customer domain already has Google Workspace try { resellerService.customers().get(CUSTOMER_DOMAIN).execute(); System.out.println("Customer already exists if call succeeds"); System.exit(0); } catch (HttpResponseException e) { if (e.getStatusCode() == 404) { System.out.println("Domain available for Google Workspace creation"); } else { throw e; } } // Create customer resource Address address = new Address() .setContactName("Marty McFly") .setOrganizationName("Acme Corp") .setCountryCode("US") .setPostalCode("10009"); Customer customer = new Customer() .setCustomerDomain(CUSTOMER_DOMAIN) .setAlternateEmail("marty.mcfly@gmail.com") .setPostalAddress(address); Customer customerResponse = resellerService.customers() .insert(customer).execute(); System.out.println("Created Customer:\n" + customerResponse); // Create first admin user String userEmail = "marty.mcfly@" + CUSTOMER_DOMAIN; UserName name = new UserName(); name.setGivenName("Marty"); name.setFamilyName("McFly"); User user = new User(); user.setPrimaryEmail(userEmail); user.setPassword("TimeCircuit88"); user.setName(name); User userResponse = directoryService.users().insert(user).execute(); System.out.println("Created User:\n" + userResponse); // Promote user to admin status UserMakeAdmin admin = new UserMakeAdmin(); admin.setStatus(true); directoryService.users().makeAdmin(userEmail, admin).execute(); System.out.println("User promoted to Admin"); // Create subscription resource Seats seats = new Seats() .setNumberOfSeats(5); Subscription.Plan plan = new Subscription.Plan() .setPlanName("ANNUAL_YEARLY_PAY"); RenewalSettings renewalSettings = new RenewalSettings() .setRenewalType("RENEW_CURRENT_USERS_MONTHLY_PAY"); Subscription subscription = new Subscription() .setCustomerId(CUSTOMER_DOMAIN) .setSeats(seats) .setPlan(plan) .setSkuId("1010020027") .setRenewalSettings(renewalSettings); Subscription subscriptionResponse = resellerService.subscriptions() .insert(CUSTOMER_DOMAIN, subscription).execute(); System.out.println("Created Subscription:\n" + subscriptionResponse); // Verify domain and designate domain owners SiteVerificationWebResourceResource.Site verifySite = new SiteVerificationWebResourceResource.Site() .setIdentifier(CUSTOMER_DOMAIN) .setType("INET_DOMAIN"); List<String> owners = Arrays.asList(userEmail); SiteVerificationWebResourceResource resource = new SiteVerificationWebResourceResource() .setSite(verifySite) .setOwners(owners); SiteVerificationWebResourceResource verifyResponse = verificationService.webResource().insert("DNS_TXT", resource).execute(); System.out.println("Site Verification Web Resource:\n" + verifyResponse); } }
C#
// OAuth2 and HTTP using Google.Apis.Auth.OAuth2; using Google.Apis.Services; // Reseller API using Google.Apis.Reseller.v1; using Google.Apis.Reseller.v1.Data; // Directory API using Google.Apis.Admin.Directory.directory_v1; using User = Google.Apis.Admin.Directory.directory_v1.Data.User; using UserName = Google.Apis.Admin.Directory.directory_v1.Data.UserName; using UserMakeAdmin = Google.Apis.Admin.Directory.directory_v1.Data.UserMakeAdmin; //Site Verification API using Google.Apis.SiteVerification.v1; using Google.Apis.SiteVerification.v1.Data; // System imports using System; using System.IO; class CodelabExample { // Full List of scopes: // https://developers.google.com/identity/protocols/googlescopes static string[] OAUTH2_SCOPES = { ResellerService.Scope.AppsOrder, DirectoryService.Scope.AdminDirectoryUser, SiteVerificationService.Scope.Siteverification }; /***************** REPLACE WITH YOUR OWN VALUES ********************************/ public static String JSON_PRIVATE_KEY_FILE = "path/to/json_key_file.json"; public static String RESELLER_ADMIN_USER = "admin@yourresellerdomain.com"; public static String CUSTOMER_DOMAIN = "example.com"; public static String CUSTOMER_SITE = "https://www.example.com/"; /*******************************************************************************/ static void Main(string[] args) { GoogleCredential credential; using (var stream = new FileStream(JSON_PRIVATE_KEY_FILE, FileMode.Open, FileAccess.Read)) { credential = GoogleCredential .FromStream(stream) .CreateScoped(OAUTH2_SCOPES) .CreateWithUser(RESELLER_ADMIN_USER); } var resellerService = new ResellerService(new BaseClientService.Initializer() { HttpClientInitializer = credential, }); var directoryService = new DirectoryService(new BaseClientService.Initializer() { HttpClientInitializer = credential, }); var verificationService = new SiteVerificationService(new BaseClientService.Initializer() { HttpClientInitializer = credential, }); // Retrieve the site verification token and place it according to: // https://developers.google.com/site-verification/v1/getting_started#tokens SiteVerificationWebResourceGettokenRequest.SiteData getTokenSite = new SiteVerificationWebResourceGettokenRequest.SiteData() { Type = "INET_DOMAIN", Identifier = CUSTOMER_DOMAIN }; SiteVerificationWebResourceGettokenRequest request = new SiteVerificationWebResourceGettokenRequest() { VerificationMethod = "DNS_TXT", Site = getTokenSite }; SiteVerificationWebResourceGettokenResponse getTokenResponse = verificationService.WebResource.GetToken(request).Execute(); Console.WriteLine("Site Verification Token: {0}", getTokenResponse.Token); // Determine if customer domain already has Google Workspace try { resellerService.Customers.Get(CUSTOMER_DOMAIN).Execute(); Console.WriteLine("Customer already exists if call succeeds"); Environment.Exit(0); } catch (Google.GoogleApiException e) { if (e.Error.Code == 404) { Console.WriteLine("Domain available for Google Workspace creation"); } else throw e; } // Create customer resource Address address = new Address() { ContactName = "Marty McFly", OrganizationName = "Acme Corp", CountryCode = "US", PostalCode = "10009" }; Customer customer = new Customer() { CustomerDomain = CUSTOMER_DOMAIN, AlternateEmail = "marty.mcfly@gmail.com", PostalAddress = address }; Customer customerResponse = resellerService.Customers.Insert(customer).Execute(); Console.WriteLine("Created Customer:\n{0}", customerResponse); // Create first admin user String userEmail = "marty.mcfly@" + CUSTOMER_DOMAIN; UserName name = new UserName() { GivenName = "Marty", FamilyName = "McFly" }; User user = new User() { PrimaryEmail = userEmail, Password = "TimeCircuit88", Name = name }; User userResponse = directoryService.Users.Insert(user).Execute(); Console.WriteLine("Created User:\n{0}", userResponse); // Promote user to admin status UserMakeAdmin admin = new UserMakeAdmin() { Status = true }; directoryService.Users.MakeAdmin(admin, userEmail).Execute(); Console.WriteLine("User promoted to Admin"); // Create subscription resource Seats seats = new Seats() { NumberOfSeats = 5 }; Subscription.PlanData plan = new Subscription.PlanData() { PlanName = "ANNUAL_YEARLY_PAY" }; RenewalSettings renewalSettings = new RenewalSettings() { RenewalType = "RENEW_CURRENT_USERS_MONTHLY_PAY" }; Subscription subscription = new Subscription() { CustomerId = CUSTOMER_DOMAIN, Seats = seats, Plan = plan, SkuId = "1010020027", RenewalSettings = renewalSettings }; Subscription subscriptionResponse = resellerService.Subscriptions .Insert(subscription, CUSTOMER_DOMAIN).Execute(); Console.WriteLine("Created Subscription:\n" + subscriptionResponse); // Verify domain and designate domain owners SiteVerificationWebResourceResource.SiteData verifySite = new SiteVerificationWebResourceResource.SiteData() { Identifier = CUSTOMER_DOMAIN, Type = "INET_DOMAIN" }; string[] owners = { userEmail }; SiteVerificationWebResourceResource resource = new SiteVerificationWebResourceResource() { Site = verifySite, Owners = owners }; SiteVerificationWebResourceResource verifyResponse = verificationService.WebResource.Insert(resource, "DNS_TXT").Execute(); Console.WriteLine("Site Verification Web Resource:\n" + verifyResponse); } }
PHP
// https://developers.google.com/api-client-library/php/ require_once 'vendor/autoload.php'; // Full List of scopes: // https://developers.google.com/identity/protocols/googlescopes $OAUTH2_SCOPES = [ Google_Service_Reseller::APPS_ORDER, Google_Service_SiteVerification::SITEVERIFICATION, Google_Service_Directory::ADMIN_DIRECTORY_USER, ]; ######### REPLACE WITH YOUR OWN VALUES ############### $JSON_PRIVATE_KEY_FILE = 'path/to/json_key_file.json'; $RESELLER_ADMIN_USER = 'admin@yourresellerdomain.com'; $CUSTOMER_DOMAIN = 'example.com'; $CUSTOMER_SITE = 'https://www.example.com/'; ###################################################### $client = new Google_Client(); $client->setAuthConfig($JSON_PRIVATE_KEY_FILE); $client->setSubject($RESELLER_ADMIN_USER); $client->setScopes($OAUTH2_SCOPES); $resellerService = new Google_Service_Reseller($client); $directoryService = new Google_Service_Directory($client); $verificationService = new Google_Service_SiteVerification($client); // Retrieve the site verification token and place it according to: // https://developers.google.com/site-verification/v1/getting_started#tokens $body = new Google_Service_SiteVerification_SiteVerificationWebResourceGettokenRequest([ 'verificationMethod' => 'DNS_TXT', 'site' => [ 'type' => 'INET_DOMAIN', 'identifier' => $CUSTOMER_DOMAIN ] ]); $response = $verificationService->webResource->getToken($body); print_r ($response); // Determine if customer domain already has Google Workspace try { $response = $resellerService->customers->get($CUSTOMER_DOMAIN); exit('Customer already exists if call succeeds'); } catch(Google_Service_Exception $e) { if ($e->getErrors()[0]['reason'] == 'notFound'){ print ("Domain available for Google Workspace creation\n"); } else { throw $e; } } // Create customer resource $customer = new Google_Service_Reseller_Customer([ 'customerDomain' => $CUSTOMER_DOMAIN, 'alternateEmail' => 'marty.mcfly@gmail.com', 'postalAddress' => [ 'contactName' => 'Marty McFly', 'organizationName' => 'Acme Corp', 'countryCode' => 'US', 'postalCode' => '10009' ] ]); $response = $resellerService->customers->insert($customer); print_r ($response); // Create first admin user $user = new Google_Service_Directory_User([ 'primaryEmail' => 'marty.mcfly@' . $CUSTOMER_DOMAIN, 'password' => 'Timecircuit88', 'name' => [ 'givenName' => 'Marty', 'familyName' => 'McFly', 'fullName' => 'Marty McFly' ] ]); $response = $directoryService->users->insert($user); print_r ($response); // Promote user to admin status $makeAdmin = new Google_Service_Directory_UserMakeAdmin([ 'status' => true ]); $directoryService->users->makeAdmin( 'marty.mcfly@' . $CUSTOMER_DOMAIN, $makeAdmin ); // Create subscription resource $subscription = new Google_Service_Reseller_Subscription([ 'customerId' => $CUSTOMER_DOMAIN, 'skuId' => '1010020027', 'plan' => [ 'planName' => 'ANNUAL_MONTHLY_PAY' ], 'seats' => [ 'numberOfSeats' => '5' ], 'renewalSettings' => [ 'renewalType' => 'RENEW_CURRENT_USERS_MONTHLY_PAY' ] ]); $response = $resellerService->subscriptions->insert( $CUSTOMER_DOMAIN, $subscription ); print_r ($response); // Verify domain and designate domain owners $body = new Google_Service_SiteVerification_SiteVerificationWebResourceResource([ 'site' => [ 'type' => 'INET_DOMAIN', 'identifier' => $CUSTOMER_DOMAIN, ], 'owners' => ['marty.mcfly@' . $CUSTOMER_DOMAIN] ]); $response = $verificationService->webResource->insert('DNS_TXT', $body); print_r ($response);
Ruby
require 'googleauth' require 'google/apis/reseller_v1' require 'google/apis/site_verification_v1' require 'google/apis/admin_directory_v1' # Full List of scopes: # https://developers.google.com/identity/protocols/googlescopes OAUTH2_SCOPES = [ 'https://reseller.googleapis.com/auth/apps.order', 'https://reseller.googleapis.com/auth/admin.directory.user', 'https://reseller.googleapis.com/auth/siteverification', ] ####### REPLACE WITH YOUR OWN VALUES ############### JSON_PRIVATE_KEY_FILE = 'path/to/json_key_file.json' RESELLER_ADMIN_USER = 'admin@yourresellerdomain.com' CUSTOMER_DOMAIN = 'example.com' CUSTOMER_SITE = 'https://www.example.com/' #################################################### credentials = Google::Auth::ServiceAccountCredentials.make_creds( json_key_io: File.open(JSON_PRIVATE_KEY_FILE), scope: OAUTH2_SCOPES) credentials.sub = RESELLER_ADMIN_USER Google::Apis::RequestOptions.default.authorization = credentials reseller_service = Google::Apis::ResellerV1::ResellerService.new directory_service = Google::Apis::AdminDirectoryV1::DirectoryService.new verification_service = Google::Apis::SiteVerificationV1::SiteVerificationService.new # Retrieve the site verification token and place it according to: # https://developers.google.com/site-verification/v1/getting_started#tokens request = Google::Apis::SiteVerificationV1::GetWebResourceTokenRequest.new( site: { type: 'INET_DOMAIN', identifier: CUSTOMER_DOMAIN }, verification_method: 'DNS_TXT' ) response = verification_service.get_web_resource_token(request) puts response.inspect # Determine if customer domain already has Google Workspace begin reseller_service.get_customer(CUSTOMER_DOMAIN) abort('Customer already exists if call succeeds') rescue Google::Apis::ClientError => ex if ex.status_code == 404 puts 'Domain available for Google Workspace creation' else raise ex end end # Create customer resource customer = Google::Apis::ResellerV1::Customer.new( customer_domain: CUSTOMER_DOMAIN, alternate_email: 'marty.mcfly@gmail.com', postal_address: { contact_name: 'Marty McFly', organization_name: 'Acme Corp', country_code: 'US', postal_code: '10009'}) response = reseller_service.insert_customer(customer) puts response.inspect # Create first admin user user = Google::Apis::AdminDirectoryV1::User.new( name: { given_name: 'Marty', family_name: 'McFly', full_name: 'Marty McFly' }, password: 'Timecircuit88', primary_email: 'marty.mcfly@' + CUSTOMER_DOMAIN, ) response = directory_service.insert_user(user) puts response.inspect # Promote user to admin status admin_status = Google::Apis::AdminDirectoryV1::UserMakeAdmin.new( status: true ) response = directory_service.make_user_admin('marty.mcfly@' + CUSTOMER_DOMAIN, admin_status) # Create subscription resource subscription = Google::Apis::ResellerV1::Subscription.new( customer_id: CUSTOMER_DOMAIN, sku_id: '1010020027', plan: { plan_name: 'ANNUAL_MONTHLY_PAY' }, seats: { number_of_seats: 5, }, renewal_settings: { renewal_type: 'RENEW_CURRENT_USERS_MONTHLY_PAY' } ) response = reseller_service.insert_subscription(CUSTOMER_DOMAIN, subscription) puts response.inspect # Verify domain and designate domain owners webResource = Google::Apis::SiteVerificationV1::SiteVerificationWebResourceResource.new( site: { type: 'INET_DOMAIN', identifier: CUSTOMER_DOMAIN }, owners: ['marty.mcfly@' + CUSTOMER_DOMAIN] ) response = verification_service.insert_web_resource('DNS_TXT', webResource) puts response.inspect
Node.js
// NOTE: This script needs googleapis 28.0.0 or later as it uses promises const {google} = require('googleapis'); // ############## REPLACE WITH YOUR OWN VALUES #################### const JSON_PRIVATE_KEY_FILE = 'path/to/json_key_file.json'; const RESELLER_ADMIN_USER = 'admin@yourresellerdomain.com'; const CUSTOMER_DOMAIN = 'example.com'; const CUSTOMER_SITE = 'https://www.example.com/'; // ################################################################ // Full List of scopes: https://developers.google.com/identity/protocols/googlescopes const OAUTH2_SCOPES = [ 'https://reseller.googleapis.com/auth/apps.order', 'https://reseller.googleapis.com/auth/siteverification', 'https://reseller.googleapis.com/auth/admin.directory.user', ]; const authJWT = new google.auth.JWT({ keyFile: JSON_PRIVATE_KEY_FILE, scopes: OAUTH2_SCOPES, subject: RESELLER_ADMIN_USER, }); const resellerService = google.reseller({version: 'v1', auth: authJWT}); const directoryService = google.admin({version: 'directory_v1', auth: authJWT}); const verificationService = google.siteVerification({version: 'v1', auth: authJWT}); // Run all the steps one after each other, and exit as soon as one of them fail Promise.resolve() .then(() => { /** * Retrieve the site verification token and place it according to: * https://developers.google.com/site-verification/v1/getting_started#tokens */ const getTokenPromise = verificationService.webResource.getToken({ requestBody: { site: { type: 'INET_DOMAIN', identifier: CUSTOMER_DOMAIN, }, verificationMethod: 'DNS_TXT', } }).then(({data}) => { console.log(data); return data; }); return getTokenPromise; }) .then(() => { // Determine if customer domain already has Google Workspace const getCustomerPromise = resellerService.customers.get({ customerId: CUSTOMER_DOMAIN }).then(() => { throw new Error('Customer already exists'); }, resErr => { if (resErr.code === 404) { console.log('Domain available for Google Workspace creation'); } else { throw resErr; } }); return getCustomerPromise; }) .then(() => { // Create customer resource const insertCustomerPromise = resellerService.customers.insert({ requestBody: { customerDomain: CUSTOMER_DOMAIN, alternateEmail: 'marty.mcfly@gmail.com', postalAddress: { contactName: 'Marty McFly', organizationName: 'Acme Corp', postalCode: '10009', countryCode: 'US', } } }).then(({data}) => { console.log(data); return data; }); return insertCustomerPromise; }) .then(() => { // Create first admin user const insertUserPromise = directoryService.users.insert({ requestBody: { primaryEmail: `marty.mcfly@${CUSTOMER_DOMAIN}`, name: { givenName: 'Marty', familyName: 'McFly', }, password: 'Timecircuit88', } }).then(({data}) => { console.log(data); return data; }); return insertUserPromise; }).then(() => { // Promote user to admin status const makeAdminPromise = directoryService.users.makeAdmin({ userKey: `marty.mcfly@${CUSTOMER_DOMAIN}`, requestBody: { status: true } }); return makeAdminPromise; }) .then(() => { // Create subscription resource const insertSubscriptionPromise = resellerService.subscriptions.insert({ customerId: CUSTOMER_DOMAIN, requestBody: { customerId: CUSTOMER_DOMAIN, skuId: '1010020027', plan: { planName: 'ANNUAL_MONTHLY_PAY', }, seats: { numberOfSeats: 5, }, renewalSettings: { // only relevant for annual plans renewalType: 'RENEW_CURRENT_USERS_MONTHLY_PAY', } } }).then(({data}) => { console.log(data); return data; }); return insertSubscriptionPromise; }) .then(() => { // Verify domain and designate domain owners const verifyDomainPromise = verificationService.webResource.insert({ verificationMethod: 'DNS_TXT', requestBody: { site: { type: 'INET_DOMAIN', identifier: CUSTOMER_DOMAIN, }, owners: [`marty.mcfly@${CUSTOMER_DOMAIN}`], } }).then(({data}) => { console.log(data); return data; }); return verifyDomainPromise; }) .catch(err => { console.error('Error:', err.message); if (err.code) { console.log('Error code:', err.code); } if (err.errors) { console.log('Details:', err.errors); } });