مشوق‌ها

مشوق‌ها پیشنهادهای تبلیغاتی هستند که برای تشویق کاربران به استفاده از Google Ads ارائه می‌شوند. این راهنما توضیح می‌دهد که چگونه از Google Ads API برای واکشی برنامه‌ای و اعمال مشوق‌های Google Ads برای مشتریانتان استفاده کنید.

واکشی مشوق‌ها

می‌توانید از روش IncentiveService.FetchIncentive برای واکشی مشوق‌های دردسترس برای مشتری استفاده کنید. این روش می‌تواند گزینه‌های تشویقی شخصی‌سازی‌شده «انتخاب خودتان» (CYO) را برگرداند.

FetchIncentiveRequest می‌تواند شامل موارد زیر باشد:

  • language_code: کد زبان BCP 47 مشتری (به‌طور پیش‌فرض en).
  • country_code: کد کشور ISO 3166-1 alpha-2 دوحرفی مشتری (به‌طور پیش‌فرض US).
  • ‫email: نشانی ایمیل مشتری. از v24، اگر نشانی ایمیل نامعتبر ارائه شود، FetchIncentive به برگرداندن پیشنهادهای تشویقی پیش‌فرض برمی‌گردد؛ در v23، نشانی ایمیل نامعتبر خطای AuthenticationError.INVALID_EMAIL_ADDRESS را برمی‌گرداند.
  • incentive_type (در v25 و نسخه‌های جدیدتر؛ با نام type با enum تودرتو FetchIncentiveRequest.IncentiveType در v24 و نسخه‌های قدیمی‌تر): IncentiveType مشوقی که باید دریافت شود (اگر حذف شود، به‌طور پیش‌فرض ACQUISITION است). ‫Google Ads API از مشوق‌های نوع ACQUISITION پشتیبانی می‌کند که فقط برای حساب‌های جدید (حساب‌هایی که کمتر از ۱۴ روز است آگهی ارائه می‌دهند) است.

FetchIncentiveResponse حاوی IncentiveOffer است که شامل consolidated_terms_and_conditions_url می‌شود. اگر OfferType در offer_type (به‌نام type با enum تودرتوی IncentiveOffer.OfferType در v24 و نسخه‌های قبلی) CYO_INCENTIVE باشد، فیلد cyo_incentives حاوی low_offer، medium_offer، و high_offer است که هرکدام یک Incentive با جزئیاتی مثل incentive_id، incentive_type (به‌نام type در v24 و نسخه‌های قبلی)، requirement، و incentive_terms_and_conditions_url است. اگر هیچ مشوقی برای کاربر دردسترس نباشد، فیلد IncentiveOffer offer_type NO_INCENTIVE است و فیلد incentive_details تنظیم نشده است.

مثال زیر نحوه واکشی مشوق‌ها را نشان می‌دهد:

جاوا

// Copyright 2026 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.incentives;

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.v26.errors.GoogleAdsError;
import com.google.ads.googleads.v26.errors.GoogleAdsException;
import com.google.ads.googleads.v26.services.CyoIncentives;
import com.google.ads.googleads.v26.services.FetchIncentiveRequest;
import com.google.ads.googleads.v26.enums.IncentiveTypeEnum.IncentiveType;
import com.google.ads.googleads.v26.services.FetchIncentiveResponse;
import com.google.ads.googleads.v26.services.Incentive;
import com.google.ads.googleads.v26.services.IncentiveServiceClient;
import java.io.FileNotFoundException;
import java.io.IOException;

/**
 * This example fetches the available incentives for a user.
 */
public class FetchIncentives {

  private static class FetchIncentivesParams extends CodeSampleParams {

    @Parameter(
        names = ArgumentNames.EMAIL_ADDRESS,
        required = true,
        description = "The email of the user to fetch incentives for.")
    private String email;

    @Parameter(
        names = ArgumentNames.LANGUAGE_CODE,
        description = "The language for the returned incentive.")
    private String languageCode = "en";

    @Parameter(
        names = ArgumentNames.COUNTRY_CODE,
        description = "The country for the returned incentive.")
    private String countryCode = "US";
  }

