جاوا
// Copyright 2019 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 com.google.ads.googleads.examples.accountmanagement;
import com.beust.jcommander.Parameter;
import com.google.ads.googleads.examples.utils.ArgumentNames;
import com.google.ads.googleads.examples.utils.CodeSampleParams;
import com.google.ads.googleads.lib.GoogleAdsClient;
import com.google.ads.googleads.lib.utils.FieldMasks;
import com.google.ads.googleads.v17.enums.ManagerLinkStatusEnum.ManagerLinkStatus;
import com.google.ads.googleads.v17.errors.GoogleAdsError;
import com.google.ads.googleads.v17.errors.GoogleAdsException;
import com.google.ads.googleads.v17.services.CustomerClientLinkOperation;
import com.google.ads.googleads.v17.services.CustomerClientLinkServiceClient;
import com.google.ads.googleads.v17.services.CustomerManagerLinkOperation;
import com.google.ads.googleads.v17.services.CustomerManagerLinkServiceClient;
import com.google.ads.googleads.v17.services.GoogleAdsRow;
import com.google.ads.googleads.v17.services.GoogleAdsServiceClient;
import com.google.ads.googleads.v17.services.GoogleAdsServiceClient.SearchPagedResponse;
import com.google.ads.googleads.v17.services.MutateCustomerClientLinkResponse;
import com.google.ads.googleads.v17.services.MutateCustomerManagerLinkResponse;
import com.google.ads.googleads.v17.utils.ResourceNames;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Arrays;
/**
* Demonstrates how to link an existing Google Ads manager customer to an existing Google Ads client
* customer.
*/
public class LinkManagerToClient {
private static class LinkManagerToClientParams extends CodeSampleParams {
@Parameter(names = ArgumentNames.CUSTOMER_ID, required = true)
private long customerId;
@Parameter(names = ArgumentNames.MANAGER_ID, required = true)
private long managerId;
}
public static void main(String[] args) throws IOException {
LinkManagerToClientParams params = new LinkManagerToClientParams();
if (!params.parseArguments(args)) {
// Either pass the required parameters for this example on the command line, or insert them
// into the code here. See the parameter class definition above for descriptions.
params.customerId = Long.parseLong("INSERT_CUSTOMER_ID_HERE");
params.managerId = Long.parseLong("INSERT_MANAGER_ID_HERE");
}
GoogleAdsClient googleAdsClient = null;
try {
googleAdsClient = GoogleAdsClient.newBuilder().fromPropertiesFile().build();
} catch (FileNotFoundException fnfe) {
System.err.printf(
"Failed to load GoogleAdsClient configuration from file. Exception: %s%n", fnfe);
System.exit(1);
} catch (IOException ioe) {
System.err.printf("Failed to create GoogleAdsClient. Exception: %s%n", ioe);
System.exit(1);
}
try {
new LinkManagerToClient().runExample(googleAdsClient, params.customerId, params.managerId);
} catch (GoogleAdsException gae) {
// GoogleAdsException is the base class for most exceptions thrown by an API request.
// Instances of this exception have a message and a GoogleAdsFailure that contains a
// collection of GoogleAdsErrors that indicate the underlying causes of the
// GoogleAdsException.
System.err.printf(
"Request ID %s failed due to GoogleAdsException. Underlying errors:%n",
gae.getRequestId());
int i = 0;
for (GoogleAdsError googleAdsError : gae.getGoogleAdsFailure().getErrorsList()) {
System.err.printf(" Error %d: %s%n", i++, googleAdsError);
}
System.exit(1);
}
}
/** Runs the example. */
private void runExample(GoogleAdsClient googleAdsClient, long clientCustomerId, long managerId) {
// This example assumes that the same credentials will work for both customers, but that may not
// be the case. If you need to use different credentials for each customer, then you may either
// update the client configuration or instantiate two clients, one for each set of credentials.
// Always make sure you use a GoogleAdsClient with the proper credentials to fetch any services
// you need to use.
// Extend an invitation to the client while authenticating as the manager.
googleAdsClient = googleAdsClient.toBuilder().setLoginCustomerId(managerId).build();
CustomerClientLinkOperation.Builder clientLinkOp = CustomerClientLinkOperation.newBuilder();
clientLinkOp
.getCreateBuilder()
.setStatus(ManagerLinkStatus.PENDING)
.setClientCustomer(ResourceNames.customer(clientCustomerId));
String pendingLinkResourceName;
try (CustomerClientLinkServiceClient customerClientLinkServiceClient =
googleAdsClient.getLatestVersion().createCustomerClientLinkServiceClient()) {
MutateCustomerClientLinkResponse response =
customerClientLinkServiceClient.mutateCustomerClientLink(
String.valueOf(managerId), clientLinkOp.build());
pendingLinkResourceName = response.getResult().getResourceName();
System.out.printf(
"Extended an invitation from customer %s to customer %s with client link resource name"
+ " %s%n",
managerId, clientCustomerId, pendingLinkResourceName);
}
// Find the manager_link_id of the link we just created, so we can construct the resource name
// for the link from the client side.
String query =
"SELECT customer_client_link.manager_link_id FROM customer_client_link WHERE"
+ " customer_client_link.resource_name = '"
+ pendingLinkResourceName
+ "'";
long managerLinkId;
try (GoogleAdsServiceClient googleAdsServiceClient =
googleAdsClient.getLatestVersion().createGoogleAdsServiceClient()) {
SearchPagedResponse response =
googleAdsServiceClient.search(String.valueOf(managerId), query);
GoogleAdsRow result = response.iterateAll().iterator().next();
managerLinkId = result.getCustomerClientLink().getManagerLinkId();
}
// Accept the link using the client account.
CustomerManagerLinkOperation.Builder managerLinkOp = CustomerManagerLinkOperation.newBuilder();
managerLinkOp
.getUpdateBuilder()
.setResourceName(
ResourceNames.customerManagerLink(clientCustomerId, managerId, managerLinkId))
.setStatus(ManagerLinkStatus.ACTIVE);
managerLinkOp.setUpdateMask(FieldMasks.allSetFieldsOf(managerLinkOp.getUpdate()));
googleAdsClient = googleAdsClient.toBuilder().setLoginCustomerId(clientCustomerId).build();
try (CustomerManagerLinkServiceClient managerLinkServiceClient =
googleAdsClient.getLatestVersion().createCustomerManagerLinkServiceClient()) {
MutateCustomerManagerLinkResponse response =
managerLinkServiceClient.mutateCustomerManagerLink(
String.valueOf(clientCustomerId), Arrays.asList(managerLinkOp.build()));
System.out.printf(
"Client accepted invitation with resource name %s%n",
response.getResults(0).getResourceName());
}
}
}
سی شارپ
// Copyright 2019 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.
using CommandLine;
using Google.Ads.Gax.Examples;
using Google.Ads.Gax.Util;
using Google.Ads.GoogleAds.Lib;
using Google.Ads.GoogleAds.V17.Errors;
using Google.Ads.GoogleAds.V17.Resources;
using Google.Ads.GoogleAds.V17.Services;
using System;
using System.Collections.Generic;
using System.Linq;
using static Google.Ads.GoogleAds.V17.Enums.ManagerLinkStatusEnum.Types;
namespace Google.Ads.GoogleAds.Examples.V17
{
/// <summary>
/// This code example demonstrates how to link an existing Google Ads manager customer
/// account to an existing Google Ads client customer account.
/// </summary>
public class LinkManagerToClient : ExampleBase
{
/// <summary>
/// Command line options for running the <see cref="LinkManagerToClient"/> example.
/// </summary>
public class Options : OptionsBase
{
/// <summary>
/// ID of the client customer being linked.
/// </summary>
[Option("clientCustomerId", Required = true, HelpText =
"ID of the client customer being linked.")]
public long ClientCustomerId { get; set; }
/// <summary>
/// ID of the manager customer that is being linked to.
/// </summary>
[Option("managerCustomerId", Required = true, HelpText =
"ID of the manager customer that is being linked to.")]
public long ManagerCustomerId { get; set; }
}
/// <summary>
/// Main method, to run this code example as a standalone application.
/// </summary>
/// <param name="args">The command line arguments.</param>
public static void Main(string[] args)
{
Options options = ExampleUtilities.ParseCommandLine<Options>(args);
LinkManagerToClient codeExample = new LinkManagerToClient();
Console.WriteLine(codeExample.Description);
codeExample.Run(new GoogleAdsClient(),
options.ClientCustomerId,
options.ManagerCustomerId);
}
/// <summary>
/// Returns a description about the code example.
/// </summary>
public override string Description =>
"This code example demonstrates how to link an existing Google Ads manager customer " +
"account to an existing Google Ads client customer account.";
/// <summary>
/// Runs the code example.
/// </summary>
/// <param name="client">The Google Ads client.</param>
/// <param name="clientCustomerId">ID of the client customer being linked.</param>
/// <param name="managerCustomerId">ID of the manager customer that is being linked to.
/// </param>
public void Run(GoogleAdsClient client, long managerCustomerId, long clientCustomerId)
{
// Remarks: For ease of understanding, this code example assumes that managerCustomerId
// and clientCustomerId have the login email (and hence the same credentials work for
// both accounts). In real life, this might not be the case, so you'd have a separate
// GoogleAdsClient for managerCustomerId and clientCustomerId.
try
{
// Extend an invitation to the client while authenticating as the manager.
string customerClientLinkResourceName = CreateInvitation(client, managerCustomerId,
clientCustomerId);
// Retrieve the manager link information.
string managerLinkResourceName = GetManagerLinkResourceName(client,
managerCustomerId, clientCustomerId,
customerClientLinkResourceName);
// Accept the manager's invitation while authenticating as the client.
AcceptInvitation(client, clientCustomerId, managerLinkResourceName);
}
catch (GoogleAdsException e)
{
Console.WriteLine("Failure:");
Console.WriteLine($"Message: {e.Message}");
Console.WriteLine($"Failure: {e.Failure}");
Console.WriteLine($"Request ID: {e.RequestId}");
throw;
}
}
/// <summary>
/// Extends an invitation from a manager customer to a client customer.
/// </summary>
/// <param name="client">The Google Ads client.</param>
/// <param name="managerCustomerId">The manager customer ID.</param>
/// <param name="clientCustomerId">The client customer ID.</param>
/// <returns>The invitation resource name.</returns>
private string CreateInvitation(GoogleAdsClient client, long managerCustomerId,
long clientCustomerId)
{
// Get the CustomerClientLinkService.
CustomerClientLinkServiceClient customerClientLinkService =
client.GetService(Services.V17.CustomerClientLinkService);
// Create a client with the manager customer ID as login customer ID.
client.Config.LoginCustomerId = managerCustomerId.ToString();
// Create a customer client link.
CustomerClientLink customerClientLink = new CustomerClientLink()
{
ClientCustomer = ResourceNames.Customer(clientCustomerId),
// Sets the client customer to invite.
Status = ManagerLinkStatus.Pending
};
// Creates a customer client link operation for creating the one above.
CustomerClientLinkOperation customerClientLinkOperation =
new CustomerClientLinkOperation()
{
Create = customerClientLink
};
// Issue a mutate request to create the customer client link.
MutateCustomerClientLinkResponse response =
customerClientLinkService.MutateCustomerClientLink(
managerCustomerId.ToString(), customerClientLinkOperation);
// Prints the result.
string customerClientLinkResourceName = response.Result.ResourceName;
Console.WriteLine($"An invitation has been extended from the manager " +
$"customer {managerCustomerId} to the client customer {clientCustomerId} with " +
$"the customer client link resource name '{customerClientLinkResourceName}'.");
// Returns the resource name of the created customer client link.
return customerClientLinkResourceName;
}
/// <summary>
/// Retrieves the manager link resource name of a customer client link given its resource
/// name.
/// </summary>
/// <param name="client">The Google Ads client.</param>
/// <param name="managerCustomerId">The manager customer ID.</param>
/// <param name="clientCustomerId">The client customer ID.</param>
/// <param name="customerClientLinkResourceName">The customer client link resource
/// name.</param>
/// <returns>The manager link resource name.</returns>
private string GetManagerLinkResourceName(GoogleAdsClient client, long managerCustomerId,
long clientCustomerId, string customerClientLinkResourceName)
{
// Get the GoogleAdsService.
GoogleAdsServiceClient googleAdsService =
client.GetService(Services.V17.GoogleAdsService);
// Create a client with the manager customer ID as login customer ID.
client.Config.LoginCustomerId = managerCustomerId.ToString();
// Creates the query.
string query = "SELECT customer_client_link.manager_link_id FROM " +
"customer_client_link WHERE customer_client_link.resource_name = " +
$"'{customerClientLinkResourceName}'";
// Issue a search request by specifying the page size.
GoogleAdsRow result = googleAdsService.Search(
managerCustomerId.ToString(), query).First();
// Gets the ID and resource name associated to the manager link found.
long managerLinkId = result.CustomerClientLink.ManagerLinkId;
string managerLinkResourceName = ResourceNames.CustomerManagerLink(
clientCustomerId, managerCustomerId, managerLinkId);
// Prints the result.
Console.WriteLine($"Retrieved the manager link of the customer client link: its ID " +
$"is {managerLinkId} and its resource name is '{managerLinkResourceName}'.");
// Returns the resource name of the manager link found.
return managerLinkResourceName;
}
/// <summary>
/// Accepts the invitation.
/// </summary>
/// <param name="client">The Google Ads client.</param>
/// <param name="clientCustomerId">The client customer ID.</param>
/// <param name="managerLinkResourceName">The manager link resource name.</param>
private void AcceptInvitation(GoogleAdsClient client, long clientCustomerId,
string managerLinkResourceName)
{
// Get the CustomerManagerLinkService.
CustomerManagerLinkServiceClient customerManagerLinkService =
client.GetService(Services.V17.CustomerManagerLinkService);
// Create a client with the client customer ID as login customer ID.
client.Config.LoginCustomerId = clientCustomerId.ToString();
// Creates the customer manager link with the updated status.
CustomerManagerLink customerManagerLink = new CustomerManagerLink()
{
ResourceName = managerLinkResourceName,
Status = ManagerLinkStatus.Active
};
// Creates a customer manager link operation for updating the one above.
CustomerManagerLinkOperation customerManagerLinkOperation =
new CustomerManagerLinkOperation()
{
Update = customerManagerLink,
UpdateMask = FieldMasks.AllSetFieldsOf(customerManagerLink)
};
// Issue a mutate request to update the customer manager link.
MutateCustomerManagerLinkResponse response =
customerManagerLinkService.MutateCustomerManagerLink(
clientCustomerId.ToString(), new[] { customerManagerLinkOperation }
);
// Prints the result.
Console.WriteLine($"The client {clientCustomerId} accepted the invitation with " +
$"the resource name '{response.Results[0].ResourceName}");
}
}
}
PHP
<?php
/**
* Copyright 2019 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.
*/
namespace Google\Ads\GoogleAds\Examples\AccountManagement;
require __DIR__ . '/../../vendor/autoload.php';
use GetOpt\GetOpt;
use Google\Ads\GoogleAds\Examples\Utils\ArgumentNames;
use Google\Ads\GoogleAds\Examples\Utils\ArgumentParser;
use Google\Ads\GoogleAds\Lib\OAuth2TokenBuilder;
use Google\Ads\GoogleAds\Lib\V17\GoogleAdsClient;
use Google\Ads\GoogleAds\Lib\V17\GoogleAdsClientBuilder;
use Google\Ads\GoogleAds\Lib\V17\GoogleAdsException;
use Google\Ads\GoogleAds\Util\FieldMasks;
use Google\Ads\GoogleAds\Util\V17\ResourceNames;
use Google\Ads\GoogleAds\V17\Enums\ManagerLinkStatusEnum\ManagerLinkStatus;
use Google\Ads\GoogleAds\V17\Errors\GoogleAdsError;
use Google\Ads\GoogleAds\V17\Resources\CustomerClientLink;
use Google\Ads\GoogleAds\V17\Resources\CustomerManagerLink;
use Google\Ads\GoogleAds\V17\Services\CustomerClientLinkOperation;
use Google\Ads\GoogleAds\V17\Services\CustomerManagerLinkOperation;
use Google\Ads\GoogleAds\V17\Services\MutateCustomerClientLinkRequest;
use Google\Ads\GoogleAds\V17\Services\MutateCustomerManagerLinkRequest;
use Google\Ads\GoogleAds\V17\Services\SearchGoogleAdsRequest;
use Google\ApiCore\ApiException;
/**
* This example demonstrates how to link an existing Google Ads manager customer
* account to an existing Google Ads client customer account.
*/
class LinkManagerToClient
{
private const MANAGER_CUSTOMER_ID = 'INSERT_MANAGER_CUSTOMER_ID_HERE';
private const CUSTOMER_ID = 'INSERT_CUSTOMER_ID_HERE';
public static function main()
{
// Either pass the required parameters for this example on the command line, or insert them
// into the constants above.
$options = (new ArgumentParser())->parseCommandArguments([
ArgumentNames::MANAGER_CUSTOMER_ID => GetOpt::REQUIRED_ARGUMENT,
ArgumentNames::CUSTOMER_ID => GetOpt::REQUIRED_ARGUMENT
]);
try {
self::runExample(
$options[ArgumentNames::MANAGER_CUSTOMER_ID] ?: self::MANAGER_CUSTOMER_ID,
$options[ArgumentNames::CUSTOMER_ID] ?: self::CUSTOMER_ID
);
} catch (GoogleAdsException $googleAdsException) {
printf(
"Request with ID '%s' has failed.%sGoogle Ads failure details:%s",
$googleAdsException->getRequestId(),
PHP_EOL,
PHP_EOL
);
foreach ($googleAdsException->getGoogleAdsFailure()->getErrors() as $error) {
/** @var GoogleAdsError $error */
printf(
"\t%s: %s%s",
$error->getErrorCode()->getErrorCode(),
$error->getMessage(),
PHP_EOL
);
}
exit(1);
} catch (ApiException $apiException) {
printf(
"ApiException was thrown with message '%s'.%s",
$apiException->getMessage(),
PHP_EOL
);
exit(1);
}
}
/**
* Runs the example.
*
* This example assumes that the same credentials will work for both customers,
* but that may not be the case. If you need to use different credentials
* for each customer, then you may either update the client configuration or
* instantiate the clients accordingly, one for each set of credentials. Always make
* sure to update the configuration before fetching any services you need to use.
*
* @param int $managerCustomerId the manager customer ID
* @param int $clientCustomerId the customer ID
*/
public static function runExample(int $managerCustomerId, int $clientCustomerId)
{
// Extends an invitation to the client while authenticating as the manager.
$customerClientLinkResourceName = self::createInvitation(
$managerCustomerId,
$clientCustomerId
);
// Retrieves the manager link information.
$managerLinkResourceName = self::getManagerLinkResourceName(
$managerCustomerId,
$clientCustomerId,
$customerClientLinkResourceName
);
// Accepts the manager's invitation while authenticating as the client.
self::acceptInvitation($clientCustomerId, $managerLinkResourceName);
}
/**
* Extends an invitation from a manager customer to a client customer.
*
* @param int $managerCustomerId the manager customer ID
* @param int $clientCustomerId the customer ID
* @return string the resource name of the customer client link created for the invitation
*/
private static function createInvitation(
int $managerCustomerId,
int $clientCustomerId
) {
// Creates a client with the manager customer ID as login customer ID.
$googleAdsClient = self::createGoogleAdsClient($managerCustomerId);
// Creates a customer client link.
$customerClientLink = new CustomerClientLink([
// Sets the client customer to invite.
'client_customer' => ResourceNames::forCustomer($clientCustomerId),
'status' => ManagerLinkStatus::PENDING
]);
// Creates a customer client link operation for creating the one above.
$customerClientLinkOperation = new CustomerClientLinkOperation();
$customerClientLinkOperation->setCreate($customerClientLink);
// Issues a mutate request to create the customer client link.
$customerClientLinkServiceClient = $googleAdsClient->getCustomerClientLinkServiceClient();
$response = $customerClientLinkServiceClient->mutateCustomerClientLink(
MutateCustomerClientLinkRequest::build(
$managerCustomerId,
$customerClientLinkOperation
)
);
// Prints the result.
$customerClientLinkResourceName = $response->getResult()->getResourceName();
printf(
"An invitation has been extended from the manager customer %d" .
" to the client customer %d with the customer client link resource name '%s'.%s",
$managerCustomerId,
$clientCustomerId,
$customerClientLinkResourceName,
PHP_EOL
);
// Returns the resource name of the created customer client link.
return $customerClientLinkResourceName;
}
/**
* Retrieves the manager link resource name of a customer client link given its resource name.
*
* @param int $managerCustomerId the manager customer ID
* @param int $clientCustomerId the customer ID
* @param string $customerClientLinkResourceName the customer client link resource name
* @return string the manager link resource name
*/
private static function getManagerLinkResourceName(
int $managerCustomerId,
int $clientCustomerId,
string $customerClientLinkResourceName
) {
// Creates a client with the manager customer ID as login customer ID.
$googleAdsClient = self::createGoogleAdsClient($managerCustomerId);
// Creates the query.
$query = "SELECT customer_client_link.manager_link_id FROM customer_client_link" .
" WHERE customer_client_link.resource_name = '$customerClientLinkResourceName'";
// Issues a search request.
$googleAdsServiceClient = $googleAdsClient->getGoogleAdsServiceClient();
$response = $googleAdsServiceClient->search(
SearchGoogleAdsRequest::build($managerCustomerId, $query)
);
// Gets the ID and resource name associated to the manager link found.
$managerLinkId = $response->getIterator()->current()
->getCustomerClientLink()
->getManagerLinkId();
$managerLinkResourceName = ResourceNames::forCustomerManagerLink(
$clientCustomerId,
$managerCustomerId,
$managerLinkId
);
// Prints the result.
printf(
"Retrieved the manager link of the customer client link:" .
" its ID is %d and its resource name is '%s'.%s",
$managerLinkId,
$managerLinkResourceName,
PHP_EOL
);
// Returns the resource name of the manager link found.
return $managerLinkResourceName;
}
/**
* Accepts an invitation.
*
* @param int $clientCustomerId the customer ID
* @param string $managerLinkResourceName the resource name of the manager link to accept
*/
private static function acceptInvitation(
int $clientCustomerId,
string $managerLinkResourceName
) {
// Creates a client with the client customer ID as login customer ID.
$googleAdsClient = self::createGoogleAdsClient($clientCustomerId);
// Creates the customer manager link with the updated status.
$customerManagerLink = new CustomerManagerLink();
$customerManagerLink->setResourceName($managerLinkResourceName);
$customerManagerLink->setStatus(ManagerLinkStatus::ACTIVE);
// Creates a customer manager link operation for updating the one above.
$customerManagerLinkOperation = new CustomerManagerLinkOperation();
$customerManagerLinkOperation->setUpdate($customerManagerLink);
$customerManagerLinkOperation->setUpdateMask(
FieldMasks::allSetFieldsOf($customerManagerLink)
);
// Issues a mutate request to update the customer manager link.
$customerManagerLinkServiceClient =
$googleAdsClient->getCustomerManagerLinkServiceClient();
$response = $customerManagerLinkServiceClient->mutateCustomerManagerLink(
MutateCustomerManagerLinkRequest::build(
$clientCustomerId,
[$customerManagerLinkOperation]
)
);
// Prints the result.
printf(
"The client %d accepted the invitation with the resource name '%s'.%s",
$clientCustomerId,
$response->getResults()[0]->getResourceName(),
PHP_EOL
);
}
/**
* Creates a Google Ads client based on the default configuration file
* and a given login customer id.
*
* @param int $loginCustomerId the login customer ID
* @return GoogleAdsClient the created client
*/
private static function createGoogleAdsClient(int $loginCustomerId)
{
// Generates a refreshable OAuth2 credential for authentication.
$oAuth2Credential = (new OAuth2TokenBuilder())
// Sets the properties based on the default properties file
->fromFile()
->build();
// Builds and returns the Google Ads client
return (new GoogleAdsClientBuilder())
// Sets the properties based on the default properties file
->fromFile()
// Uses the OAuth2 credentials created above.
->withOAuth2Credential($oAuth2Credential)
// Overrides the login customer ID with the given one.
->withLoginCustomerId($loginCustomerId)
->build();
}
}
LinkManagerToClient::main();
پایتون
#!/usr/bin/env python
# Copyright 2019 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 shows how to link a manager customer to a client customer."""
import argparse
import sys
from google.api_core import protobuf_helpers
from google.ads.googleads.client import GoogleAdsClient
from google.ads.googleads.errors import GoogleAdsException
def main(client, customer_id, manager_customer_id):
# This example assumes that the same credentials will work for both
# customers, but that may not be the case. If you need to use different
# credentials for each customer, then you may either update the client
# configuration or instantiate two clients, where at least one points to
# a specific configuration file so that both clients don't read the same
# file located in the $HOME dir.
customer_client_link_service = client.get_service(
"CustomerClientLinkService"
)
# Extend an invitation to the client while authenticating as the manager.
client_link_operation = client.get_type("CustomerClientLinkOperation")
client_link = client_link_operation.create
client_link.client_customer = customer_client_link_service.customer_path(
customer_id
)
client_link.status = client.enums.ManagerLinkStatusEnum.PENDING
response = customer_client_link_service.mutate_customer_client_link(
customer_id=manager_customer_id, operation=client_link_operation
)
resource_name = response.results[0].resource_name
print(
f'Extended an invitation from customer "{manager_customer_id}" to '
f'customer "{customer_id}" with client link resource_name '
f'"{resource_name}"'
)
# Find the manager_link_id of the link we just created, so we can construct
# the resource name for the link from the client side. Note that since we
# are filtering by resource_name, a unique identifier, only one
# customer_client_link resource will be returned in the response
query = f'''
SELECT
customer_client_link.manager_link_id
FROM
customer_client_link
WHERE
customer_client_link.resource_name = "{resource_name}"'''
ga_service = client.get_service("GoogleAdsService")
try:
response = ga_service.search(
customer_id=manager_customer_id, query=query
)
# Since the googleads_service.search method returns an iterator we need
# to initialize an iteration in order to retrieve results, even though
# we know the query will only return a single row.
for row in response.result:
manager_link_id = row.customer_client_link.manager_link_id
except GoogleAdsException as ex:
handle_googleads_exception(ex)
customer_manager_link_service = client.get_service(
"CustomerManagerLinkService"
)
manager_link_operation = client.get_type("CustomerManagerLinkOperation")
manager_link = manager_link_operation.update
manager_link.resource_name = (
customer_manager_link_service.customer_manager_link_path(
customer_id,
manager_customer_id,
manager_link_id,
)
)
manager_link.status = client.enums.ManagerLinkStatusEnum.ACTIVE
client.copy_from(
manager_link_operation.update_mask,
protobuf_helpers.field_mask(None, manager_link._pb),
)
response = customer_manager_link_service.mutate_customer_manager_link(
customer_id=customer_id, operations=[manager_link_operation]
)
print(
"Client accepted invitation with resource_name: "
f'"{response.results[0].resource_name}"'
)
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description=(
"Links an existing manager customer to an existing"
"client customer"
)
)
# The following argument(s) should be provided to run the example.
parser.add_argument(
"-c", "--customer_id", type=str, required=True, help="The customer ID."
)
parser.add_argument(
"-m",
"--manager_customer_id",
type=str,
required=True,
help="The manager customer ID.",
)
args = parser.parse_args()
# GoogleAdsClient will read the google-ads.yaml configuration file in the
# home directory if none is specified.
googleads_client = GoogleAdsClient.load_from_storage(version="v17")
try:
main(googleads_client, args.customer_id, args.manager_customer_id)
except GoogleAdsException as ex:
print(
f'Request with ID "{ex.request_id}" failed with status '
f'"{ex.error.code().name}" and includes the following errors:'
)
for error in ex.failure.errors:
print(f'\tError with message "{error.message}".')
if error.location:
for field_path_element in error.location.field_path_elements:
print(f"\t\tOn field: {field_path_element.field_name}")
sys.exit(1)
روبی
#!/usr/bin/env ruby
# Encoding: utf-8
#
# Copyright 2019 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 demonstrates how to link an existing Google Ads manager customer
# to an existing Google Ads client customer.
require 'optparse'
require 'google/ads/google_ads'
def link_manager_to_client(manager_customer_id, client_customer_id)
# GoogleAdsClient will read a config file from
# ENV['HOME']/google_ads_config.rb when called without parameters
client = Google::Ads::GoogleAds::GoogleAdsClient.new
# This example assumes that the same credentials will work for both customers,
# but that may not be the case. If you need to use different credentials
# for each customer, then you may either update the client configuration or
# instantiate two clients, one for each set of credentials. Always make sure
# to update the configuration before fetching any services you need to use.
# Extend an invitation to the client while authenticating as the manager.
client.configure do |config|
config.login_customer_id = manager_customer_id.to_i
end
client_link = client.resource.customer_client_link do |link|
link.client_customer = client.path.customer(client_customer_id)
link.status = :PENDING
end
client_link_operation = client.operation.create_resource.customer_client_link(client_link)
response = client.service.customer_client_link.mutate_customer_client_link(
customer_id: manager_customer_id,
operation: client_link_operation,
)
client_link_resource_name = response.result.resource_name
puts "Extended an invitation from customer #{manager_customer_id} to " \
"customer #{client_customer_id} with client link resource name " \
"#{client_link_resource_name}."
# Find the manager_link_id of the link we just created, so we can construct
# the resource name for the link from the client side.
query = <<~QUERY
SELECT
customer_client_link.manager_link_id
FROM
customer_client_link
WHERE
customer_client_link.resource_name = '#{client_link_resource_name}'
QUERY
response = client.service.google_ads.search(customer_id: manager_customer_id, query: query)
manager_link_id = response.first.customer_client_link.manager_link_id
# Accept the link using the client account.
client.configure do |config|
config.login_customer_id = client_customer_id.to_i
end
manager_link_resource_name = client.path.customer_manager_link(
client_customer_id,
manager_customer_id,
manager_link_id,
)
manager_link_operation =
client.operation.update_resource.customer_manager_link(manager_link_resource_name) do |link|
link.status = :ACTIVE
end
response = client.service.customer_manager_link.mutate_customer_manager_link(
customer_id: client_customer_id,
operations: [manager_link_operation],
)
puts "Client accepted invitation with resource name " \
"#{response.results.first.resource_name}."
end
if __FILE__ == $0
options = {}
# The following parameter(s) should be provided to run the example. You can
# either specify these by changing the INSERT_XXX_ID_HERE values below, or on
# the command line.
#
# Parameters passed on the command line will override any parameters set in
# code.
#
# Running the example with -h will print the command line usage.
options[:manager_customer_id] = 'INSERT_MANAGER_CUSTOMER_ID_HERE'
options[:customer_id] = 'INSERT_CUSTOMER_ID_HERE'
OptionParser.new do |opts|
opts.banner = sprintf('Usage: %s [options]', File.basename(__FILE__))
opts.separator ''
opts.separator 'Options:'
opts.on('-C', '--customer-id CUSTOMER-ID', String, 'Customer ID') do |v|
options[:customer_id] = v
end
opts.on('-M', '--manager-customer-id MANAGER-CUSTOMER-ID', String,
'Manager Customer ID') do |v|
options[:manager_customer_id] = v
end
opts.separator ''
opts.separator 'Help:'
opts.on_tail('-h', '--help', 'Show this message') do
puts opts
exit
end
end.parse!
begin
link_manager_to_client(
options.fetch(:manager_customer_id).tr("-", ""),
options.fetch(:customer_id).tr("-", ""),
)
rescue Google::Ads::GoogleAds::Errors::GoogleAdsError => e
e.failure.errors.each do |error|
STDERR.printf("Error with message: %s\n", error.message)
if error.location
error.location.field_path_elements.each do |field_path_element|
STDERR.printf("\tOn field: %s\n", field_path_element.field_name)
end
end
error.error_code.to_h.each do |k, v|
next if v == :UNSPECIFIED
STDERR.printf("\tType: %s\n\tCode: %s\n", k, v)
end
end
raise
end
end
پرل
#!/usr/bin/perl -w
#
# Copyright 2019, 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.
#
# This example demonstrates how to link an existing Google Ads manager customer
# account to an existing Google Ads client customer account.
use strict;
use warnings;
use utf8;
use FindBin qw($Bin);
use lib "$Bin/../../lib";
use Google::Ads::GoogleAds::Client;
use Google::Ads::GoogleAds::Utils::GoogleAdsHelper;
use Google::Ads::GoogleAds::Utils::FieldMasks;
use Google::Ads::GoogleAds::V17::Resources::CustomerClientLink;
use Google::Ads::GoogleAds::V17::Resources::CustomerManagerLink;
use Google::Ads::GoogleAds::V17::Enums::ManagerLinkStatusEnum
qw(PENDING ACTIVE);
use
Google::Ads::GoogleAds::V17::Services::CustomerClientLinkService::CustomerClientLinkOperation;
use
Google::Ads::GoogleAds::V17::Services::CustomerManagerLinkService::CustomerManagerLinkOperation;
use Google::Ads::GoogleAds::V17::Utils::ResourceNames;
use Getopt::Long qw(:config auto_help);
use Pod::Usage;
use Cwd qw(abs_path);
# The following parameter(s) should be provided to run the example. You can
# either specify these by changing the INSERT_XXX_ID_HERE values below, or on
# the command line.
#
# Parameters passed on the command line will override any parameters set in
# code.
#
# Running the example with -h will print the command line usage.
my $manager_customer_id = "INSERT_MANAGER_CUSTOMER_ID_HERE";
my $customer_id = "INSERT_CUSTOMER_ID_HERE";
# This example assumes that the same credentials will work for both customers,
# but that may not be the case. If you need to use different credentials
# for each customer, then you may either update the client configuration or
# instantiate two clients, one for each set of credentials. Always make sure
# to update the configuration before fetching any services you need to use.
sub link_manager_to_client {
my ($api_client, $manager_customer_id, $api_client_customer_id) = @_;
# Step 1: Extend an invitation to the client customer while authenticating
# as the manager.
$api_client->set_login_customer_id($manager_customer_id);
# Create a customer client link.
my $api_client_link =
Google::Ads::GoogleAds::V17::Resources::CustomerClientLink->new({
clientCustomer =>
Google::Ads::GoogleAds::V17::Utils::ResourceNames::customer(
$api_client_customer_id),
status => PENDING
});
# Create a customer client link operation.
my $api_client_link_operation =
Google::Ads::GoogleAds::V17::Services::CustomerClientLinkService::CustomerClientLinkOperation
->new({
create => $api_client_link
});
# Add the customer client link to extend an invitation to the client customer.
my $api_client_link_response =
$api_client->CustomerClientLinkService()->mutate({
customerId => $manager_customer_id,
operation => $api_client_link_operation
});
my $api_client_link_resource_name =
$api_client_link_response->{result}{resourceName};
printf "Extended an invitation from the manager customer %d to the " .
"client customer %d with the customer client link resource name: '%s'.\n",
$manager_customer_id, $api_client_customer_id,
$api_client_link_resource_name;
# Step 2: Get the 'manager_link_id' of the client link we just created,
# to construct the resource name of the manager link from the client side.
my $search_query =
"SELECT customer_client_link.manager_link_id FROM customer_client_link " .
"WHERE customer_client_link.resource_name = '$api_client_link_resource_name'";
my $search_response = $api_client->GoogleAdsService()->search({
customerId => $manager_customer_id,
query => $search_query
});
my $manager_link_id =
$search_response->{results}[0]{customerClientLink}{managerLinkId};
my $manager_link_resource_name =
Google::Ads::GoogleAds::V17::Utils::ResourceNames::customer_manager_link(
$api_client_customer_id, $manager_customer_id, $manager_link_id);
# Step 3: Accept the manager customer's link invitation while authenticating
# as the client.
$api_client->set_login_customer_id($api_client_customer_id);
# Create a customer manager link.
my $manager_link =
Google::Ads::GoogleAds::V17::Resources::CustomerManagerLink->new({
resourceName => $manager_link_resource_name,
status => ACTIVE
});
# Create a customer manager link operation.
my $manager_link_operation =
Google::Ads::GoogleAds::V17::Services::CustomerManagerLinkService::CustomerManagerLinkOperation
->new({
update => $manager_link,
updateMask => all_set_fields_of($manager_link)});
# Update the customer manager link to accept the invitation.
my $manager_link_response =
$api_client->CustomerManagerLinkService()->mutate({
customerId => $api_client_customer_id,
operations => [$manager_link_operation]});
printf "The client customer %d accepted the invitation with " .
"the customer manager link resource name: '%s'.\n",
$api_client_customer_id,
$manager_link_response->{results}[0]{resourceName};
return 1;
}
# Don't run the example if the file is being included.
if (abs_path($0) ne abs_path(__FILE__)) {
return 1;
}
# Get Google Ads Client, credentials will be read from ~/googleads.properties.
my $api_client = Google::Ads::GoogleAds::Client->new();
# By default examples are set to die on any server returned fault.
$api_client->set_die_on_faults(1);
# Parameters passed on the command line will override any parameters set in code.
GetOptions(
"manager_customer_id=s" => \$manager_customer_id,
"customer_id=s" => \$customer_id
);
# Print the help message if the parameters are not initialized in the code nor
# in the command line.
pod2usage(2) if not check_params($manager_customer_id, $customer_id);
# Call the example.
link_manager_to_client(
$api_client,
$manager_customer_id =~ s/-//gr,
$customer_id =~ s/-//gr
);
=pod
=head1 NAME
link_manager_to_client
=head1 DESCRIPTION
This example demonstrates how to link an existing Google Ads manager customer
account to an existing Google Ads client customer account.
=head1 SYNOPSIS
link_manager_to_client.pl [options]
-help Show the help message.
-manager_customer_id The Google Ads manager customer ID.
-customer_id The Google Ads customer ID.
=cut