Google utiliza tecnología de IA para traducir contenido a tu idioma preferido. Las traducciones realizadas con IA pueden contener errores.
Recuperar incentivos
Organiza tus páginas con colecciones
Guarda y categoriza el contenido según tus preferencias.
Java
// 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
#!/usr/bin/env ruby
# Encoding: utf-8
#
# 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.
#
# This example fetches the available incentives for a user.
require 'bigdecimal'
require 'optparse'
require 'google/ads/google_ads'
def fetch_incentives(email, language_code = 'en', country_code = 'US')
# GoogleAdsClient will read a config file from a default location
# if no path is passed.
client = Google::Ads::GoogleAds::GoogleAdsClient.new
# Issues the request.
request_args = {
email: email.to_s.strip,
language_code: language_code,
country_code: country_code,
# Passing :ACQUISITION as the symbol representation of the IncentiveType enum.
incentive_type: :ACQUISITION,
}.compact
response = client.service.incentive.fetch_incentive(**request_args)
# Processes the response.
if response.incentive_offer.nil? || response.incentive_offer.offer_type == :NO_INCENTIVE
puts 'No incentive offer was found.'
return
end
# 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.incentive_offer.cyo_incentives
cyo = response.incentive_offer.cyo_incentives
[cyo.low_offer, cyo.medium_offer, cyo.high_offer].compact.each do |incentive|
print_incentive_details(incentive)
end
unless response.incentive_offer.consolidated_terms_and_conditions_url.empty?
puts "Consolidated terms and conditions: '#{response.incentive_offer.consolidated_terms_and_conditions_url}'"
end
else
puts 'Incentive offer is not a CHOOSE_YOUR_OWN_INCENTIVE type. ' \
'Non-CYO offers are not supported by this example.'
end
end
def print_incentive_details(incentive)
return if incentive.nil?
puts '=' * 68
puts "Incentive ID: '#{incentive.incentive_id}'"
puts "Incentive requirement: '#{format_requirement(incentive.requirement)}'"
unless incentive.incentive_terms_and_conditions_url.empty?
puts "Incentive terms and conditions: '#{incentive.incentive_terms_and_conditions_url}'"
end
puts '=' * 68
end
def format_requirement(requirement)
return 'No requirements' if requirement.nil?
if requirement.spend
spend = requirement.spend
required = format_money(spend.required_amount)
award = format_money(spend.award_amount)
"Spend #{required} to receive #{award}"
else
'Unsupported requirement type'
end
end
def format_money(money)
return 'N/A' if money.nil?
amount = BigDecimal(money.units) + (BigDecimal(money.nanos) / 1_000_000_000)
currency = money.currency_code.empty? ? '' : " #{money.currency_code}"
format('%.2f%s', amount, currency)
end
if __FILE__ == $PROGRAM_NAME
options = {}
# The following parameter(s) should be provided to run the example. You can
# either specify these by changing the default 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[:email] = 'INSERT_EMAIL_HERE'
options[:language_code] = 'en'
options[:country_code] = 'US'
OptionParser.new do |opts|
opts.banner = "Usage: #{File.basename(__FILE__)} [options]"
opts.separator ''
opts.separator 'Options:'
opts.on('-E', '--email EMAIL', String, 'Email') do |v|
options[:email] = v
end
opts.on('-L', '--language-code LANGUAGE-CODE', String, 'Language Code') do |v|
options[:language_code] = v
end
opts.on('-K', '--country-code COUNTRY-CODE', String, 'Country Code') do |v|
options[:country_code] = v
end
opts.separator ''
opts.separator 'Help:'
opts.on_tail('-h', '--help', 'Show this message') do
puts opts
exit
end
end.parse!
begin
fetch_incentives(
options.fetch(:email),
options[:language_code],
options[:country_code],
)
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
This example is not yet available in Perl; you can take a look at the other languages.
curl
Salvo que se indique lo contrario, el contenido de esta página está sujeto a la licencia Atribución 4.0 de Creative Commons, y los ejemplos de código están sujetos a la licencia Apache 2.0. Para obtener más información, consulta las políticas del sitio de Google Developers. Java es una marca registrada de Oracle o sus afiliados.
Última actualización: 2026-12-03 (UTC)
[null,null,["Última actualización: 2026-12-03 (UTC)"],[],[]]