  public static void main(String[] args) throws IOException {
    FetchIncentivesParams params = new FetchIncentivesParams();
    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 more information.
      params.email = "INSERT_EMAIL_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 FetchIncentives()
          .runExample(googleAdsClient, params.email, params.languageCode, params.countryCode);
    } 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 GoogleAdsError instances that detail the underlying causes of the
      // exception.
      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 email the email of the user to fetch incentives for.
   * @param languageCode the language of the incentives.
   * @param countryCode the country of the incentives.
   */
  private void runExample(
      GoogleAdsClient googleAdsClient, String email, String languageCode, String countryCode) {
    try (IncentiveServiceClient incentiveServiceClient =
        googleAdsClient.getLatestVersion().createIncentiveServiceClient()) {
      FetchIncentiveRequest request = FetchIncentiveRequest.newBuilder().setCountryCode(countryCode)
          .setLanguageCode(languageCode).setEmail(email).setIncentiveType(IncentiveType.ACQUISITION).build();

      // Issues the request.
      FetchIncentiveResponse response =
          incentiveServiceClient.fetchIncentive(request);

      // Processes the response.
      if (!response.hasIncentiveOffer()) {
        System.out.print("No incentive offer was found");
        return;
      }

      // If the offer type is CHOOSE_YOUR_OWN_INCENTIVE, there will be 3 incentives in the
      // response. At the time this example was written, all incentive offers are CYO incentive offers.
      if (response.getIncentiveOffer().hasCyoIncentives()) {
        CyoIncentives cyoIncentives = response.getIncentiveOffer().getCyoIncentives();
        printIncentiveDetails(cyoIncentives.getLowOffer());
        printIncentiveDetails(cyoIncentives.getMediumOffer());
        printIncentiveDetails(cyoIncentives.getHighOffer());
      }
    }
  }

  private void printIncentiveDetails(Incentive incentive) {
    System.out.println("====================================================================");
    System.out.printf("Incentive ID: '%s'%n", incentive.getIncentiveId());
    System.out.printf("Incentive requirement: '%s'%n", incentive.getRequirement());
    System.out.printf(
        "Incentive terms and conditions: '%s'%n", incentive.getIncentiveTermsAndConditionsUrl());
    System.out.println("====================================================================");
  }
}



      

C#‎

// Copyright 2026 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.Lib;
using Google.Ads.GoogleAds.Lib;
using Google.Ads.GoogleAds.V26.Errors;
using Google.Ads.GoogleAds.V26.Services;
using System;
using static Google.Ads.GoogleAds.V26.Enums.IncentiveTypeEnum.Types;


namespace Google.Ads.GoogleAds.Examples.V26
{
    /// <summary>
    /// This code example fetches the available incentives for a user.
    /// </summary>
    public class FetchIncentives : ExampleBase
    {
         /// <summary>
        /// Command line options for running the <see cref="FetchIncentives"/> example.
        /// </summary>
        public class Options : OptionsBase
        {
            /// <summary>
            /// The email of the user to fetch incentives for.
            /// </summary>
            [Option("email", Required = true, HelpText =
                "The email of the user to fetch incentives for.")]
            public string Email { get; set; }

            /// <summary>
            /// The language for the returned incentive.
            /// </summary>
            [Option("languageCode", Required = true, HelpText =
                "The language for the returned incentive.")]
            public string LanguageCode { get; set; }

            /// <summary>
            /// The country for the returned incentive.
            /// </summary>
            [Option("countryCode", Required = true, HelpText =
                "The country for the returned incentive.")]
            public string CountryCode { 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);

            FetchIncentives codeExample = new FetchIncentives();
            Console.WriteLine(codeExample.Description);
            codeExample.Run(new GoogleAdsClient(), options.Email,
            options.LanguageCode, options.CountryCode);
        }

        /// <summary>
        /// Returns a description about the code example.
        /// </summary>
        public override string Description =>
            "This code example fetches the available incentives for a user.";

