Java
// Copyright 2020 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.v13.enums.MerchantCenterLinkStatusEnum.MerchantCenterLinkStatus; import com.google.ads.googleads.v13.errors.GoogleAdsError; import com.google.ads.googleads.v13.errors.GoogleAdsException; import com.google.ads.googleads.v13.resources.MerchantCenterLink; import com.google.ads.googleads.v13.services.ListMerchantCenterLinksRequest; import com.google.ads.googleads.v13.services.ListMerchantCenterLinksResponse; import com.google.ads.googleads.v13.services.MerchantCenterLinkOperation; import com.google.ads.googleads.v13.services.MerchantCenterLinkServiceClient; import com.google.ads.googleads.v13.services.MutateMerchantCenterLinkResponse; import com.google.ads.googleads.v13.services.MutateMerchantCenterLinkResult; import java.io.FileNotFoundException; import java.io.IOException; /** * Demonstrates how to approve a Merchant Center link request. * * <p>Prerequisite: You need to have access to a Merchant Center account. You can find instructions * to create a Merchant Center account here: https://support.google.com/merchants/answer/188924. * * <p>To run this example, you must use the Merchant Center UI or the Content API for Shopping to * send a link request between your Merchant Center and Google Ads accounts. */ public class ApproveMerchantCenterLink { private static class ApproveMerchantCenterLinkParams extends CodeSampleParams { @Parameter(names = ArgumentNames.CUSTOMER_ID, required = true) private Long customerId; @Parameter(names = ArgumentNames.MERCHANT_CENTER_ACCOUNT_ID, required = true) private Long merchantCenterAccountId; } public static void main(String[] args) { ApproveMerchantCenterLinkParams params = new ApproveMerchantCenterLinkParams(); 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.merchantCenterAccountId = Long.parseLong("INSERT_MERCHANT_CENTER_ACCOUNT_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 ApproveMerchantCenterLink() .runExample(googleAdsClient, params.customerId, params.merchantCenterAccountId); } 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. * * @param googleAdsClient the Google Ads API client. * @param customerId the client customer ID of the Google Ads account to approve the link request. * @param merchantCenterAccountId the Merchant Center account ID for the account requesting to * link. * @throws GoogleAdsException if an API request failed with one or more service errors. */ private void runExample( GoogleAdsClient googleAdsClient, long customerId, long merchantCenterAccountId) { // Approves a pending link request for a Google Ads account with customerId from a Merchant // Center account with merchantCenterAccountId. try (MerchantCenterLinkServiceClient merchantCenterLinkService = googleAdsClient.getLatestVersion().createMerchantCenterLinkServiceClient()) { ListMerchantCenterLinksResponse response = merchantCenterLinkService.listMerchantCenterLinks( ListMerchantCenterLinksRequest.newBuilder() .setCustomerId(Long.toString(customerId)) .build()); System.out.printf( "%d Merchant Center link(s) found with the following details:%n", response.getMerchantCenterLinksCount()); for (MerchantCenterLink merchantCenterLink : response.getMerchantCenterLinksList()) { System.out.printf( "Link '%s' has status '%s'.%n", merchantCenterLink.getResourceName(), merchantCenterLink.getStatus()); // Checks if there is a link for the Merchant Center account we are looking for, then only // approves the link if it is in a 'PENDING' state. if (merchantCenterAccountId == merchantCenterLink.getId() && merchantCenterLink.getStatus() == MerchantCenterLinkStatus.PENDING) { // Updates the status of Merchant Center link to 'ENABLED' to approve the link. updateMerchantCenterLinkStatus( merchantCenterLinkService, customerId, merchantCenterLink, MerchantCenterLinkStatus.ENABLED); } } } } /** * Updates the status of a Merchant Center link request for a given resource name. * * @param merchantCenterLinkServiceClient the MerchantCenterLinkService client. * @param customerId the client customer ID of the Google Ads account to approve the link request. * @param merchantCenterLink the MerchantCenterLink object to update. * @param status the new status to set on the link. * @throws GoogleAdsException if an API request failed with one or more service errors. */ private void updateMerchantCenterLinkStatus( MerchantCenterLinkServiceClient merchantCenterLinkServiceClient, long customerId, MerchantCenterLink merchantCenterLink, MerchantCenterLinkStatus status) { // Creates an updated MerchantCenterLink object derived from the original, but with the new // status. MerchantCenterLink updatedMerchantCenterLink = merchantCenterLink.toBuilder().setStatus(status).build(); // Constructs an operation that will update the merchantCenterLink, using the FieldMasks compare // utility to derive the update mask from the changes. This mask tells the Google Ads API which // attributes of the merchantCenterLink to change. In this case we only want to change the // MerchantCenterLinkStatus. MerchantCenterLinkOperation operation = MerchantCenterLinkOperation.newBuilder() .setUpdate(updatedMerchantCenterLink) .setUpdateMask(FieldMasks.compare(merchantCenterLink, updatedMerchantCenterLink)) .build(); // Sends the operation in a mutate request. MutateMerchantCenterLinkResponse response = merchantCenterLinkServiceClient.mutateMerchantCenterLink( String.valueOf(customerId), operation); // Prints the resource name of the updated object. MutateMerchantCenterLinkResult merchantCenterLinkResult = response.getResult(); System.out.printf( "Updated Merchant Center link with resource name: '%s'.%n", merchantCenterLinkResult.getResourceName()); } }
C#
// Copyright 2020 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.V13.Errors; using Google.Ads.GoogleAds.V13.Resources; using Google.Ads.GoogleAds.V13.Services; using System; using System.Collections.Generic; using static Google.Ads.GoogleAds.V13.Enums.MerchantCenterLinkStatusEnum.Types; namespace Google.Ads.GoogleAds.Examples.V13 { /// <summary> /// This code example demonstrates how to approve a Merchant Center link request. /// /// Prerequisite: You need to have access to a Merchant Center account. You can find /// instructions to create a Merchant Center account here: /// https://support.google.com/merchants/answer/188924. /// /// To run this code example, you must use the Merchant Center UI or the Content API for /// Shopping to send a link request between your Merchant Center and Google Ads accounts. /// </summary> public class ApproveMerchantCenterLink : ExampleBase { /// <summary> /// Command line options for running the <see cref="ApproveMerchantCenterLink"/> example. /// </summary> public class Options : OptionsBase { /// <summary> /// The Google Ads customer ID for which the call is made. /// </summary> [Option("customerId", Required = true, HelpText = "The Google Ads customer ID for which the call is made.")] public long CustomerId { get; set; } /// <summary> /// ID of the Merchant center whose link request is to be approved. /// </summary> [Option("merchantCenterAccountId", Required = true, HelpText = "ID of the Merchant center whose link request is to be approved.")] public long MerchantCenterAccountId { 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); ApproveMerchantCenterLink codeExample = new ApproveMerchantCenterLink(); Console.WriteLine(codeExample.Description); codeExample.Run(new GoogleAdsClient(), options.CustomerId, options.MerchantCenterAccountId); } /// <summary> /// Returns a description about the code example. /// </summary> public override string Description => "This code example demonstrates how to approve a Merchant Center link request." + "\nPrerequisite: You need to have access to a Merchant Center account. You can find " + "instructions to create a Merchant Center account here: " + "https://support.google.com/merchants/answer/188924. To run this code example, you " + "must use the Merchant Center UI or the Content API for Shopping to send a link " + "request between your Merchant Center and Google Ads accounts."; /// <summary> /// Runs the code example. /// </summary> /// <param name="client">The Google Ads client.</param> /// <param name="customerId">The Google Ads customer ID for which the call is made.</param> /// <param name="merchantCenterAccountId">ID of the Merchant center whose link request is to be /// approved</param> public void Run(GoogleAdsClient client, long customerId, long merchantCenterAccountId) { // Get the MerchantCenterLink. MerchantCenterLinkServiceClient merchantCenterLinkService = client.GetService( Services.V13.MerchantCenterLinkService); try { // Retrieve all the existing Merchant Center links. ListMerchantCenterLinksResponse response = merchantCenterLinkService.ListMerchantCenterLinks(customerId.ToString()); Console.WriteLine($"{response.MerchantCenterLinks.Count} Merchant Center link(s)" + $" found with the following details:"); // Iterate the results, and filter for links with pending status. foreach (MerchantCenterLink merchantCenterLink in response.MerchantCenterLinks) { Console.Write($"Link '{merchantCenterLink.ResourceName}' has status " + $"'{merchantCenterLink.Status}'."); // Checks if there is a link for the Merchant Center account we are looking // for, then only approves the link if it is in a 'PENDING' state. if (merchantCenterLink.Status == MerchantCenterLinkStatus.Pending && merchantCenterLink.Id == merchantCenterAccountId) { UpdateMerchantCenterLinkStatus(customerId, merchantCenterLinkService, merchantCenterLink, MerchantCenterLinkStatus.Enabled); } } } catch (GoogleAdsException e) { Console.WriteLine("Failure:"); Console.WriteLine($"Message: {e.Message}"); Console.WriteLine($"Failure: {e.Failure}"); Console.WriteLine($"Request ID: {e.RequestId}"); throw; } } /// <summary> /// Updates the status of a Merchant Center link request for a given resource name. /// </summary> /// <param name="customerId">The customer identifier.</param> /// <param name="merchantCenterLinkService">The merchant center link service.</param> /// <param name="merchantCenterLink">The merchant center link.</param> /// <param name="status"></param> private static void UpdateMerchantCenterLinkStatus(long customerId, MerchantCenterLinkServiceClient merchantCenterLinkService, MerchantCenterLink merchantCenterLink, MerchantCenterLinkStatus status) { // Enables the pending link. MerchantCenterLink linkToUpdate = new MerchantCenterLink() { ResourceName = merchantCenterLink.ResourceName, Status = status }; // Creates an operation. MerchantCenterLinkOperation operation = new MerchantCenterLinkOperation() { Update = linkToUpdate, UpdateMask = FieldMasks.AllSetFieldsOf(linkToUpdate) }; // Updates the link. MutateMerchantCenterLinkResponse mutateResponse = merchantCenterLinkService.MutateMerchantCenterLink( customerId.ToString(), operation); // Displays the result. Console.WriteLine($"The status of Merchant Center Link with resource name " + $"'{mutateResponse.Result.ResourceName}' to Google Ads account : " + $"{customerId} was updated to {status}."); } } }
PHP
<?php /** * Copyright 2020 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\V13\GoogleAdsClient; use Google\Ads\GoogleAds\Lib\V13\GoogleAdsClientBuilder; use Google\Ads\GoogleAds\Lib\V13\GoogleAdsException; use Google\Ads\GoogleAds\Util\FieldMasks; use Google\Ads\GoogleAds\V13\Enums\MerchantCenterLinkStatusEnum\MerchantCenterLinkStatus; use Google\Ads\GoogleAds\V13\Errors\GoogleAdsError; use Google\Ads\GoogleAds\V13\Resources\MerchantCenterLink; use Google\Ads\GoogleAds\V13\Services\MerchantCenterLinkOperation; use Google\Ads\GoogleAds\V13\Services\MerchantCenterLinkServiceClient; use Google\ApiCore\ApiException; /** * Demonstrates how to approve a Merchant Center link request. * * <p>Prerequisite: You need to have access to a Merchant Center account. You can find instructions * to create a Merchant Center account here: https://support.google.com/merchants/answer/188924. * * <p>To run this example, you must use the Merchant Center UI or the Content API for Shopping to * send a link request between your Merchant Center and Google Ads accounts. * See https://support.google.com/merchants/answer/6159060 for details. */ class ApproveMerchantCenterLink { private const CUSTOMER_ID = 'INSERT_CUSTOMER_ID_HERE'; private const MERCHANT_CENTER_ACCOUNT_ID = 'INSERT_MERCHANT_CENTER_ACCOUNT_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::CUSTOMER_ID => GetOpt::REQUIRED_ARGUMENT, ArgumentNames::MERCHANT_CENTER_ACCOUNT_ID => GetOpt::REQUIRED_ARGUMENT ]); // Generate a refreshable OAuth2 credential for authentication. $oAuth2Credential = (new OAuth2TokenBuilder())->fromFile()->build(); // Construct a Google Ads client configured from a properties file and the // OAuth2 credentials above. $googleAdsClient = (new GoogleAdsClientBuilder())->fromFile() ->withOAuth2Credential($oAuth2Credential) ->build(); try { self::runExample( $googleAdsClient, $options[ArgumentNames::CUSTOMER_ID] ?: self::CUSTOMER_ID, $options[ArgumentNames::MERCHANT_CENTER_ACCOUNT_ID] ?: self::MERCHANT_CENTER_ACCOUNT_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. * * @param GoogleAdsClient $googleAdsClient the Google Ads API client * @param int $customerId the customer ID * @param int $merchantCenterAccountId the Merchant Center account ID */ public static function runExample( GoogleAdsClient $googleAdsClient, int $customerId, int $merchantCenterAccountId ) { // Lists all merchant links of the specified customer ID. $merchantCenterLinkServiceClient = $googleAdsClient->getMerchantCenterLinkServiceClient(); $response = $merchantCenterLinkServiceClient->listMerchantCenterLinks($customerId); printf( "%d Merchant Center link(s) found with the following details:%s", $response->getMerchantCenterLinks()->count(), PHP_EOL ); foreach ($response->getMerchantCenterLinks() as $merchantCenterLink) { /** @var MerchantCenterLink $merchantCenterLink */ printf( "Link '%s' has status '%s'.%s", $merchantCenterLink->getResourceName(), MerchantCenterLinkStatus::name($merchantCenterLink->getStatus()), PHP_EOL ); // Approves a pending link request for a Google Ads account with the specified customer // ID from a Merchant Center account with the specified Merchant Center account ID. if ( $merchantCenterLink->getId() === $merchantCenterAccountId && $merchantCenterLink->getStatus() === MerchantCenterLinkStatus::PENDING ) { // Updates the status of Merchant Center link to 'ENABLED' to approve the link. self::updateMerchantCenterLinkStatus( $merchantCenterLinkServiceClient, $customerId, $merchantCenterLink, MerchantCenterLinkStatus::ENABLED ); // There is only one MerchantCenterLink object for a given Google Ads account and // Merchant Center account, so we can break early. break; } } } /** * Updates the status of a Merchant Center link with a specified Merchant Center link status. * * @param MerchantCenterLinkServiceClient $merchantCenterLinkServiceClient the Merchant Center * link service client * @param int $customerId the customer ID * @param MerchantCenterLink $merchantCenterLink the Merchant Center link to update * @param int $newMerchantCenterLinkStatus the status to be updated to */ private static function updateMerchantCenterLinkStatus( MerchantCenterLinkServiceClient $merchantCenterLinkServiceClient, int $customerId, MerchantCenterLink $merchantCenterLink, int $newMerchantCenterLinkStatus ) { // Creates an updated MerchantCenterLink object derived from the original, but with the // specified status. $merchantCenterLinkToUpdate = new MerchantCenterLink([ 'resource_name' => $merchantCenterLink->getResourceName(), 'status' => $newMerchantCenterLinkStatus ]); // Constructs an operation that will update the Merchant Center link, // using the FieldMasks utility to derive the update mask. This mask tells the // Google Ads API which attributes of the Merchant Center link you want to change. $merchantCenterLinkOperation = new MerchantCenterLinkOperation(); $merchantCenterLinkOperation->setUpdate($merchantCenterLinkToUpdate); $merchantCenterLinkOperation->setUpdateMask( FieldMasks::allSetFieldsOf($merchantCenterLinkToUpdate) ); // Issues a mutate request to update the Merchant Center link and prints some // information. $response = $merchantCenterLinkServiceClient->mutateMerchantCenterLink( $customerId, $merchantCenterLinkOperation ); printf( "Approved a Merchant Center Link with resource name '%s' to the Google Ads " . "account '%s'.%s", $response->getResult()->getResourceName(), $customerId, PHP_EOL ); } } ApproveMerchantCenterLink::main();
Python
#!/usr/bin/env python # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Demonstrates how to approve a Merchant Center link request. Prerequisite: You need to have access to a Merchant Center account. You can find instructions to create a Merchant Center account here: https://support.google.com/merchants/answer/188924. To run this code example, you must use the Merchant Center UI or the Content API for Shopping to send a link request between your Merchant Center and Google Ads accounts. """ import argparse import sys from google.ads.googleads.client import GoogleAdsClient from google.ads.googleads.errors import GoogleAdsException from google.api_core import protobuf_helpers def main(client, customer_id, merchant_center_account_id): """Demonstrates how to approve a Merchant Center link request. Args: client: An initialized GoogleAdsClient instance. customer_id: The client customer ID string. merchant_center_account_id: ID of the Merchant center whose link request is to be approved. """ merchant_center_link_service = client.get_service( "MerchantCenterLinkService" ) # Retrieve all the existing Merchant Center links. response = merchant_center_link_service.list_merchant_center_links( customer_id=customer_id ) print( f"{len(response.merchant_center_links)} Merchant Center link(s) " "found with the following details:" ) merchant_center_link_status_enum = client.enums.MerchantCenterLinkStatusEnum # Iterate through the results and filter for links with pending statuses. for merchant_center_link in response.merchant_center_links: print( f"Link '{merchant_center_link.resource_name}' has status " f"'{merchant_center_link.status.name}'." ) if ( merchant_center_link.status == merchant_center_link_status_enum.PENDING and str(merchant_center_link.id) == merchant_center_account_id ): update_merchant_center_link_status( client, customer_id, merchant_center_link_service, merchant_center_link, merchant_center_link_status_enum.ENABLED, ) def update_merchant_center_link_status( client, customer_id, merchant_center_link_service, merchant_center_link, status, ): """Updates the status of a Merchant Center link request. Args: client: An initialized GoogleAdsClient instance. customer_id: The client customer ID string. merchant_center_link_service: A merchant center link service instance. merchant_center_link: The merchant center link to be modified. status: The updated status to apply to the merchant center link. """ # Creates an operation. operation = client.get_type("MerchantCenterLinkOperation") link_to_update = operation.update link_to_update.resource_name = merchant_center_link.resource_name # Enables the pending link. link_to_update.status = status client.copy_from( operation.update_mask, protobuf_helpers.field_mask(None, link_to_update._pb), ) # Updates the link. mutate_response = merchant_center_link_service.mutate_merchant_center_link( customer_id=customer_id, operation=operation ) # Displays the result. print( "The status of Merchant Center Link with resource name " f"'{mutate_response.result.resource_name}' to Google Ads account : " f"{customer_id} was updated to {status.name}." ) if __name__ == "__main__": # GoogleAdsClient will read the google-ads.yaml configuration file in the # home directory if none is specified. googleads_client = GoogleAdsClient.load_from_storage(version="v13") parser = argparse.ArgumentParser( description=("Approves a Merchant Center link request.") ) # The following argument(s) should be provided to run the example. parser.add_argument( "-c", "--customer_id", type=str, required=True, help="The Google Ads customer ID.", ) parser.add_argument( "-m", "--merchant_center_account_id", type=str, required=True, help="ID of the Merchant Center account whose link request is to be " "approved.", ) args = parser.parse_args() try: main( googleads_client, args.customer_id, args.merchant_center_account_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)
Ruby
#!/usr/bin/env ruby # Encoding: utf-8 # # Copyright 2020 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 code example accepts all pending invitations from Google Merchant Center # accounts to your Google Ads account. require 'optparse' require 'google/ads/google_ads' def approve_merchant_center_links(customer_id, merchant_center_account_id) client = Google::Ads::GoogleAds::GoogleAdsClient.new # Retrieve all the existing Merchant Center links. response = client.service.merchant_center_link.list_merchant_center_links( customer_id: customer_id, ) # Iterate the results, and filter for links with pending status. response.merchant_center_links.each do |link| # Enables the pending link. if link.status == :PENDING && link.id.to_s == merchant_center_account_id # Creates the update operation. update_operation = client.operation.update_resource.merchant_center_link( link.resource_name) do |updated_link| updated_link.status = :ENABLED end # Updates the link. mutate_response = client.service.merchant_center_link.mutate_merchant_center_link( customer_id: customer_id, operation: update_operation, ) # Display the result. puts "Enabled a Merchant Center Link with resource name " \ "#{mutate_response.result.resource_name} " \ "to Google Ads account #{customer_id}" end end 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' options[:merchant_center_account_id] = 'INSERT_MERCHANT_CENTER_ACCOUNT_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', '--merchant-center-account-id MERCHANT-CENTER-ACCOUNT-ID', String, 'Merchant Center Account ID') do |v| options[:merchant_center_account_id] = v end opts.separator '' opts.separator 'Help:' opts.on_tail('-h', '--help', 'Show this message') do puts opts exit end end.parse! begin approve_merchant_center_links( options.fetch(:customer_id).tr("-", ""), options.fetch(:merchant_center_account_id), ) 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
Perl
#!/usr/bin/perl -w # # Copyright 2020, 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. # # Demonstrates how to approve a Merchant Center link request. # # Prerequisite: You need to have access to a Merchant Center account. You can find # instructions to create a Merchant Center account here: # https://support.google.com/merchants/answer/188924. # # To run this example, you must use the Merchant Center UI or the Content API for # Shopping to send a link request between your Merchant Center and Google Ads accounts. # See https://support.google.com/merchants/answer/6159060 for details. 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::V13::Resources::MerchantCenterLink; use Google::Ads::GoogleAds::V13::Enums::MerchantCenterLinkStatusEnum qw(ENABLED PENDING); use Google::Ads::GoogleAds::V13::Services::MerchantCenterLinkService::MerchantCenterLinkOperation; 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 $customer_id = "INSERT_CUSTOMER_ID_HERE"; my $merchant_center_account_id = "INSERT_MERCHANT_CENTER_ACCOUNT_ID_HERE"; sub approve_merchant_center_link { my ($api_client, $customer_id, $merchant_center_account_id) = @_; # List all Merchant Center links of the specified customer ID. my $merchant_center_link_service = $api_client->MerchantCenterLinkService(); my $response = $merchant_center_link_service->list({customerId => $customer_id}); printf "%d Merchant Center link(s) found with the following details:\n", scalar @{$response->{merchantCenterLinks}}; foreach my $merchant_center_link (@{$response->{merchantCenterLinks}}) { printf "Link '%s' has status '%s'.\n", $merchant_center_link->{resourceName}, $merchant_center_link->{status}; # Approve a pending link request for a Google Ads account with the specified # customer ID from a Merchant Center account with the specified Merchant # Center account ID. if ( $merchant_center_link->{id} == $merchant_center_account_id && $merchant_center_link->{status} eq PENDING) { # Update the status of Merchant Center link to 'ENABLED' to approve the link. update_merchant_center_link_status( $merchant_center_link_service, $customer_id, $merchant_center_link, ENABLED ); # There is only one MerchantCenterLink object for a given Google Ads account # and Merchant Center account, so we can break early. last; } } return 1; } # Updates the status of a Merchant Center link with a specified Merchant Center # link status. sub update_merchant_center_link_status { my ($merchant_center_link_service, $customer_id, $merchant_center_link, $new_merchant_center_link_status) = @_; # Create an updated MerchantCenterLink object derived from the original, but # with the specified status. my $merchant_center_link_to_update = Google::Ads::GoogleAds::V13::Resources::MerchantCenterLink->new({ resourceName => $merchant_center_link->{resourceName}, status => $new_merchant_center_link_status }); # Construct an operation that will update the Merchant Center link, using the # FieldMasks utility to derive the update mask. This mask tells the Google Ads # API which attributes of the Merchant Center link you want to change. my $merchant_center_link_operation = Google::Ads::GoogleAds::V13::Services::MerchantCenterLinkService::MerchantCenterLinkOperation ->new({ update => $merchant_center_link_to_update, updateMask => all_set_fields_of($merchant_center_link_to_update)}); # Issue a mutate request to update the Merchant Center link and prints some # information. my $response = $merchant_center_link_service->mutate({ customerId => $customer_id, operation => $merchant_center_link_operation }); printf "Approved a Merchant Center Link with resource name '%s' " . "to the Google Ads account '%s'.\n", $response->{result}{resourceName}, $customer_id; } # 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( "customer_id=s" => \$customer_id, "merchant_center_account_id=i" => \$merchant_center_account_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($customer_id, $merchant_center_account_id); # Call the example. approve_merchant_center_link($api_client, $customer_id =~ s/-//gr, $merchant_center_account_id); =pod =head1 NAME approve_merchant_center_link =head1 DESCRIPTION Demonstrates how to approve a Merchant Center link request. Prerequisite: You need to have access to a Merchant Center account. You can find instructions to create a Merchant Center account here: https://support.google.com/merchants/answer/188924. To run this example, you must use the Merchant Center UI or the Content API for Shopping to send a link request between your Merchant Center and Google Ads accounts. See https://support.google.com/merchants/answer/6159060 for details. =head1 SYNOPSIS approve_merchant_center_link.pl [options] -help Show the help message. -customer_id The Google Ads customer ID. -merchant_center_account_id The Merchant Center account ID. =cut