Reject Merchant Center Link

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.v14.errors.GoogleAdsError;
import com.google.ads.googleads.v14.errors.GoogleAdsException;
import com.google.ads.googleads.v14.resources.MerchantCenterLink;
import com.google.ads.googleads.v14.services.ListMerchantCenterLinksRequest;
import com.google.ads.googleads.v14.services.ListMerchantCenterLinksResponse;
import com.google.ads.googleads.v14.services.MerchantCenterLinkOperation;
import com.google.ads.googleads.v14.services.MerchantCenterLinkServiceClient;
import com.google.ads.googleads.v14.services.MutateMerchantCenterLinkResponse;
import com.google.ads.googleads.v14.services.MutateMerchantCenterLinkResult;
import java.io.FileNotFoundException;
import java.io.IOException;

/**
 * Demonstrates how to reject 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.
 *
 * <p>This code example uses version v14 of the Google Ads API. Version v15 of the Google Ads API
 * replaces MerchantCenterLinkService with ProductLinkInvitationService and ProductLinkService. We
 * will add new code examples using these services shortly.
 */
public class RejectMerchantCenterLink {

  private static class RejectMerchantCenterLinkParams 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) {
    RejectMerchantCenterLinkParams params = new RejectMerchantCenterLinkParams();
    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 RejectMerchantCenterLink()
          .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 reject 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) {

    // Rejects a pending link request or unlinks an enabled link for a Google Ads account with
    // customerId from a Merchant Center account with merchantCenterAccountId.
    try (MerchantCenterLinkServiceClient merchantCenterLinkService =
        googleAdsClient.getVersion14().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.
        if (merchantCenterAccountId == merchantCenterLink.getId()) {
          // If the Merchant Center link is pending, reject it by removing the link.
          // If the Merchant Center link is enabled, unlink Merchant Center from Google Ads by
          // removing the link.
          // In both cases, the remove action is the same.
          removeMerchantCenterLink(merchantCenterLinkService, customerId, merchantCenterLink);
          // There is only one MerchantCenterLink object for a given Google Ads account and Merchant
          // Center account, so we can break early.
          break;
        }
      }
    }
  }

  /**
   * Removes a Merchant Center link from a Google Ads client customer account.
   *
   * @param merchantCenterLinkServiceClient the MerchantCenterLinkService client.
   * @param customerId the client customer ID of the Google Ads account that has the link request.
   * @param merchantCenterLink the MerchantCenterLink object to remove.
   * @throws GoogleAdsException if an API request failed with one or more service errors.
   */
  private void removeMerchantCenterLink(
      MerchantCenterLinkServiceClient merchantCenterLinkServiceClient,
      long customerId,
      MerchantCenterLink merchantCenterLink) {
    // Creates a single remove operation, specifying the Merchant Center link resource name.
    MerchantCenterLinkOperation operation =
        MerchantCenterLinkOperation.newBuilder()
            .setRemove(merchantCenterLink.getResourceName())
            .build();

    // Sends the operation in a mutate request.
    MutateMerchantCenterLinkResponse response =
        merchantCenterLinkServiceClient.mutateMerchantCenterLink(
            Long.toString(customerId), operation);
    MutateMerchantCenterLinkResult result = response.getResult();
    System.out.printf(
        "Removed Merchant Center link with resource name: '%s'.%n", result.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.GoogleAds.Lib;
using Google.Ads.GoogleAds.V14.Errors;
using Google.Ads.GoogleAds.V14.Resources;
using Google.Ads.GoogleAds.V14.Services;
using System;

namespace Google.Ads.GoogleAds.Examples.V14
{
    /// <summary>
    /// This code example demonstrates how to reject 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.
    ///
    /// <remarks>This code example uses version v14 of the Google Ads API. Version v15 of the
    /// Google Ads API replaces MerchantCenterLinkService with ProductLinkInvitationService and
    /// ProductLinkService. We will add new code examples using these services shortly.</remarks>
    /// </summary>
    public class RejectMerchantCenterLink : ExampleBase
    {
        /// <summary>
        /// Command line options for running the <see cref="RejectMerchantCenterLink"/> 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>
            /// The Merchant Center account ID for the account requesting to link.
            /// </summary>
            [Option("merchantCenterAccountId", Required = true, HelpText =
                "The Merchant Center account ID for the account requesting to link.")]
            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);

            RejectMerchantCenterLink codeExample = new RejectMerchantCenterLink();
            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 reject a Merchant Center link request.\n" +
            "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.\n" +
            "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.";

        /// <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">The Merchant Center account ID for the account
        ///     requesting to link.</param>
        public void Run(GoogleAdsClient client, long customerId, long merchantCenterAccountId)
        {
            // Get the MerchantCenterLinkService.
            MerchantCenterLinkServiceClient merchantCenterLinkServiceClient =
                client.GetService(Services.V14.MerchantCenterLinkService);

            try
            {
                // Rejects a pending link request or unlinks an enabled link for a Google Ads
                // account with customerId from a Merchant Center account with
                // merchantCenterAccountId.
                ListMerchantCenterLinksResponse response =
                    merchantCenterLinkServiceClient.ListMerchantCenterLinks(customerId.ToString());

                Console.WriteLine($"{response.MerchantCenterLinks.Count} Merchant Center " +
                    $"link(s) found with the following details:");

                foreach (MerchantCenterLink merchantCenterLink in response.MerchantCenterLinks)
                {
                    Console.WriteLine($"Link '{merchantCenterLink.ResourceName}' has status " +
                        $"'{merchantCenterLink.Status}'.");

                    // Checks if there is a link for the Merchant Center account we are looking for.
                    if (merchantCenterAccountId == merchantCenterLink.Id)
                    {
                        // If the Merchant Center link is pending, reject it by removing the link.
                        // If the Merchant Center link is enabled, unlink Merchant Center from
                        // Google Ads by removing the link.
                        // In both cases, the remove action is the same.
                        RemoveMerchantCenterLink(merchantCenterLinkServiceClient, customerId,
                            merchantCenterLink);
                        // There is only one MerchantCenterLink object for a given Google Ads
                        // account and Merchant Center account, so we can break early.
                        break;
                    }
                }
            }
            catch (GoogleAdsException e)
            {
                Console.WriteLine("Failure:");
                Console.WriteLine($"Message: {e.Message}");
                Console.WriteLine($"Failure: {e.Failure}");
                Console.WriteLine($"Request ID: {e.RequestId}");
                throw;
            }
        }

        /// <summary>
        /// Removes a Merchant Center link from a Google Ads client customer account.
        /// </summary>
        /// <param name="merchantCenterLinkServiceClient">The MerchantCenterLinkService
        ///     client.</param>
        /// <param name="customerId">The client customer ID of the Google Ads account that has the
        ///     link request.</param>
        /// <param name="merchantCenterLink">The MerchantCenterLink object to remove.</param>
        private void RemoveMerchantCenterLink(
            MerchantCenterLinkServiceClient merchantCenterLinkServiceClient,
            long customerId, MerchantCenterLink merchantCenterLink)
        {
            // Creates a single remove operation, specifying the Merchant Center link resource name.
            MerchantCenterLinkOperation operation = new MerchantCenterLinkOperation
            {
                Remove = merchantCenterLink.ResourceName
            };

            // Sends the operation in a mutate request.
            MutateMerchantCenterLinkResponse response =
                merchantCenterLinkServiceClient.MutateMerchantCenterLink(
                    customerId.ToString(), operation);
            Console.WriteLine("Removed Merchant Center Link with resource name: " +
                              $"{response.Result.ResourceName}");
        }
    }
}

      

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\V14\GoogleAdsClient;
use Google\Ads\GoogleAds\Lib\V14\GoogleAdsClientBuilder;
use Google\Ads\GoogleAds\Lib\V14\GoogleAdsException;
use Google\Ads\GoogleAds\V14\Enums\MerchantCenterLinkStatusEnum\MerchantCenterLinkStatus;
use Google\Ads\GoogleAds\V14\Errors\GoogleAdsError;
use Google\Ads\GoogleAds\V14\Resources\MerchantCenterLink;
use Google\Ads\GoogleAds\V14\Services\Client\MerchantCenterLinkServiceClient;
use Google\Ads\GoogleAds\V14\Services\ListMerchantCenterLinksRequest;
use Google\Ads\GoogleAds\V14\Services\MerchantCenterLinkOperation;
use Google\Ads\GoogleAds\V14\Services\MutateMerchantCenterLinkRequest;
use Google\ApiCore\ApiException;

/**
 * Demonstrates how to reject 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.
 *
 * <p> This code example uses version v14 of the Google Ads API. Version v15 of the
 * Google Ads API replaces MerchantCenterLinkService with ProductLinkInvitationService and
 * ProductLinkService. We will add new code examples using these services shortly.
 */
class RejectMerchantCenterLink
{
    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)
            // We set this value to true to show how to use GAPIC v2 source code. You can remove the
            // below line if you wish to use the old-style source code. Note that in that case, you
            // probably need to modify some parts of the code below to make it work.
            // For more information, see
            // https://developers.devsite.corp.google.com/google-ads/api/docs/client-libs/php/gapic.
            ->usingGapicV2Source(true)
            ->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 of the Google Ads account to reject the link request
     * @param int $merchantCenterAccountId the Merchant Center account ID for the account requesting
     *     to link
     */
    public static function runExample(
        GoogleAdsClient $googleAdsClient,
        int $customerId,
        int $merchantCenterAccountId
    ) {
        $merchantCenterLinkService = $googleAdsClient->getMerchantCenterLinkServiceClient();

        // Rejects a pending link request or unlinks an enabled link for a Google Ads account with
        // $customerId from a Merchant Center account with $merchantCenterAccountId.
        $response = $merchantCenterLinkService->listMerchantCenterLinks(
            ListMerchantCenterLinksRequest::build($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
            );

            // Checks if there is a link for the Merchant Center account we are looking for.
            if ($merchantCenterAccountId === $merchantCenterLink->getId()) {
                // If the Merchant Center link is pending, reject it by removing the link.
                // If the Merchant Center link is enabled, unlink Merchant Center from Google Ads by
                // removing the link.
                // In both cases, the remove action is the same.
                self::removeMerchantCenterLink(
                    $merchantCenterLinkService,
                    $customerId,
                    $merchantCenterLink
                );
                // There is only one MerchantCenterLink object for a given Google Ads account and
                // Merchant Center account, so we can break early.
                break;
            }
        }
    }

    /**
     * Removes a Merchant Center link from a Google Ads client customer account.
     *
     * @param MerchantCenterLinkServiceClient $merchantCenterLinkServiceClient the
     *     MerchantCenterLinkService client
     * @param int $customerId the customer ID of the Google Ads account that has the link request
     * @param MerchantCenterLink $merchantCenterLink the MerchantCenterLink object to remove
     */
    private static function removeMerchantCenterLink(
        MerchantCenterLinkServiceClient $merchantCenterLinkServiceClient,
        int $customerId,
        MerchantCenterLink $merchantCenterLink
    ) {
        // Creates a single remove operation, specifying the Merchant Center link resource name.
        $merchantCenterLinkOperation = new MerchantCenterLinkOperation();
        $merchantCenterLinkOperation->setRemove($merchantCenterLink->getResourceName());

        // Issues a mutate request to remove the link and prints the result info.
        $response = $merchantCenterLinkServiceClient->mutateMerchantCenterLink(
            MutateMerchantCenterLinkRequest::build(
                $customerId,
                $merchantCenterLinkOperation
            )
        );
        $mutateMerchantCenterLinkResult = $response->getResult();
        printf(
            "Removed Merchant Center link with resource name: '%s'.%s",
            $mutateMerchantCenterLinkResult->getResourceName(),
            PHP_EOL
        );
    }
}