        /// <summary>
        /// Runs the code example.
        /// </summary>
        /// <param name="client">The Google Ads client.</param>
        /// <param name="email">The email of the user to fetch incentives for.</param>
        /// <param name="languageCode">The language for the returned incentive.</param>
        /// <param name="countryCode">The country for the returned incentive.</param>
        public void Run(GoogleAdsClient client, string email, string languageCode,
            string countryCode)
        {
            IncentiveServiceClient incentiveService = client.GetService(
                Services.V26.IncentiveService);

            FetchIncentiveRequest request = new FetchIncentiveRequest()
            {
                CountryCode = countryCode,
                LanguageCode = languageCode,
                Email = email,
                IncentiveType = IncentiveType.Acquisition                
            };

            try
            {
                FetchIncentiveResponse response =
                    incentiveService.FetchIncentive(request);

                if (response.IncentiveOffer.IsEmpty())
                {
                    Console.WriteLine("No incentive offer was found.");
                    return;
                }

                if (!response.IncentiveOffer.CyoIncentives.IsEmpty())
                {
                    CyoIncentives cyoIncentives = response.IncentiveOffer.CyoIncentives;
                    printIncentiveDetails(cyoIncentives.LowOffer);
                }

            } catch  (GoogleAdsException e)
            {
                Console.WriteLine("Failure:");
                Console.WriteLine($"Message: {e.Message}");
                Console.WriteLine($"Failure: {e.Failure}");
                Console.WriteLine($"Request ID: {e.RequestId}");
                throw;
            }
        }

        private void printIncentiveDetails(Incentive incentive)
        {
            Console.WriteLine("===========================================");
            Console.WriteLine($"Incentive ID: {incentive.IncentiveId}");
            Console.WriteLine($"Incentive requirement: {incentive.Requirement}");
            Console.WriteLine($"Incentive terms and conditions: {incentive.IncentiveTermsAndConditionsUrl}");
            Console.WriteLine("===========================================");
        }

    }
}
      

PHP

This example is not yet available in PHP; you can take a look at the other languages.
    

Python

#!/usr/bin/env python
# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""This example returns incentives for a given user.

