ส่วนขยายสถานที่ตั้ง Google Ads

หากต้องการสร้างส่วนขยายสถานที่ตั้งของ Google Ads คุณต้องสร้าง Business Profile และกรอกที่อยู่ของที่ตั้งธุรกิจทั้งหมด จากนั้นเชื่อมโยง Business Profile กับฟีดส่วนขยายสถานที่ตั้งเพื่อสร้างส่วนขยายสถานที่ตั้ง

Business Profile

Business Profile เป็นที่เก็บส่วนกลางสําหรับที่ตั้งธุรกิจของคุณในผลิตภัณฑ์ทั้งหมดของ Google คุณไม่ต้องกังวลว่า สถานที่ตั้งของ Business Profile และส่วนขยายสถานที่ตั้งของ Google Ads จะซิงค์กัน เพียงตั้งค่าออบเจ็กต์ฟีดที่จําเป็นเพียงครั้งเดียว Google Ads จะซิงค์ส่วนขยายสถานที่ตั้งกับข้อมูลล่าสุดจาก Business Profile โดยอัตโนมัติโดยอัตโนมัติ

การสร้างสถานที่ตั้งใน Business Profile ทําได้ 2 วิธี

  1. คุณใช้ UI ของ Business Profile เพื่อสร้างสถานที่ได้ หากทําตามแนวทางนี้ คุณสามารถข้ามไปที่การลิงก์สถานที่ตั้งกับโฆษณาโดยใช้ Google Ads API ได้ทันที
  2. คุณใช้ Business Profile API เพื่อสร้างที่ตั้งธุรกิจแบบเป็นโปรแกรมได้

การทํางานกับ Business Profile API

หากต้องการเริ่มต้นใช้งาน Business Profile API โปรดไปที่หน้าแรก เราขอแนะนําให้ใช้บัญชีธุรกิจแทนที่จะใช้บัญชีส่วนตัวสําหรับสถานที่ตั้งที่ลิงก์กับ Google Ads การใช้บัญชีธุรกิจช่วยให้คุณแชร์ สิทธิ์การเข้าถึงกับผู้ใช้รายอื่นได้โดยไม่ต้องแชร์รายละเอียดบัญชีส่วนตัว

วิธีสร้างที่ตั้งธุรกิจแบบเป็นโปรแกรมโดยใช้ Business Profile API

  1. เริ่มต้นโดยการดาวน์โหลดไลบรารีของไคลเอ็นต์ ทําตามคู่มือการตั้งค่าพื้นฐาน เพื่อสร้างข้อมูลเข้าสู่ระบบ OAuth ให้ทํางานร่วมกับ Business Profile API ได้

  2. ใช้ Business Profile API เพื่อระบุบัญชีทั้งหมดที่คุณเป็นเจ้าของหรือมีสิทธิ์ในการจัดการ เลือกบัญชีที่จะใช้

  3. ใช้ Business Profile API เพื่อสร้างสถานที่

สร้างฟีดส่วนขยายสถานที่ตั้งใหม่ที่ลิงก์กับ Business Profile

หากต้องการสร้างฟีดส่วนขยายสถานที่ตั้งใหม่ ให้เริ่มต้นด้วยการสร้างออบเจ็กต์ Feed ดําเนินการ FeedService.MutateFeeds create เพื่อสร้างฟีด ข้อมูลโค้ดจะแสดงอยู่ด้านล่าง

Java

// Creates a feed that will sync to the Business Profile account. Do not add FeedAttributes to
// this object as Google Ads will add them automatically because this will be a system generated
// feed.
Feed.Builder businessProfileFeed =
    Feed.newBuilder()
        .setName("Business Profile feed #" + getPrintableDateTime())
        // Configures the location feed populated from Business Profile Locations.
        .setPlacesLocationFeedData(placesLocationFeedData)
        // Since this feed's feed items will be managed by Google,
        // you must set its origin to GOOGLE.
        .setOrigin(FeedOrigin.GOOGLE);

FeedOperation operation = FeedOperation.newBuilder().setCreate(businessProfileFeed).build();
      

C#