RejectMerchantCenterLink::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 reject or unlink 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. You can find detailed instructions to link your Merchant Center and
Google Ads accounts here: https://support.google.com/merchants/answer/6159060.

NOTE: This code example uses version v14 of the Google Ads API. Version v15 of
the Google Ads API replaces MerchantCenterLinkService with
ProductLinkInvitationService and ProductLinkService. We will add new code
examples using these services shortly.
"""

import argparse
import sys

from google.ads.googleads.client import GoogleAdsClient
from google.ads.googleads.errors import GoogleAdsException


def main(client, customer_id, merchant_center_account_id):
    """Demonstrates how to reject a Merchant Center link request.

    Args:
        client: An initialized Google Ads client.
        customer_id: The Google Ads customer ID.
        merchant_center_account_id: The Merchant Center account ID for the
            account requesting to link.
    """
    # Get the MerchantCenterLinkService client.
    merchant_center_link_service = client.get_service(
        "MerchantCenterLinkService"
    )
    # Get the extant customer account to Merchant Center account links.
    list_merchant_center_links_response = (
        merchant_center_link_service.list_merchant_center_links(
            customer_id=customer_id
        )
    )

    number_of_links = len(
        list_merchant_center_links_response.merchant_center_links
    )

    if number_of_links == 0:
        print(
            "There are no current merchant center links to Google Ads "
            f"account {customer_id}. This example will now exit."
        )
        return

    print(
        f"{number_of_links} Merchant Center link(s) found with the "
        "following details:"
    )

    for (
        merchant_center_link
    ) in list_merchant_center_links_response.merchant_center_links:
        print(
            f"\tLink '{merchant_center_link.resource_name}' has status "
            f"'{merchant_center_link.status.name}'."
        )

        # Check if this is the link to the target Merchant Center account.
        if merchant_center_link.id == merchant_center_account_id:
            # A Merchant Center link can be pending or enabled; in both
            # cases, we reject it by removing the link.
            remove_merchant_center_link(
                client,
                merchant_center_link_service,
                customer_id,
                merchant_center_link,
            )

            # We can terminate early since this example concerns only one
            # Google Ads account to Merchant Center account link.
            return

    # Raise an exception if no matching Merchant Center link was found.
    raise ValueError(
        "No link could was found between Google Ads account "
        f"{customer_id} and Merchant Center account "
        f"{merchant_center_account_id}."
    )


def remove_merchant_center_link(
    client, merchant_center_link_service, customer_id, merchant_center_link
):
    """Removes a Merchant Center link from a Google Ads client customer account.

    Args:
        client: An initialized Google Ads client.
        merchant_center_link_service: An initialized
            MerchantCenterLinkService client.
        customer_id: The Google Ads customer ID of the account that has the link
            request.
        merchant_center_link: The MerchantCenterLink object to remove.
    """
    # Create a single remove operation, specifying the Merchant Center link
    # resource name.
    operation = client.get_type("MerchantCenterLinkOperation")
    operation.remove = merchant_center_link.resource_name

    # Send the operation in a mutate request.
    response = merchant_center_link_service.mutate_merchant_center_link(
        customer_id=customer_id, operation=operation
    )
    print(
        "Removed Merchant Center link with resource name "
        f"'{response.result.resource_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="v14")

    parser = argparse.ArgumentParser(
        description=(
            "Demonstrates how to reject 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=int,
        required=True,
        help="The Merchant Center account ID for the account requesting to "
        "link.",
    )
    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.
#
# Demonstrates how to reject 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.

# NOTE: This code example uses version v14 of the Google Ads API.
# Version v15 of the Google Ads API replaces MerchantCenterLinkService with
# ProductLinkInvitationService and ProductLinkService. We will add new code
# examples using these services shortly.

require 'optparse'
require 'google/ads/google_ads'

def reject_merchant_center_links(customer_id, merchant_center_account_id)
  client = Google::Ads::GoogleAds::GoogleAdsClient.new

  merchant_center_link_service = client.service.v14.merchant_center_link

  # Rejects a pending link request or unlinks an enabled link for a Google Ads
  # account with customer_id from a Merchant Center account with
  # merchant_center_account_id.
  response = merchant_center_link_service.list_merchant_center_links(
    customer_id: customer_id,
  )

  # Checks if there is a link for the Merchant Center account we are
  # looking for.
  # If the Merchant Center link is pending, reject it by removing the link.
  # If the Merchant Center link is enabled, unlink Merchant Center from
  # Google Ads by removing the link.
  # In both cases, the remove action is the same.
  # There is only one MerchantCenterLink object for a given Google Ads
  # account and Merchant Center account, so we can just detect the first one.
  link_to_remove = response.merchant_center_links.detect {|link| link.id == merchant_center_account_id.to_i}

  if !link_to_remove.nil?
    puts "Found the link to remove:"
    puts "\t Link resource name '#{link_to_remove.resource_name}', " \
      "link status: #{link_to_remove.status}"

    remove_merchant_center_link(
      client,
      merchant_center_link_service,
      customer_id,
      link_to_remove,
    )
  else
    puts "Link between Google Ads account #{customer_id} " \
      "and Merchant Center account #{merchant_center_account_id} not found."
  end
end

# Removes a Merchant Center link from a Google Ads client customer account.
def remove_merchant_center_link(
  client,
  merchant_center_link_service,
  customer_id,
  link)
  # Creates a single remove operation, specifying the Merchant Center link
  # resource name.
  operation = client.operation.v14.remove_resource.merchant_center_link(link.resource_name)

  # Issues a mutate request to remove the link and prints the result info.
  response = merchant_center_link_service.mutate_merchant_center_link(
    customer_id: customer_id,
    operation: operation,
  )
  puts "Removed Merchant Center link with resource name: " \
    "#{response.result.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[: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 Accounnt 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
    reject_merchant_center_links(
      options.fetch(:customer_id).tr("-", ""),
      options[: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 reject 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.
#
# Note: This code example uses v14 of the Google Ads API. v15 of the Google Ads API
# replaces MerchantCenterLinkService with ProductLinkInvitationService and
# ProductLinkService.

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::V14::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 reject_merchant_center_link {
  my ($api_client, $customer_id, $merchant_center_account_id) = @_;

  my $merchant_center_link_service = $api_client->MerchantCenterLinkService();

  # Reject a pending link request or unlink an enabled link for a Google Ads
  # account with $customer_id from a Merchant Center account with $merchant_center_account_id.
  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};

    # Check if there is a link for the Merchant Center account we are looking for.
    if ($merchant_center_account_id == $merchant_center_link->{id}) {
      # If the Merchant Center link is pending, reject it by removing the link.
      # If the Merchant Center link is enabled, unlink Merchant Center from Google
      # Ads by removing the link.
      # In both cases, the remove action is the same.
      remove_merchant_center_link($merchant_center_link_service, $customer_id,
        $merchant_center_link);
      # There is only one MerchantCenterLink object for a given Google Ads account
      # and Merchant Center account, so we can break early.
      last;
    }
  }
  return 1;
}

# Removes a Merchant Center link from a Google Ads client customer account.
sub remove_merchant_center_link {
  my ($merchant_center_link_service, $customer_id, $merchant_center_link) = @_;

  # Create a single remove operation, specifying the Merchant Center link resource name.
  my $merchant_center_link_operation =
    Google::Ads::GoogleAds::V14::Services::MerchantCenterLinkService::MerchantCenterLinkOperation
    ->new({
      remove => $merchant_center_link->{resourceName}});

  # Issue a mutate request to remove the link and print the result info.
  my $response = $merchant_center_link_service->mutate({
    customerId => $customer_id,
    operation  => $merchant_center_link_operation
  });
  printf
    "Removed Merchant Center link with resource name: '%s'.\n",
    $response->{result}{resourceName};
}

# 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.
reject_merchant_center_link($api_client, $customer_id =~ s/-//gr,
  $merchant_center_account_id);

=pod

=head1 NAME

reject_merchant_center_link

=head1 DESCRIPTION

Demonstrates how to reject 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.

=head1 SYNOPSIS

reject_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