To apply an incentive, use apply_incentive.py.
"""

import argparse
import sys

from google.ads.googleads.client import GoogleAdsClient
from google.ads.googleads.errors import GoogleAdsException
from google.ads.googleads.v24.services import (
    FetchIncentiveRequest,
    FetchIncentiveResponse,
)
from google.ads.googleads.v24.services.services.incentive_service.client import (
    IncentiveServiceClient,
)


def main(
    client: GoogleAdsClient,
    email_address: str,
    language_code: str,
    country_code: str,
) -> None:
    """Returns incentives for a given user.

    Args:
        client: An initialized GoogleAdsClient instance.
        email_address: The email of the user to fetch incentives for.
        language_code: The language code of the user (e.g. 'en').
        country_code: The country code of the user (e.g. 'US').
    """
    incentive_service: IncentiveServiceClient = client.get_service(
        "IncentiveService"
    )
    fetch_incentive_request: FetchIncentiveRequest = client.get_type(
        "FetchIncentiveRequest"
    )

    fetch_incentive_request.email = email_address
    fetch_incentive_request.language_code = language_code
    fetch_incentive_request.country_code = country_code

    response: FetchIncentiveResponse = incentive_service.fetch_incentive(
        request=fetch_incentive_request
    )

    if response.incentive_offer and response.incentive_offer.cyo_incentives:
        print("Fetched incentive.")
        # If the offer type is CHOOSE_YOUR_OWN_INCENTIVE, there will be three
        # incentives in the response. At the time this example was written, all
        # incentive offers are CYO incentive offers.
        cyo_incentives = response.incentive_offer.cyo_incentives
        print(cyo_incentives.low_offer)
        print(cyo_incentives.medium_offer)
        print(cyo_incentives.high_offer)
    else:
        print("No incentives found.")


if __name__ == "__main__":
    parser = argparse.ArgumentParser(
        description="Returns incentives for a given user."
    )
    # The following argument(s) should be provided to run the example.
    parser.add_argument(
        "-e",
        "--email_address",
        type=str,
        required=True,
        help="The email of the user to fetch incentives for.",
    )
    parser.add_argument(
        "-l",
        "--language_code",
        type=str,
        required=False,
        default="en",
        help="The language code of the user (e.g. 'en').",
    )
    parser.add_argument(
        "-k",
        "--country_code",
        type=str,
        required=False,
        default="US",
        help="The country code of the user (e.g. 'US').",
    )
    args = parser.parse_args()

    # GoogleAdsClient will read the google-ads.yaml configuration file in the
    # home directory if none is specified.
    googleads_client = GoogleAdsClient.load_from_storage(version="v24")

    try:
        main(
            googleads_client,
            args.email_address,
            args.language_code,
            args.country_code,
        )
    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

This example is not yet available in Ruby; you can take a look at the other languages.
    

پرل

#!/usr/bin/perl -w
#
# Copyright 2026, Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# This example returns incentives for a given user.
#
# To apply an incentive, use apply_incentive.pl.

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::V26::Services::IncentiveService::FetchIncentiveRequest;

use Getopt::Long qw(:config auto_help);
use Pod::Usage;
use Cwd          qw(abs_path);
use JSON;

sub fetch_incentives {
  my ($api_client, $email_address, $language_code, $country_code) = @_;

  my $fetch_incentives_request =
    Google::Ads::GoogleAds::V26::Services::IncentiveService::FetchIncentiveRequest
    ->new({
      email        => $email_address,
      languageCode => $language_code,
      countryCode  => $country_code,
      type         => "ACQUISITION"
    });

  # Issue the request.
  my $fetch_incentives_response =
    $api_client->IncentiveService()->fetch_incentive($fetch_incentives_request);

  # Process the response.
  if ( $fetch_incentives_response->{incentiveOffer}
    && $fetch_incentives_response->{incentiveOffer}{cyoIncentives})
  {
    print "Fetched incentive.\n";
    # If the offer type is CHOOSE_YOUR_OWN_INCENTIVE, there will be three
    # incentives in the response. At the time this example was written, all
    # incentive offers are CYO incentive offers.
    my $cyo_incentives =
      $fetch_incentives_response->{incentiveOffer}{cyoIncentives};
    print_incentive_details($cyo_incentives->{lowOffer});
    print_incentive_details($cyo_incentives->{mediumOffer});
    print_incentive_details($cyo_incentives->{highOffer});
  } else {
    print "No incentives found.\n";
  }

  return 1;
}

sub print_incentive_details {
  my ($incentive) = @_;

  return unless defined $incentive;

  printf "Incentive ID: '%s'.\n",        $incentive->{incentiveId};
  printf "Incentive requirement: %s.\n", encode_json($incentive->{requirement});
  printf "Incentive terms and conditions: %s.\n",
    $incentive->{incentiveTermsAndConditionsUrl};
}

# 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);

# Initialize the command line parameters.
my $email_address;
my $language_code = "en";
my $country_code  = "US";

# Parameters passed on the command line will override any parameters set in code.
GetOptions(
  "email_address=s" => \$email_address,
  "language_code=s" => \$language_code,
  "country_code=s"  => \$country_code
);

# Print the help message if the parameters are not initialized in the code nor
# in the command line.
pod2usage(2) if not check_params($email_address);

# Call the example.
fetch_incentives($api_client, $email_address, $language_code, $country_code);

=pod

=head1 NAME

fetch_incentives

=head1 DESCRIPTION

This example returns incentives for a given user. To apply an incentive, use
apply_incentive.pl.

=head1 SYNOPSIS

fetch_incentives.pl [options]

    -help                       Show the help message.
    -email_address              The email of the user to fetch incentives for.
    -language_code              [optional] The language code of the user (e.g. 'en').
    -country_code               [optional] The country code of the user (e.g. 'US').

=cut

      

curl

اعمال کردن مشوق‌ها

پس‌از اینکه مشتری مشوقی را انتخاب کرد، می‌توانید از روش IncentiveService.ApplyIncentive برای اعمال آن به حساب مشتری Google Ads خاصی استفاده کنید.

ApplyIncentiveRequest به فیلدهای زیر نیاز دارد (در v25 و نسخه‌های جدیدتر، هر سه فیلد در تعریف protobuf با REQUIRED علامت‌گذاری شده‌اند و به‌عنوان امضای روش ۳ آرگومانی پشتیبانی می‌شوند؛ در v24 و نسخه‌های قدیمی‌تر، selected_incentive_id و customer_id در طرح‌واره به‌عنوان اختیاری علامت‌گذاری شده‌اند):

  • selected_incentive_id: شناسه مشوقی که مشتری انتخاب کرده است.
  • customer_id: شناسه مشتری حسابی که مشوق را در آن اعمال می‌کنید.
  • country_code: کد کشور دوحرفی ISO 3166-1 alpha-2 مشتری، که باید با کشور صورت‌حساب حساب Google Ads مطابقت داشته باشد.

ApplyIncentiveResponse coupon_code مشوق اعمال‌شده و creation_time (در قالب "yyyy-MM-dd HH:mm:ss" در ساعت هماهنگ جهانی) را برمی‌گرداند.

مثال زیر نحوه اعمال مشوق را نشان می‌دهد:

جاوا

// Copyright 2026 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.incentives;

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.v26.errors.GoogleAdsError;
import com.google.ads.googleads.v26.errors.GoogleAdsException;
import com.google.ads.googleads.v26.services.ApplyIncentiveRequest;
import com.google.ads.googleads.v26.services.ApplyIncentiveResponse;
import com.google.ads.googleads.v26.services.IncentiveServiceClient;
import java.io.FileNotFoundException;
import java.io.IOException;

/**
 * This example applies an incentive to a user's account.
 *
 * <p>This example is a no-op if the user already has an accepted incentive. If the user attempts to
 * apply a new incentive, the response will simply return the existing incentive that has already
 * been applied to the account.
 */
public class ApplyIncentive {

  private static class ApplyIncentiveParams extends CodeSampleParams {

    @Parameter(
        names = ArgumentNames.CUSTOMER_ID,
        required = true,
        description = "The Google Ads customer ID.")
    private Long customerId;

    @Parameter(
        names = ArgumentNames.INCENTIVE_ID,
        required = true,
        description = "The ID of the incentive to apply.")
    private Long incentiveId;

    @Parameter(
        names = ArgumentNames.COUNTRY_CODE,
        required = true,
        description = "The country for the incentive to apply.")
    private String countryCode = "US";
  }

  public static void main(String[] args) throws IOException {
    ApplyIncentiveParams params = new ApplyIncentiveParams();
    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 more information.
      params.customerId = Long.parseLong("INSERT_CUSTOMER_ID_HERE");
      params.incentiveId = Long.parseLong("INSERT_INCENTIVE_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 ApplyIncentive().runExample(googleAdsClient, params.customerId, params.incentiveId,
          params.countryCode);
    } 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 GoogleAdsError instances that detail the underlying causes of the
      // exception.
      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.
   * @param incentiveId the ID of the incentive to apply.
   * @param countryCode the country of the incentive.
   */
  private void runExample(GoogleAdsClient googleAdsClient, long customerId, long incentiveId,
      String countryCode) {
    try (IncentiveServiceClient incentiveServiceClient = googleAdsClient.getLatestVersion()
        .createIncentiveServiceClient()) {
      ApplyIncentiveRequest request = ApplyIncentiveRequest.newBuilder()
          .setCustomerId(String.valueOf(customerId))
          .setSelectedIncentiveId(incentiveId)
          .setCountryCode(countryCode).build();
      // Issues the request.
      ApplyIncentiveResponse response = incentiveServiceClient.applyIncentive(request);

      // Processes the response.
      System.out.println("====================================================================");
      System.out.printf("Applied incentive with coupon code '%s'.%n", response.getCouponCode());
      System.out.printf("Incentive was created at '%s'.%n", response.getCreationTime());
      System.out.println("====================================================================");
    }
  }
}

      

C#‎

// Copyright 2026 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.Lib;
using Google.Ads.GoogleAds.Config;
using Google.Ads.GoogleAds.Extensions.Config;
using Google.Ads.GoogleAds.Lib;
using Google.Ads.GoogleAds.V26.Errors;
using Google.Ads.GoogleAds.V26.Services;
using System;

namespace Google.Ads.GoogleAds.Examples.V26
{
    /// <summary>
    /// This code example applies an incentive to a user's account.
    /// </summary>
    public class ApplyIncentive : ExampleBase
    {
         /// <summary>
        /// Command line options for running the <see cref="FetchIncentives"/> example.
        /// </summary>
        public class Options : OptionsBase
        {
            /// <summary>
            /// The customer ID for which the call is made.
            /// </summary>
            [Option("customerId", Required = true, HelpText =
                "The customer ID for which the call is made.")]
            public long CustomerId { get; set; }

            /// <summary>
            /// The ID of the incentive to apply.
            /// </summary>
            [Option("incentiveId", Required = true, HelpText =
                "The ID of the incentive to apply.")]
            public long IncentiveId { get; set; }

            /// <summary>
            /// The country for the incentive to apply.
            /// </summary>
            [Option("countryCode", Required = true, HelpText =
                "The country for the incentive to apply.")]
            public string CountryCode { 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);

            ApplyIncentive codeExample = new ApplyIncentive();
            Console.WriteLine(codeExample.Description);              
            codeExample.Run(new GoogleAdsClient(), options.CustomerId,
            options.IncentiveId, options.CountryCode);
        }

        /// <summary>
        /// Returns a description about the code example.
        /// </summary>
        public override string Description =>
            "This code example applies an incentive to a user's account.";

        /// <summary>
        /// Runs the code example.
        /// </summary>
        /// <param name="client">The Google Ads client.</param>
        /// <param name="customerId">The client customer ID.</param>
        /// <param name="incentiveId">The ID of the incentive to apply.</param>
        /// <param name="countryCode">The country for the returned incentive.</param>
        public void Run(GoogleAdsClient client, long customerId,
            long incentiveId, string countryCode)
        {
            IncentiveServiceClient incentiveService = client.GetService(
                Services.V26.IncentiveService);

            ApplyIncentiveRequest request = new ApplyIncentiveRequest()
            {
                CustomerId = customerId.ToString(),
                SelectedIncentiveId = incentiveId,
                CountryCode = countryCode
            };

            try
            {
                ApplyIncentiveResponse response =
                    incentiveService.ApplyIncentive(request);

                Console.WriteLine("===========================================");
                Console.WriteLine($"Applied incentive with coupon code: {response.CouponCode}");
                Console.WriteLine($"Incentive was created at: {response.CreationTime}");
                Console.WriteLine("===========================================");

            } catch  (GoogleAdsException e)
            {
                Console.WriteLine("Failure:");
                Console.WriteLine($"Message: {e.Message}");
                Console.WriteLine($"Failure: {e.Failure}");
                Console.WriteLine($"Request ID: {e.RequestId}");
                throw;
            }
        }
    }
}
      

PHP

This example is not yet available in PHP; you can take a look at the other languages.
    

Python

#!/usr/bin/env python
# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""This example applies an incentive to a user's account.

This example is a no-op if the user already has an accepted incentive. If the
user attempts to apply a new incentive, the response will simply return the
existing incentive that has already been applied to the account. Use the
fetch_incentives.py example to get the available incentives.
"""