private static string CreateBusinessProfileFeed(GoogleAdsClient client, long customerId,
    string businessProfileEmailAddress, string businessAccountId,
    string businessProfileAccessToken)
{
    // Optional: Delete all existing location extension feeds. This is an optional step,
    // and is required for this code example to run correctly more than once.
    // 1. Google Ads only allows one location extension feed per email address.
    // 2. A Google Ads account cannot have a location extension feed and an affiliate
    // location extension feed at the same time.
    DeleteLocationExtensionFeeds(client, customerId);

    // Get the FeedServiceClient.
    FeedServiceClient feedService = client.GetService(Services.V13.FeedService);

    // Creates a feed that will sync to the Business Profile account specified by
    // businessProfileEmailAddress. Do not add FeedAttributes to this object as Google Ads
    // will add them automatically because this will be a system generated feed.
    Feed businessProfileFeed = new Feed()
    {
        Name = "Business Profile feed #" + ExampleUtilities.GetRandomString(),

        PlacesLocationFeedData = new PlacesLocationFeedData()
        {
            EmailAddress = businessProfileEmailAddress,
            // If the EmailAddress is for a Business Profile manager instead of the
            // Business Profile account owner, then set BusinessAccountId to the Google+
            // Page ID of a location for which the manager has access. This information is
            // available through the Business Profile API. See
            // https://developers.google.com/my-business/reference/rest/v4/accounts.locations#locationkey
            // for details.
            BusinessAccountId = string.IsNullOrEmpty(businessAccountId) ?
                null : businessAccountId,
            // Used to filter Business Profile listings by labels. If entries exist in
            // label_filters, only listings that have at least one of the labels set are
            // candidates to be synchronized into FeedItems. If no entries exist in
            // label_filters, then all listings are candidates for syncing.
            LabelFilters = { "Stores in New York" },
            // Sets the authentication info to be able to connect Google Ads to the
            // Business Profile account.
            OauthInfo = new OAuthInfo()
            {
                HttpMethod = "GET",
                HttpRequestUrl = GOOGLE_ADS_SCOPE,
                HttpAuthorizationHeader = $"Bearer {businessProfileAccessToken}"
            },
        },
        // Since this feed's feed items will be managed by Google,
        // you must set its origin to GOOGLE.
        Origin = FeedOrigin.Google
    };

    FeedOperation operation = new FeedOperation()
    {
        Create = businessProfileFeed
    };

    // Adds the feed.
    MutateFeedsResponse response =
        feedService.MutateFeeds(customerId.ToString(), new[] { operation });

    // Displays the results.
    string businessProfileFeedResourceName = response.Results[0].ResourceName;
    Console.WriteLine($"Business Profile feed created with resource name: " +
        $"{businessProfileFeedResourceName}.");
    return businessProfileFeedResourceName;
}
      

PHP

private static function createFeed(
    GoogleAdsClient $googleAdsClient,
    int $customerId,
    string $businessProfileEmail,
    string $businessProfileAccessToken,
    string $businessAccountIdentifier
) {

    $businessProfileFeed = new Feed([
        'name' => 'Business Profile feed #' . Helper::getPrintableDatetime(),
        'origin' => FeedOrigin::GOOGLE,
        'places_location_feed_data' => new PlacesLocationFeedData([
            'email_address' => $businessProfileEmail,
            'business_account_id' => $businessAccountIdentifier,
            // Used to filter Business Profile listings by labels. If entries exist in
            // label_filters, only listings that have at least one of the labels set are
            // candidates to be synchronized into FeedItems. If no entries exist in
            // label_filters, then all listings are candidates for syncing.
            'label_filters' => ['Stores in New York'],
            // Sets the authentication info to be able to connect Google Ads to the Business
            // Profile account.
            'oauth_info' => new OAuthInfo([
                'http_method' => 'GET',
                'http_request_url' => self::GOOGLE_ADS_SCOPE,
                'http_authorization_header' => 'Bearer ' . $businessProfileAccessToken
            ])

        ])
    ]);
    // Creates a feed operation.
    $feedOperation = new FeedOperation();
    $feedOperation->setCreate($businessProfileFeed);

    // Issues a mutate request to add the feed and print its information.
    // Since it is a system generated feed, Google Ads will automatically:
    // 1. Set up the feed attributes on the feed.
    // 2. Set up a feed mapping that associates the feed attributes of the feed with the
    //    placeholder fields of the LOCATION placeholder type.
    $feedServiceClient = $googleAdsClient->getFeedServiceClient();
    $response = $feedServiceClient->mutateFeeds(
        $customerId,
        [$feedOperation]
    );
    $businessProfileFeedResourceName = $response->getResults()[0]->getResourceName();
    printf(
        "Business Profile feed created with resource name: '%s'.%s",
        $businessProfileFeedResourceName,
        PHP_EOL
    );

    return $businessProfileFeedResourceName;
}
      

Python

feed_operation = client.get_type("FeedOperation")
business_profile_feed = feed_operation.create
business_profile_feed.name = f"Business Profile Feed #{uuid4()}"
# Configure the location feed populated from Business Profile Locations.
business_profile_feed.places_location_feed_data.email_address = (
    business_profile_email
)

if business_account_id is not None:
    business_profile_feed.places_location_feed_data.business_account_id = (
        business_account_id
    )

# Used to filter Business Profile listings by labels. If entries exist in
# label_filters, only listings that have at least one of the labels set are
# candidates to be synchronized into FeedItems. If no entries exist in
# label_filters, then all listings are candidates for syncing.
business_profile_feed.places_location_feed_data.label_filters.append(
    "Stores in New York"
)

# Set the authentication info to be able to connect Google Ads to the
# Business Profile account.
business_profile_feed.places_location_feed_data.oauth_info.http_method = (
    "GET"
)
business_profile_feed.places_location_feed_data.oauth_info.http_request_url = (
    DEFAULT_OAUTH2_SCOPE
)
business_profile_feed.places_location_feed_data.oauth_info.http_authorization_header = (
    f"Bearer {business_profile_access_token}"
)
# Since this feed's feed items will be managed by Google, you must set its
# origin to GOOGLE.
business_profile_feed.origin = client.enums.FeedOriginEnum.GOOGLE

# Optional: Delete all existing location extension feeds. This is an
# optional step, and is required for this code example to run correctly
# more than once; Google Ads only allows one location extension feed
# per email address, and a Google Ads account cannot have a location
# extension feed and an affiliate location extension feed at the same
# time.
delete_location_extension_feeds(client, customer_id)