import argparse
import sys

from google.ads.googleads.client import GoogleAdsClient
from google.ads.googleads.errors import GoogleAdsException
from google.ads.googleads.v24.services import (
    ApplyIncentiveRequest,
    ApplyIncentiveResponse,
)
from google.ads.googleads.v24.services.services.incentive_service.client import (
    IncentiveServiceClient,
)


def main(
    client: GoogleAdsClient,
    customer_id: str,
    incentive_id: str,
    country_code: str,
) -> None:
    """Applies an incentive for the ads customer.

    Args:
        client: An initialized GoogleAdsClient instance.
        customer_id: The client customer ID.
        country_code: The country code of the user.
        incentive_id: The incentive ID to select.
    """
    incentive_service: IncentiveServiceClient = client.get_service(
        "IncentiveService"
    )
    apply_incentive_request: ApplyIncentiveRequest = client.get_type(
        "ApplyIncentiveRequest"
    )

    apply_incentive_request.customer_id = customer_id
    apply_incentive_request.selected_incentive_id = incentive_id

    if country_code:
        apply_incentive_request.country_code = country_code

    response: ApplyIncentiveResponse = incentive_service.apply_incentive(
        request=apply_incentive_request
    )

    print("Applied incentive.")
    print(f"Coupon Code: {response.coupon_code}")
    print(f"Creation Time: {response.creation_time}")


if __name__ == "__main__":
    parser = argparse.ArgumentParser(
        description="Applies an incentive for the ads customer."
    )
    # 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(
        "-i",
        "--incentive_id",
        type=int,
        required=True,
        help="The incentive ID to select.",
    )
    parser.add_argument(
        "-k",
        "--country_code",
        type=str,
        required=True,
        help="The country code of the user (e.g. 'US').",
    )
    args = parser.parse_args()

    # GoogleAdsClient will read the google-ads.yaml configuration file in the
    # home directory if none is specified.
    googleads_client = GoogleAdsClient.load_from_storage(version="v24")

    try:
        main(
            googleads_client,
            args.customer_id,
            args.incentive_id,
            args.country_code,
        )
    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

This example is not yet available in Ruby; you can take a look at the other languages.
    

پرل

#!/usr/bin/perl -w
#
# Copyright 2026, Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# This example applies an incentive to a user's account.
#
# This example is a no-op if the user already has an accepted incentive.
# If the user attempts to apply a new incentive, the response will simply
# return the existing incentive that has already been applied to the account.
# Use the fetch_incentives.pl example to get the available incentives.

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::V26::Services::IncentiveService::ApplyIncentiveRequest;

use Getopt::Long qw(:config auto_help);
use Pod::Usage;
use Cwd          qw(abs_path);