# Add the feed. Since it is a system generated feed, Google Ads will
# automatically:
# 1. Set up the FeedAttributes on the feed.
# 2. Set up a FeedMapping that associates the FeedAttributes of the feed
#   with the placeholder fields of the LOCATION placeholder type.
feed_response = feed_service.mutate_feeds(
    customer_id=customer_id, operations=[feed_operation]
)
feed_resource_name = feed_response.results[0].resource_name
print(
    "Business Profile feed created with resource name "
    f"'{feed_resource_name}'."
)
      

Ruby

def create_feed(
  client,
  customer_id,
  business_profile_email_address,
  business_profile_access_token,
  business_account_identifier)
  # Creates a feed operation.
  operation = client.operation.create_resource.feed do |feed|
    feed.name = "Business Profile feed #{(Time.new.to_f * 1000).to_i}"
    feed.origin = :GOOGLE
    feed.places_location_feed_data = client.resource.places_location_feed_data do |data|
      data.email_address = business_profile_email_address
      data.business_account_id = business_account_identifier
      data.label_filters << "Stores in New York"
      data.oauth_info = client.resource.o_auth_info do |oauth|
        oauth.http_method = "GET"
        oauth.http_request_url = "https://www.googleapis.com/auth/adwords"
        oauth.http_authorization_header = "Bearer #{business_profile_access_token}"
      end
    end
  end

  # Issues a mutate request to add the feed and print its information.
  # Since it is a system generated feed, Google Ads will automatically:
  # 1. Set up the feed attributes on the feed.
  # 2. Set up a feed mapping that associates the feed attributes of the feed with the
  #    placeholder fields of the LOCATION placeholder type.
  response = client.service.feed.mutate_feeds(
    customer_id: customer_id,
    operations: [operation],
  )

  # Prints out the Business Profile feed resource name.
  business_profile_feed_resource_name = response.results.first.resource_name
  puts "Business Profile feed created with resource name: #{business_profile_feed_resource_name}"

  business_profile_feed_resource_name
end
      

Perl

# Create a feed that will sync to the Business Profile account specified by
# $business_profile_email. Do not add FeedAttributes to this object as Google Ads
# will add them automatically because this will be a system generated feed.
my $business_profile_feed = Google::Ads::GoogleAds::V13::Resources::Feed->new(
  {
    name => "Business Profile feed #" . uniqid(),
    # Configure the location feed populated from Business Profile Locations.
    placesLocationFeedData =>
      Google::Ads::GoogleAds::V13::Resources::PlacesLocationFeedData->new({
        emailAddress      => $business_profile_email,
        businessAccountId => $business_profile_account_id,
        # Used to filter Business Profile listings by labels. If entries exist in
        # label_filters, only listings that have at least one of the labels set are
        # candidates to be synchronized into FeedItems. If no entries exist in
        # label_filters, then all listings are candidates for syncing.
        labelFilters => ["Stores in New York"],
        # Set the authentication info to be able to connect Google Ads to the
        # Business Profile account.
        oauthInfo => Google::Ads::GoogleAds::V13::Resources::OAuthInfo->new({
            httpMethod     => "GET",
            httpRequestUrl =>
              Google::Ads::GoogleAds::Constants::DEFAULT_OAUTH2_SCOPE,
            httpAuthorizationHeader => "Bearer " .
              $business_profile_access_token
          })}
      ),
    # Since this feed's feed items will be managed by Google, you must set its
    # origin to GOOGLE.
    origin => GOOGLE
  });
      

คุณต้องป้อนข้อมูลในช่องต่อไปนี้สําหรับฟีดส่วนขยายสถานที่ตั้งโดยเฉพาะ

แอตทริบิวต์ จำเป็น คำอธิบาย
origin ได้ เนื่องจากฟีดส่วนขยายสถานที่ตั้งสร้างขึ้นโดยระบบ คุณจึงต้องตั้งค่าช่อง origin เป็น GOOGLE
attributes ไม่ได้ อย่าระบุ attributes สําหรับฟีด Google Ads จะสร้างฟีดเหล่านี้ให้คุณโดยอัตโนมัติเพราะเป็นฟีดที่ระบบสร้าง
places_location_feed_data ได้ การตั้งค่าแอตทริบิวต์ places_location_feed_data กับออบเจ็กต์ PlacesLocationFeedData ในฟีดจะบอก Google Ads ให้ทําสิ่งต่อไปนี้
  • ลิงก์ Business Profile กับบัญชี Google Ads
  • สร้างแอตทริบิวต์ฟีดสําหรับฟีดโดยอัตโนมัติ
  • สร้างประเภทเกณฑ์ FeedMapping โดยอัตโนมัติ LOCATION_EXTENSION_TARGETING ประเภทเกณฑ์
  • (ไม่บังคับ) จํากัดชุดสถานที่ที่ Google Ads ซิงค์จาก Business Profile

แอตทริบิวต์ของ PlacesLocationFeedData