sub apply_incentive {
  my ($api_client, $customer_id, $incentive_id, $country_code) = @_;

  my $apply_incentive_request =
    Google::Ads::GoogleAds::V26::Services::IncentiveService::ApplyIncentiveRequest
    ->new({
      customerId          => $customer_id,
      selectedIncentiveId => $incentive_id,
      countryCode         => $country_code
    });

  # Issue the request.
  my $apply_incentive_response =
    $api_client->IncentiveService()->apply_incentive($apply_incentive_request);

  # Process the response.
  print "Applied incentive.\n";
  printf "Coupon Code: %s\n",   $apply_incentive_response->{couponCode};
  printf "Creation Time: %s\n", $apply_incentive_response->{creationTime};

  return 1;
}

# Don't run the example if the file is being included.
if (abs_path($0) ne abs_path(__FILE__)) {
  return 1;
}

# Get Google Ads Client, credentials will be read from ~/googleads.properties.
my $api_client = Google::Ads::GoogleAds::Client->new();

# By default examples are set to die on any server returned fault.
$api_client->set_die_on_faults(1);

# Initialize the command line parameters.
my $customer_id;
my $incentive_id;
my $country_code;

# Parameters passed on the command line will override any parameters set in code.
GetOptions(
  "customer_id=s"  => \$customer_id,
  "incentive_id=i" => \$incentive_id,
  "country_code=s" => \$country_code
);

# 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, $incentive_id, $country_code);

# Call the example.
apply_incentive($api_client, $customer_id =~ s/-//gr,
  $incentive_id, $country_code);

=pod

=head1 NAME

apply_incentive

=head1 DESCRIPTION

This example applies an incentive to a user's account. This example is a no-op
if the user already has an accepted incentive. If the user attempts to apply a new
incentive, the response will simply return the existing incentive that has already
been applied to the account. Use the fetch_incentives.pl example to get the
available incentives.

=head1 SYNOPSIS

apply_incentive.pl [options]

    -help                       Show the help message.
    -customer_id                The Google Ads customer ID.
    -incentive_id               The ID of the incentive to apply.
    -country_code               The country code of the user (e.g. 'US').

=cut

      

curl

بازیابی مشوق‌های اعمال‌شده

می‌توانید منبع فقط خواندنی AppliedIncentive (applied_incentive) را ازطریق GoogleAdsService.Search و GoogleAdsService.SearchStream پرس‌وجو کنید تا جزئیات مربوط به مشوق‌های اعمال‌شده را بازیابی کنید.

فیلدهای کلیدی دردسترس در AppliedIncentive شامل موارد زیر است:

  • resource_name: نام منبع در قالب customers/{customer_id}/appliedIncentives/{coupon_code}.
  • ‫coupon_code: کد کوپن مشوق.
  • incentive_state: IncentiveState فعلی مشوق (مانند REDEEMED، FULFILLED، REWARD_GRANTED، EXPIRED، REWARD_EXHAUSTED، یا INVALIDATED).
  • ‫redemption_date_time، fulfillment_expiration_date_time، reward_grant_date_time، و reward_expiration_date_time: مُهرهای زمان در قالب "yyyy-MM-dd HH:mm:ss" به‌وقت ساعت هماهنگ جهانی.
  • ‫currency_code،‏ reward_amount_micros،‏ granted_amount_micros،‏ required_min_spend_micros،‏ current_spend_towards_fulfillment_micros، و reward_balance_remaining_micros: واحد پول و مبالغ پولی به میکرو.

پُرسمان Google Ads Query Language زیر همه فیلدها را از AppliedIncentive واکشی می‌کند:

SELECT
  applied_incentive.resource_name,
  applied_incentive.coupon_code,
  applied_incentive.incentive_state,
  applied_incentive.redemption_date_time,
  applied_incentive.fulfillment_expiration_date_time,
  applied_incentive.reward_grant_date_time,
  applied_incentive.reward_expiration_date_time,
  applied_incentive.currency_code,
  applied_incentive.reward_amount_micros,
  applied_incentive.granted_amount_micros,
  applied_incentive.required_min_spend_micros,
  applied_incentive.current_spend_towards_fulfillment_micros,
  applied_incentive.reward_balance_remaining_micros
FROM
  applied_incentive