แอตทริบิวต์ จำเป็น คำอธิบาย
email_address ได้ อีเมลของเจ้าของหรือผู้จัดการธุรกิจใน Business Profile ต้องตรงกับอีเมลที่ระบุไว้ใน oauth_info
oauth_info ได้ ข้อมูล OAuth2 ที่ให้สิทธิ์ Google Ads ในการเข้าถึง Business Profile หากคุณไม่คุ้นเคยกับ OAuth2 โปรดอ่านคู่มือการตรวจสอบสิทธิ์ก่อน
business_account_id ไม่ได้ รหัสบัญชีของธุรกิจที่มีการจัดการซึ่งจะใช้สถานที่ตั้ง หากใช้ Business Profile API คุณจะรับรหัสนี้ได้จากส่วน account_id ของ name ของ Account ไม่เช่นนั้น คุณอาจคัดลอกส่วน LOCATION_GROUP_ID จากส่วนข้อมูลกลุ่มสถานที่ตั้งของกลุ่มสถานที่ตั้งที่ระบุได้
business_name_filter ไม่ได้ ชื่อธุรกิจที่จะซิงค์กับ Google Ads
category_filters ไม่ได้ หมวดหมู่ของข้อมูลที่จะซิงค์กับ Google Ads
label_filters ไม่ได้ ป้ายกํากับของข้อมูลที่ต้องการซิงค์กับ Google Ads

แอตทริบิวต์ oauth_info ของ PlacesLocationFeedData

แอตทริบิวต์ ค่า คำอธิบาย
http_method GET วิธี HTTP ในการรับข้อมูลการให้สิทธิ์
http_request_url https://www.googleapis.com/auth/adwords ขอบเขต OAuth ที่ Google Ads API ใช้เพื่อให้สิทธิ์คําขอของคุณกับ Business Profile
http_authorization_header Bearer OAUTH_ACCESS_TOKEN ส่วนหัวการให้สิทธิ์ที่มีโทเค็นเพื่อการเข้าถึง OAuth ที่ให้สิทธิ์บัญชี Google Ads เพื่ออ่านจากบัญชี Business Profile แทนที่ OAUTH_ACCESS_TOKEN ใช้แทนโทเค็นเพื่อการเข้าถึงที่สร้างขึ้นด้วยข้อมูลเข้าสู่ระบบ OAuth สําหรับ http_request_url ของ PlacesLocationFeedData และขอบเขตที่ตรงกับ http_request_url

รอให้ฟีดพร้อมใช้งาน

เมื่อสร้าง Feed แล้ว Google Ads จะสร้างแอตทริบิวต์ฟีดและ FeedMapping หลังจากนั้น ระบบจะสร้างเนื้อหาฟีดโดยสร้างออบเจ็กต์ FeedItem ที่สอดคล้องกับสถานที่ตั้งใน Business Profile

คุณต้องรอจนกว่าจะสร้าง FeedMapping ขึ้นเพื่อให้แน่ใจว่าฟีดมีการตั้งค่าอย่างถูกต้อง และสามารถนําไปใช้ในขั้นตอนถัดไปได้ ซึ่งทําได้โดยพยายามเรียกข้อมูล FeedMapping สําหรับฟีดที่เกี่ยวข้องด้วย placeholder_type เท่ากับ LOCATION

Java

try (FeedServiceClient feedServiceClient =
    googleAdsClient.getLatestVersion().createFeedServiceClient()) {
  // Adds the feed. Since it is a system generated feed, Google Ads will automatically:
  // 1. Set up the FeedAttributes on the feed.
  // 2. Set up a FeedMapping that associates the FeedAttributes of the feed
  // with the placeholder fields of the LOCATION placeholder type.
  MutateFeedsResponse response =
      feedServiceClient.mutateFeeds(Long.toString(customerId), ImmutableList.of(operation));
  String businessProfileFeedResourceName = response.getResults(0).getResourceName();
  System.out.printf(
      "Business Profile feed created with resource name: %s%n",
      businessProfileFeedResourceName);
      

C#

private static FeedMapping GetBusinessProfileFeedMapping(GoogleAdsClient client,
    long customerId, string businessProfileFeedResourceName)
{
    // Get the GoogleAdsService.
    GoogleAdsServiceClient googleAdsService = client.GetService(
        Services.V13.GoogleAdsService);

    // Create the query.
    string query = $"SELECT feed_mapping.resource_name, feed_mapping.status FROM " +
        $"feed_mapping WHERE feed_mapping.feed = '{businessProfileFeedResourceName}' and " +
        $"feed_mapping.status = ENABLED and feed_mapping.placeholder_type = LOCATION" +
        $" LIMIT 1";

    // Issue a search request.
    PagedEnumerable<SearchGoogleAdsResponse, GoogleAdsRow> result =
        googleAdsService.Search(customerId.ToString(), query);

    // Display the results.
    GoogleAdsRow googleAdsRow = result.FirstOrDefault();
    return (googleAdsRow == null) ? null : googleAdsRow.FeedMapping;
}
      

PHP

// Issues a mutate request to add the feed and print its information.
// Since it is a system generated feed, Google Ads will automatically:
// 1. Set up the feed attributes on the feed.
// 2. Set up a feed mapping that associates the feed attributes of the feed with the
//    placeholder fields of the LOCATION placeholder type.
$feedServiceClient = $googleAdsClient->getFeedServiceClient();
$response = $feedServiceClient->mutateFeeds(
    $customerId,
    [$feedOperation]
);
$businessProfileFeedResourceName = $response->getResults()[0]->getResourceName();
printf(
    "Business Profile feed created with resource name: '%s'.%s",
    $businessProfileFeedResourceName,
    PHP_EOL
);

return $businessProfileFeedResourceName;
      

Python

# Add the feed. Since it is a system generated feed, Google Ads will
# automatically:
# 1. Set up the FeedAttributes on the feed.
# 2. Set up a FeedMapping that associates the FeedAttributes of the feed
#   with the placeholder fields of the LOCATION placeholder type.
feed_response = feed_service.mutate_feeds(
    customer_id=customer_id, operations=[feed_operation]
)
feed_resource_name = feed_response.results[0].resource_name
print(
    "Business Profile feed created with resource name "
    f"'{feed_resource_name}'."
)
      

Ruby

# Issues a mutate request to add the feed and print its information.
# Since it is a system generated feed, Google Ads will automatically:
# 1. Set up the feed attributes on the feed.
# 2. Set up a feed mapping that associates the feed attributes of the feed with the
#    placeholder fields of the LOCATION placeholder type.
response = client.service.feed.mutate_feeds(
  customer_id: customer_id,
  operations: [operation],
)

# Prints out the Business Profile feed resource name.
business_profile_feed_resource_name = response.results.first.resource_name
puts "Business Profile feed created with resource name: #{business_profile_feed_resource_name}"

business_profile_feed_resource_name
      

Perl

# Add the feed. Since it is a system generated feed, Google Ads will automatically:
# 1. Set up the FeedAttributes on the feed.
# 2. Set up a FeedMapping that associates the FeedAttributes of the feed with the
#    placeholder fields of the LOCATION placeholder type.
my $feeds_response = $api_client->FeedService()->mutate({
    customerId => $customer_id,
    operations => [$feed_operation]});

my $feed_resource_name = $feeds_response->{results}[0]{resourceName};

printf "Business Profile feed created with resource name: '%s'.\n",
  $feed_resource_name;
      

หาก FeedMapping ยังไม่พร้อมใช้งาน ให้ลองโทรอีกครั้งพร้อมนโยบายการขอเลขชี้ขาดจนกว่า Feed จะพร้อม

Java

try (CustomerFeedServiceClient customerFeedServiceClient =
    googleAdsClient.getLatestVersion().createCustomerFeedServiceClient()) {

  // After the completion of the Feed ADD operation above the added feed will not be available
  // for usage in a CustomerFeed until the sync between the Google Ads and Business Profile
  // accounts
  // completes. The loop below will retry adding the CustomerFeed up to ten times with an
  // exponential back-off policy.
  String addedCustomerFeed = null;
  int numberOfAttempts = 0;
  do {
    numberOfAttempts++;
    try {
      MutateCustomerFeedsResponse customerFeedsResponse =
          customerFeedServiceClient.mutateCustomerFeeds(
              Long.toString(customerId), ImmutableList.of(customerFeedOperation));
      addedCustomerFeed = customerFeedsResponse.getResults(0).getResourceName();
      System.out.printf("Customer feed created with resource name: %s%n", addedCustomerFeed);
    } catch (GoogleAdsException gae) {
      // Waits using exponential backoff policy.
      long sleepSeconds = (long) Math.scalb(5, numberOfAttempts);

      // Exits the loop early if sleepSeconds grows too large in the event that
      // MAX_CUSTOMER_FEED_ADD_ATTEMPTS is set too high.
      if (sleepSeconds > (long) Math.scalb(5, 10)) {
        break;
      }

      System.out.printf(
          "Attempt #%d to add the CustomerFeed was not successful. "
              + "Waiting %d seconds before trying again.%n",
          numberOfAttempts, sleepSeconds);
      Thread.sleep(sleepSeconds * 1000);
    }
  } while (numberOfAttempts < MAX_CUSTOMER_FEED_ADD_ATTEMPTS && addedCustomerFeed == null);
      

C#

private static void WaitForBusinessProfileFeedToBeReady(GoogleAdsClient client,
    long customerId, string businessProfileFeedResourceName)
{
    int numAttempts = 0;
    while (numAttempts < MAX_FEEDMAPPING_RETRIEVAL_ATTEMPTS)
    {
        // Once you create a feed, Google's servers will setup the feed by creating feed
        // attributes and feedmapping. Once the feedmapping is created, it is ready to be
        // used for creating customer feed.
        // This process is asynchronous, so we wait until the feed mapping is created,
        // peforming exponential backoff.
        FeedMapping feedMapping = GetBusinessProfileFeedMapping(client,
            customerId, businessProfileFeedResourceName);

        if (feedMapping == null)
        {
            numAttempts++;
            int sleepSeconds = (int)(5 * Math.Pow(2, numAttempts));
            Console.WriteLine($"Checked: #{numAttempts} time(s). Business Profile feed " +
                $"is not ready yet. Waiting {sleepSeconds} seconds before trying again.");
            Thread.Sleep(sleepSeconds * 1000);
        }
        else
        {
            Console.WriteLine($"Business Profile Feed {businessProfileFeedResourceName} " +
                $"is now ready.");
            return;
        }
    }
    throw new RpcException(new Status(StatusCode.DeadlineExceeded,
        $"Business Profile Feed is not ready after {MAX_FEEDMAPPING_RETRIEVAL_ATTEMPTS} " +
        $"retries."));
}
      

PHP

// After the completion of the feed ADD operation above the added feed will not be available
// for usage in a customer feed until the sync between the Google Ads and Business Profile
// accounts completes. The loop below will retry adding the customer feed up to ten times
// with an exponential back-off policy.
$numberOfAttempts = 0;
$addedCustomerFeed = null;
$customerFeedServiceClient = $googleAdsClient->getCustomerFeedServiceClient();
do {
    $numberOfAttempts++;
    try {
        // Issues a mutate request to add a customer feed and print its information if the
        // request succeeded.
        $addedCustomerFeed = $customerFeedServiceClient->mutateCustomerFeeds(
            $customerId,
            [$customerFeedOperation]
        );
        printf(
            "Customer feed created with resource name: '%s'.%s",
            $addedCustomerFeed->getResults()[0]->getResourceName(),
            PHP_EOL
        );
    } catch (GoogleAdsException $googleAdsException) {
        // Waits using exponential backoff policy.
        $sleepSeconds = self::POLL_FREQUENCY_SECONDS * pow(2, $numberOfAttempts);
        // Exits the loop early if $sleepSeconds grows too large in the event that
        // MAX_CUSTOMER_FEED_ADD_ATTEMPTS is set too high.
        if (
            $sleepSeconds > self::POLL_FREQUENCY_SECONDS
            * pow(2, self::MAX_CUSTOMER_FEED_ADD_ATTEMPTS)
        ) {
            break;
        }
        printf(
            "Attempt #%d to add the customer feed was not successful."
            . " Waiting %d seconds before trying again.%s",
            $numberOfAttempts,
            $sleepSeconds,
            PHP_EOL
        );
        sleep($sleepSeconds);
    }
} while (
    $numberOfAttempts < self::MAX_CUSTOMER_FEED_ADD_ATTEMPTS
    && is_null($addedCustomerFeed)
);
      

Python

# Create a CustomerFeed operation and configure the CustomerFeed to
# associate the feed with this customer for the LOCATION placeholder
# type.

# OPTIONAL: Create a CampaignFeed to specify which FeedItems to use at
# the Campaign level.

# OPTIONAL: Create an AdGroupFeed for even more fine grained control
# over which feed items are used at the AdGroup level.
customer_feed_operation = client.get_type("CustomerFeedOperation")
customer_feed = customer_feed_operation.create
customer_feed.feed = feed_resource_name
customer_feed.placeholder_types.append(
    client.enums.PlaceholderTypeEnum.LOCATION
)
# The function string "IDENTITY(true)" will enable this feed.
true_operand = client.get_type("Operand")
true_operand.constant_operand.boolean_value = True
customer_feed.matching_function.left_operands.append(true_operand)
customer_feed.matching_function.function_string = "IDENTITY(true)"
customer_feed.matching_function.operator = (
    client.enums.MatchingFunctionOperatorEnum.IDENTITY
)

customer_feed_response = customer_feed_service.mutate_customer_feeds(
    customer_id=customer_id, operations=[customer_feed_operation]
)
print(
    "Customer feed created with resource name "
    f"'{customer_feed_response.results[0].resource_name}'."
)
      

Ruby

# After the completion of the feed ADD operation above the added feed will
# not be available for usage in a customer feed until the sync between the
# Google Ads and Business Profile accounts completes. The loop below will
# retry adding the customer feed up to ten times with an exponential back-off
# policy.
number_of_attempts = 0
added_customer_feed = nil
customer_feed_service_client = client.service.customer_feed

loop do
  number_of_attempts += 1
  begin
    # Issues a mutate request to add a customer feed and print its information
    # if the request succeeded.
    response = customer_feed_service_client.mutate_customer_feeds(
      customer_id: customer_id,
      operations: [operation]
    )
    puts "Customer feed created with resource name: " \
      "#{response.results.first.resource_name}"
  rescue Google::Ads::GoogleAds::Errors::GoogleAdsError => e
    # Waits using exponential backoff policy
    sleep_seconds = POLL_FREQUENCY_SECONDS * (2 ** number_of_attempts)
    puts "Attempt #{number_of_attempts} to add the customer feed was " \
      "not successful. Waiting #{sleep_seconds} seconds before trying again."
    sleep sleep_seconds
  end
  break if number_of_attempts >= MAX_CUSTOMER_FEED_ADD_ATTEMPTS || added_customer_feed
end
      

Perl

# After the completion of the Feed ADD operation above the added feed will not be available
# for usage in a CustomerFeed until the sync between the Google Ads and Business Profile
# accounts completes. The loop below will retry adding the CustomerFeed up to ten times with an
# exponential back-off policy.
my $customer_feed_service       = $api_client->CustomerFeedService();
my $customer_feed_resource_name = undef;
my $number_of_attempts          = 0;

while ($number_of_attempts < MAX_CUSTOMER_FEED_ADD_ATTEMPTS) {
  $number_of_attempts++;

  my $customer_feeds_response = eval {
    $customer_feed_service->mutate({
      customerId => $customer_id,
      operations => [$customer_feed_operation],
    });
  };

  if ($@) {
    # Wait using exponential backoff policy.
    my $sleep_seconds = 5 * (2**$number_of_attempts);

    # Exit the loop early if $sleep_seconds grows too large in the event that
    # MAX_CUSTOMER_FEED_ADD_ATTEMPTS is set too high.
    if ($sleep_seconds > 5 * (2**10)) {
      last;
    }

    printf "Attempt #%d to add the CustomerFeed was not successful. " .
      "Waiting %d seconds before trying again.\n",
      $number_of_attempts, $sleep_seconds;

    sleep($sleep_seconds);
  } else {
    $customer_feed_resource_name =
      $customer_feeds_response->{results}[0]{resourceName};

    printf "Customer feed created with resource name: '%s'.\n",
      $customer_feed_resource_name;

    last;
  }
}
      

เชื่อมโยงฟีดกับลูกค้า

เมื่อฟีดพร้อมแล้ว คุณจะเชื่อมโยงฟีดกับลูกค้าได้โดยสร้าง CustomerFeed จากนั้นดําเนินการ CustomerFeedService.MutateCustomerFeeds create เพื่อทําการลิงก์ให้เสร็จสมบูรณ์

ควรตั้งค่าช่องต่อไปนี้ของ CustomerFeed

แอตทริบิวต์ ค่า คำอธิบาย
feed ชื่อทรัพยากรฟีด ชื่อทรัพยากรของฟีดที่สร้างขึ้นในขั้นตอนก่อนหน้า
placeholder_types LOCATION ระบุว่าฟีดนี้จะป้อนข้อมูลส่วนขยายสถานที่ตั้งในส่วนลูกค้าที่เชื่อมต่อ
matching_function IDENTITY(true) เพื่อทําเครื่องหมายว่าฟีดนี้เปิดใช้อยู่ และIDENTITY(false)เพื่อทําเครื่องหมายว่าฟีดนี้ปิดใช้อยู่ ดูรายละเอียดเพิ่มเติมได้ที่กลยุทธ์การกรอง

Java

// Adds a CustomerFeed that associates the feed with this customer for
// the LOCATION placeholder type.
CustomerFeed customerFeed =
    CustomerFeed.newBuilder()
        .setFeed(businessProfileFeedResourceName)
        .addPlaceholderTypes(PlaceholderType.LOCATION)
        // Creates a matching function that will always evaluate to true.
        .setMatchingFunction(
            MatchingFunction.newBuilder()
                .addLeftOperands(
                    Operand.newBuilder()
                        .setConstantOperand(
                            ConstantOperand.newBuilder().setBooleanValue(true).build())
                        .build())
                .setFunctionString("IDENTITY(true)")
                .setOperator(MatchingFunctionOperator.IDENTITY)
                .build())
        .build();

CustomerFeedOperation customerFeedOperation =
    CustomerFeedOperation.newBuilder().setCreate(customerFeed).build();
      

C#

private static void CreateCustomerFeed(GoogleAdsClient client, long customerId,
    string businessProfileFeedResourceName)
{
    // Get the CustomerFeedService.
    CustomerFeedServiceClient customerFeedService = client.GetService(
        Services.V13.CustomerFeedService);

    // Adds a CustomerFeed that associates the feed with this customer for
    // the LOCATION placeholder type.
    CustomerFeed customerFeed = new CustomerFeed()
    {
        Feed = businessProfileFeedResourceName,
        PlaceholderTypes = { PlaceholderType.Location },
        MatchingFunction = new MatchingFunction()
        {
            LeftOperands =
            {
                new Operand()
                {
                    ConstantOperand = new ConstantOperand()
                    {
                        BooleanValue = true
                    }
                }
            },
            // Specify the function string as IDENTITY(true) to mark this feed as enabled.
            FunctionString = "IDENTITY(true)",
            Operator = MatchingFunctionOperator.Identity
        },
    };

    CustomerFeedOperation operation = new CustomerFeedOperation()
    {
        Create = customerFeed
    };

    MutateCustomerFeedsResponse customerFeedsResponse =
        customerFeedService.MutateCustomerFeeds(
            customerId.ToString(), new[] { operation });

    // Displays the result.
    string addedCustomerFeed = customerFeedsResponse.Results[0].ResourceName;
    Console.WriteLine($"Customer feed created with resource name: {addedCustomerFeed}.");
    return;
}
      

PHP

private static function createCustomerFeed(
    GoogleAdsClient $googleAdsClient,
    int $customerId,
    string $businessProfileFeedResourceName
) {
    // Creates a customer feed that associates the feed with this customer for the LOCATION
    // placeholder type.
    $customerFeed = new CustomerFeed([
        'feed' => $businessProfileFeedResourceName,
        'placeholder_types' => [PlaceholderType::LOCATION],
        // Creates a matching function that will always evaluate to true.
        'matching_function' => new MatchingFunction([
            'left_operands' => [new Operand([
                'constant_operand' => new ConstantOperand(['boolean_value' => true])
            ])],
            'function_string' => 'IDENTITY(true)',
            'operator' => MatchingFunctionOperator::IDENTITY
        ])
    ]);
    // Creates a customer feed operation.
    $customerFeedOperation = new CustomerFeedOperation();
    $customerFeedOperation->setCreate($customerFeed);

    // After the completion of the feed ADD operation above the added feed will not be available
    // for usage in a customer feed until the sync between the Google Ads and Business Profile
    // accounts completes. The loop below will retry adding the customer feed up to ten times
    // with an exponential back-off policy.
    $numberOfAttempts = 0;
    $addedCustomerFeed = null;
    $customerFeedServiceClient = $googleAdsClient->getCustomerFeedServiceClient();
    do {
        $numberOfAttempts++;
        try {
            // Issues a mutate request to add a customer feed and print its information if the
            // request succeeded.
            $addedCustomerFeed = $customerFeedServiceClient->mutateCustomerFeeds(
                $customerId,
                [$customerFeedOperation]
            );
            printf(
                "Customer feed created with resource name: '%s'.%s",
                $addedCustomerFeed->getResults()[0]->getResourceName(),
                PHP_EOL
            );
        } catch (GoogleAdsException $googleAdsException) {
            // Waits using exponential backoff policy.
            $sleepSeconds = self::POLL_FREQUENCY_SECONDS * pow(2, $numberOfAttempts);
            // Exits the loop early if $sleepSeconds grows too large in the event that
            // MAX_CUSTOMER_FEED_ADD_ATTEMPTS is set too high.
            if (
                $sleepSeconds > self::POLL_FREQUENCY_SECONDS
                * pow(2, self::MAX_CUSTOMER_FEED_ADD_ATTEMPTS)
            ) {
                break;
            }
            printf(
                "Attempt #%d to add the customer feed was not successful."
                . " Waiting %d seconds before trying again.%s",
                $numberOfAttempts,
                $sleepSeconds,
                PHP_EOL
            );
            sleep($sleepSeconds);
        }
    } while (
        $numberOfAttempts < self::MAX_CUSTOMER_FEED_ADD_ATTEMPTS
        && is_null($addedCustomerFeed)
    );

    if (is_null($addedCustomerFeed)) {
        throw new \RuntimeException(
            'Could not create the customer feed after ' . self::MAX_CUSTOMER_FEED_ADD_ATTEMPTS
            . ' attempts. Please retry the customer feed ADD operation later.'
        );
    }
}
      

Python

# After the completion of the Feed ADD operation above the added feed
# will not be available for usage in a CustomerFeed until the sync
# between the Google Ads and Business Profile accounts completes.
# This process is asynchronous, so we wait until the feed mapping is
# created, performing exponential backoff.
customer_feed_resource_name = None
number_of_attempts = 0

while number_of_attempts < MAX_CUSTOMER_FEED_ADD_ATTEMPTS:
    feed_mapping = get_business_profile_feed_mapping(
        client, customer_id, feed_resource_name
    )

    if feed_mapping is None:
        number_of_attempts += 1
        sleep_seconds = 5 * (2 ** number_of_attempts)

        print(
            f"Attempt #{number_of_attempts} was not successful. "
            f"Waiting {sleep_seconds}s before trying again."
        )

        time.sleep(sleep_seconds)
    else:
        customer_feed_resource_name = feed_mapping.resource_name
        print(f"Business Profile feed {feed_resource_name} is now ready.")
        break
      

Ruby

def create_customer_feed(
  client,
  customer_id,
  business_profile_feed_resource_name)
  # Creates a customer feed operation.
  operation = client.operation.create_resource.customer_feed do |cf|
    cf.feed = business_profile_feed_resource_name
    cf.placeholder_types << :LOCATION
    cf.matching_function = client.resource.matching_function do |m|
      m.left_operands << client.resource.operand do |op|
        op.constant_operand = client.resource.constant_operand do |co|
          co.boolean_value = true
        end
      end
      m.function_string = "IDENTITY(true)"
      m.operator = :IDENTITY
    end
  end

  # After the completion of the feed ADD operation above the added feed will
  # not be available for usage in a customer feed until the sync between the
  # Google Ads and Business Profile accounts completes. The loop below will
  # retry adding the customer feed up to ten times with an exponential back-off
  # policy.
  number_of_attempts = 0
  added_customer_feed = nil
  customer_feed_service_client = client.service.customer_feed

  loop do
    number_of_attempts += 1
    begin
      # Issues a mutate request to add a customer feed and print its information
      # if the request succeeded.
      response = customer_feed_service_client.mutate_customer_feeds(
        customer_id: customer_id,
        operations: [operation]
      )
      puts "Customer feed created with resource name: " \
        "#{response.results.first.resource_name}"
    rescue Google::Ads::GoogleAds::Errors::GoogleAdsError => e
      # Waits using exponential backoff policy
      sleep_seconds = POLL_FREQUENCY_SECONDS * (2 ** number_of_attempts)
      puts "Attempt #{number_of_attempts} to add the customer feed was " \
        "not successful. Waiting #{sleep_seconds} seconds before trying again."
      sleep sleep_seconds
    end
    break if number_of_attempts >= MAX_CUSTOMER_FEED_ADD_ATTEMPTS || added_customer_feed
  end

  if added_customer_feed.nil?
    raise "Could not create the customer feed after #{MAX_CUSTOMER_FEED_ADD_ATTEMPTS} " \
      "attempts. Please retry the customer feed ADD operation later."
  end
end
      

Perl

# Add a CustomerFeed that associates the feed with this customer for the LOCATION
# placeholder type.
my $customer_feed = Google::Ads::GoogleAds::V13::Resources::CustomerFeed->new(
  {
    feed             => $feed_resource_name,
    placeholderTypes => LOCATION,
    # Create a matching function that will always evaluate to true.
    matchingFunction =>
      Google::Ads::GoogleAds::V13::Common::MatchingFunction->new({
        leftOperands => [
          Google::Ads::GoogleAds::V13::Common::Operand->new({
              constantOperand =>
                Google::Ads::GoogleAds::V13::Common::ConstantOperand->new({
                  booleanValue => "true"
                })})
        ],
        functionString => "IDENTITY(true)",
        operator       => IDENTITY
      })});