Java
// Copyright 2020 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.ads.googleads.examples.assets; 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.v17.common.Money; import com.google.ads.googleads.v17.common.PriceAsset; import com.google.ads.googleads.v17.common.PriceOffering; import com.google.ads.googleads.v17.enums.AssetFieldTypeEnum.AssetFieldType; import com.google.ads.googleads.v17.enums.PriceExtensionPriceQualifierEnum.PriceExtensionPriceQualifier; import com.google.ads.googleads.v17.enums.PriceExtensionPriceUnitEnum.PriceExtensionPriceUnit; import com.google.ads.googleads.v17.enums.PriceExtensionTypeEnum.PriceExtensionType; import com.google.ads.googleads.v17.errors.GoogleAdsError; import com.google.ads.googleads.v17.errors.GoogleAdsException; import com.google.ads.googleads.v17.resources.Asset; import com.google.ads.googleads.v17.resources.CustomerAsset; import com.google.ads.googleads.v17.services.AssetOperation; import com.google.ads.googleads.v17.services.AssetServiceClient; import com.google.ads.googleads.v17.services.CustomerAssetOperation; import com.google.ads.googleads.v17.services.CustomerAssetServiceClient; import com.google.ads.googleads.v17.services.MutateAssetsResponse; import com.google.ads.googleads.v17.services.MutateCustomerAssetsResponse; import com.google.common.collect.ImmutableList; import java.io.FileNotFoundException; import java.io.IOException; /** Adds a price asset and associates it with an account. */ public class AddPrices { public static class AddPricesParams extends CodeSampleParams { @Parameter(names = ArgumentNames.CUSTOMER_ID) private long customerId; } public static void main(String[] args) { AddPricesParams params = new AddPricesParams(); if (!params.parseArguments(args)) { // Either pass the required parameters for this example on the command line, or insert them // into the code here. See the parameter class definition above for descriptions. params.customerId = Long.parseLong("INSERT_CUSTOMER_ID_HERE"); } 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 AddPrices().runExample(googleAdsClient, params.customerId); } catch (GoogleAdsException gae) { // GoogleAdsException is the base class for most exceptions thrown by an API request. // Instances of this exception have a message and a GoogleAdsFailure that contains a // collection of GoogleAdsErrors that indicate the underlying causes of the // GoogleAdsException. System.err.printf( "Request ID %s failed due to GoogleAdsException. Underlying errors:%n", gae.getRequestId()); int i = 0; for (GoogleAdsError googleAdsError : gae.getGoogleAdsFailure().getErrorsList()) { System.err.printf(" Error %d: %s%n", i++, googleAdsError); } System.exit(1); } } /** Runs the example. */ private void runExample(GoogleAdsClient googleAdsClient, long customerId) { // Creates a PriceAsset. String priceAssetResourceName = createPriceAsset(googleAdsClient, customerId); // Links the asset at the Customer level, allowing the asset to serve in all eligible // campaigns. For more detail about linking assets at customer, campaign and ad group level // see // https://developers.google.com/google-ads/api/docs/assets/overview#asset_types_linked_to_customers_campaigns_and_ad_groups. linkPriceAssetToCustomer(googleAdsClient, priceAssetResourceName, customerId); } /** Creates a PriceAsset. */ private String createPriceAsset(GoogleAdsClient googleAdsClient, long customerId) { PriceAsset priceAsset = PriceAsset.newBuilder() .setType(PriceExtensionType.SERVICES) // Optional: sets a qualifier text to show with the price asset. .setPriceQualifier(PriceExtensionPriceQualifier.FROM) .setLanguageCode("en") // To create a price asset, at least three price offerings are needed. .addPriceOfferings( createPriceOffering( "Scrubs", "Body Scrub, Salt Scrub", 60000000, // 60 USD "USD", PriceExtensionPriceUnit.PER_HOUR, "http://www.example.com/scrubs", "http://m.example.com/scrubs")) .addPriceOfferings( createPriceOffering( "Hair Cuts", "Once a month", 75000000, // 75 USD "USD", PriceExtensionPriceUnit.PER_MONTH, "http://www.example.com/haircuts", "http://m.example.com/haircuts")) .addPriceOfferings( createPriceOffering( "Skin Care Package", "Four times a month", 250000000, // 250 USD "USD", PriceExtensionPriceUnit.PER_MONTH, "http://www.example.com/skincarepackage", null)) .build(); // Wraps the PriceAsset in an Asset. Asset asset = Asset.newBuilder() .setPriceAsset(priceAsset) .setTrackingUrlTemplate("http://tracker.example.com/?u={lpurl}") .build(); // Creates an AssetOperation to add the new Asset. AssetOperation operation = AssetOperation.newBuilder().setCreate(asset).build(); // Creates the service client. try (AssetServiceClient client = googleAdsClient.getLatestVersion().createAssetServiceClient()) { // Sends the mutate request. MutateAssetsResponse response = client.mutateAssets(String.valueOf(customerId), ImmutableList.of(operation)); // Prints some information about the result. String resourceName = response.getResults(0).getResourceName(); System.out.printf("Created price asset with resource name '%s'.%n", resourceName); return resourceName; } } /** Links an Asset to Customer, allowing it to serve in all campaigns under the customer. */ private void linkPriceAssetToCustomer( GoogleAdsClient googleAdsClient, String priceAssetResourceName, long customerId) { // Creates the CustomerAsset link. CustomerAsset customerAsset = CustomerAsset.newBuilder() .setAsset(priceAssetResourceName) .setFieldType(AssetFieldType.PRICE) .build(); // Creates an CustomerAssetOperation to add the link. CustomerAssetOperation operation = CustomerAssetOperation.newBuilder().setCreate(customerAsset).build(); // Creates the service client. try (CustomerAssetServiceClient client = googleAdsClient.getLatestVersion().createCustomerAssetServiceClient()) { // Sends the mutate request. MutateCustomerAssetsResponse response = client.mutateCustomerAssets(String.valueOf(customerId), ImmutableList.of(operation)); // Prints some information about the result. String resourceName = response.getResults(0).getResourceName(); System.out.printf("Created customer asset with resource name '%s'.%n", resourceName); } } /** Creates a PriceOffering with the specified fields. */ private PriceOffering createPriceOffering( String header, String description, int priceInMicros, String currencyCode, PriceExtensionPriceUnit unit, String finalUrl, String finalMobileUrl) { PriceOffering.Builder builder = PriceOffering.newBuilder() .setHeader(header) .setDescription(description) .setFinalUrl(finalUrl) .setPrice( Money.newBuilder().setAmountMicros(priceInMicros).setCurrencyCode(currencyCode)) .setUnit(unit); if (finalMobileUrl != null) { builder.setFinalMobileUrl(finalMobileUrl); } return builder.build(); } }
C#
// Copyright 2020 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using CommandLine; using Google.Ads.Gax.Examples; using Google.Ads.GoogleAds.Lib; using Google.Ads.GoogleAds.V17.Common; using Google.Ads.GoogleAds.V17.Enums; using Google.Ads.GoogleAds.V17.Errors; using Google.Ads.GoogleAds.V17.Resources; using Google.Ads.GoogleAds.V17.Services; using System; using System.Collections.Generic; using static Google.Ads.GoogleAds.V17.Enums.PriceExtensionPriceQualifierEnum.Types; using static Google.Ads.GoogleAds.V17.Enums.PriceExtensionPriceUnitEnum.Types; using static Google.Ads.GoogleAds.V17.Enums.PriceExtensionTypeEnum.Types; namespace Google.Ads.GoogleAds.Examples.V17 { /// <summary> /// This code example adds a price extension and associates it with an account. /// </summary> public class AddPrices : ExampleBase { /// <summary> /// Command line options for running the <see cref="AddPrices"/> 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> /// 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); AddPrices codeExample = new AddPrices(); Console.WriteLine(codeExample.Description); codeExample.Run(new GoogleAdsClient(), options.CustomerId); } /// <summary> /// Returns a description about the code example. /// </summary> public override string Description => "This example adds a price extension and associates it with an account."; /// <summary> /// Runs the code example. /// </summary> /// <param name="client">The Google Ads client.</param> /// <param name="customerId">The customer ID for which the call is made.</param> public void Run(GoogleAdsClient client, long customerId) { try { // Create a new price asset. string priceAssetResourceName = CreatePriceAsset(client, customerId); // Add the new price asset to the account, so it will serve all // campaigns under the account. AddExtensionToAccount(client, customerId, priceAssetResourceName); } catch (GoogleAdsException e) { Console.WriteLine("Failure:"); Console.WriteLine($"Message: {e.Message}"); Console.WriteLine($"Failure: {e.Failure}"); Console.WriteLine($"Request ID: {e.RequestId}"); throw; } } /// <summary> /// Creates a price asset. /// </summary> /// <param name="client">The Google Ads client.</param> /// <param name="customerId">The customer ID for which the call is made.</param> /// <returns>the resource name of the newly created price asset.</returns> private string CreatePriceAsset(GoogleAdsClient client, long customerId) { PriceAsset priceAsset = new PriceAsset { Type = PriceExtensionType.Services, // Price qualifier is optional. PriceQualifier = PriceExtensionPriceQualifier.From, LanguageCode = "en", PriceOfferings = { CreatePriceOffering( "Scrubs", "Body Scrub, Salt Scrub", "http://www.example.com/scrubs", "http://m.example.com/scrubs", 60000000, // 60 USD "USD", PriceExtensionPriceUnit.PerHour ), CreatePriceOffering( "Hair Cuts", "Once a month", "http://www.example.com/haircuts", "http://m.example.com/haircuts", 250000000, // 60 USD "USD", PriceExtensionPriceUnit.PerMonth ), CreatePriceOffering( "Skin Care Package", "Four times a month", "http://www.example.com/skincarepackage", null, 250000000, // 250 USD "USD", PriceExtensionPriceUnit.PerMonth ), }, }; Asset asset = new Asset { Name = "Price Asset #" + ExampleUtilities.GetRandomString(), TrackingUrlTemplate = "http://tracker.example.com/?u={lpurl}", PriceAsset = priceAsset, }; AssetOperation operation = new AssetOperation { Create = asset, }; AssetServiceClient assetClient = client.GetService(Services.V17.AssetService); MutateAssetsResponse response = assetClient.MutateAssets(customerId.ToString(), new[] { operation }); string resourceName = response.Results[0].ResourceName; Console.WriteLine($"Created price asset with resource name '{resourceName}'."); return resourceName; } /// <summary> /// Adds the price asset to the customer account, allowing it to serve all campaigns under /// the account. /// </summary> /// <param name="client">The Google Ads client.</param> /// <param name="customerId">The customer ID for which the call is made.</param> /// <param name="priceAssetResourceName">The price asset resource name for which the call is /// made.</param> private void AddExtensionToAccount(GoogleAdsClient client, long customerId, string priceAssetResourceName) { CustomerAsset customerAsset = new CustomerAsset { Asset = priceAssetResourceName, FieldType = AssetFieldTypeEnum.Types.AssetFieldType.Price, }; // Issues the create request to add the callout. CustomerAssetServiceClient customerAssetServiceClient = client.GetService(Services.V17.CustomerAssetService); CustomerAssetOperation operation = new CustomerAssetOperation { Create = customerAsset, }; CustomerAssetServiceClient assetClient = client.GetService(Services.V17.CustomerAssetService); MutateCustomerAssetsResponse response = assetClient.MutateCustomerAssets(customerId.ToString(), new[] { operation }); string resourceName = response.Results[0].ResourceName; Console.WriteLine($"Created customer asset with resource name '{resourceName}'."); } /// <summary> /// Creates a new price offering with the specified attributes. /// </summary> /// <param name="header">The header for the price offering.</param> /// <param name="description">The description for the price offering.</param> /// <param name="finalUrl">The final url for the price offering.</param> /// <param name="finalMobileUrl">The final mobile url for the price offering. Can be set to /// null.</param> /// <param name="priceInMicros">The price in micros.</param> /// <param name="currencyCode">The currency code.</param> /// <param name="unit">The price unit.</param> private PriceOffering CreatePriceOffering(string header, string description, string finalUrl, string finalMobileUrl, long priceInMicros, string currencyCode, PriceExtensionPriceUnit unit) { PriceOffering priceOffering = new PriceOffering { Header = header, Description = description, FinalUrl = finalUrl, Price = new Money { AmountMicros = priceInMicros, CurrencyCode = currencyCode, }, Unit = unit, }; if (finalMobileUrl != null) { priceOffering.FinalMobileUrl = finalMobileUrl; } return priceOffering; } } }
PHP
<?php /** * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace Google\Ads\GoogleAds\Examples\Extensions; require __DIR__ . '/../../vendor/autoload.php'; use GetOpt\GetOpt; use Google\Ads\GoogleAds\Examples\Utils\ArgumentNames; use Google\Ads\GoogleAds\Examples\Utils\ArgumentParser; use Google\Ads\GoogleAds\Lib\OAuth2TokenBuilder; use Google\Ads\GoogleAds\Lib\V17\GoogleAdsClient; use Google\Ads\GoogleAds\Lib\V17\GoogleAdsClientBuilder; use Google\Ads\GoogleAds\Lib\V17\GoogleAdsException; use Google\Ads\GoogleAds\V17\Common\Money; use Google\Ads\GoogleAds\V17\Common\PriceAsset; use Google\Ads\GoogleAds\V17\Common\PriceOffering; use Google\Ads\GoogleAds\V17\Enums\AssetFieldTypeEnum\AssetFieldType; use Google\Ads\GoogleAds\V17\Enums\PriceExtensionPriceQualifierEnum\PriceExtensionPriceQualifier; use Google\Ads\GoogleAds\V17\Enums\PriceExtensionPriceUnitEnum\PriceExtensionPriceUnit; use Google\Ads\GoogleAds\V17\Enums\PriceExtensionTypeEnum\PriceExtensionType; use Google\Ads\GoogleAds\V17\Errors\GoogleAdsError; use Google\Ads\GoogleAds\V17\Resources\Asset; use Google\Ads\GoogleAds\V17\Resources\CustomerAsset; use Google\Ads\GoogleAds\V17\Services\AssetOperation; use Google\Ads\GoogleAds\V17\Services\CustomerAssetOperation; use Google\Ads\GoogleAds\V17\Services\MutateAssetsRequest; use Google\Ads\GoogleAds\V17\Services\MutateCustomerAssetsRequest; use Google\ApiCore\ApiException; /** * This example adds a price asset and associates it with an account. */ class AddPrices { private const CUSTOMER_ID = 'INSERT_CUSTOMER_ID_HERE'; public static function main() { // Either pass the required parameters for this example on the command line, or insert them // into the constants above. $options = (new ArgumentParser())->parseCommandArguments([ ArgumentNames::CUSTOMER_ID => GetOpt::REQUIRED_ARGUMENT ]); // Generate a refreshable OAuth2 credential for authentication. $oAuth2Credential = (new OAuth2TokenBuilder())->fromFile()->build(); // Construct a Google Ads client configured from a properties file and the // OAuth2 credentials above. $googleAdsClient = (new GoogleAdsClientBuilder())->fromFile() ->withOAuth2Credential($oAuth2Credential) // We set this value to true to show how to use GAPIC v2 source code. You can remove the // below line if you wish to use the old-style source code. Note that in that case, you // probably need to modify some parts of the code below to make it work. // For more information, see // https://developers.devsite.corp.google.com/google-ads/api/docs/client-libs/php/gapic. ->usingGapicV2Source(true) ->build(); try { self::runExample( $googleAdsClient, $options[ArgumentNames::CUSTOMER_ID] ?: self::CUSTOMER_ID ); } catch (GoogleAdsException $googleAdsException) { printf( "Request with ID '%s' has failed.%sGoogle Ads failure details:%s", $googleAdsException->getRequestId(), PHP_EOL, PHP_EOL ); foreach ($googleAdsException->getGoogleAdsFailure()->getErrors() as $error) { /** @var GoogleAdsError $error */ printf( "\t%s: %s%s", $error->getErrorCode()->getErrorCode(), $error->getMessage(), PHP_EOL ); } exit(1); } catch (ApiException $apiException) { printf( "ApiException was thrown with message '%s'.%s", $apiException->getMessage(), PHP_EOL ); exit(1); } } /** * Runs the example. * * @param GoogleAdsClient $googleAdsClient the Google Ads API client * @param int $customerId the client customer ID */ public static function runExample(GoogleAdsClient $googleAdsClient, int $customerId) { // Creates a PriceAsset. $priceAssetResourceName = self::createPriceAsset($googleAdsClient, $customerId); // Links the asset at the Customer level, allowing the asset to serve in all // eligible campaigns. For more detail about linking assets at customer, campaign and // ad group level see // https://support.google.com/google-ads/answer/7106946?hl=en&ref_topic=3119125 self::linkPriceAssetToCustomer($googleAdsClient, $priceAssetResourceName, $customerId); } /** * Creates a PriceAsset. * * @param GoogleAdsClient $googleAdsClient the Google Ads API client * @param int $customerId the client customer ID * @return string the created PriceAsset's resource name */ private static function createPriceAsset(GoogleAdsClient $googleAdsClient, int $customerId) { $priceAsset = new PriceAsset([ 'type' => PriceExtensionType::SERVICES, // Optional: Sets price qualifier. 'price_qualifier' => PriceExtensionPriceQualifier::FROM, 'language_code' => 'en' ]); // To create a price asset, at least three price offerings are needed. $priceAsset->setPriceOfferings([ self::createPriceOffering( 'Scrubs', 'Body Scrub, Salt Scrub', 60000000, // 60 USD 'USD', PriceExtensionPriceUnit::PER_HOUR, 'http://www.example.com/scrubs', 'http://m.example.com/scrubs' ), self::createPriceOffering( 'Hair Cuts', 'Once a month', 75000000, // 75 USD 'USD', PriceExtensionPriceUnit::PER_MONTH, 'http://www.example.com/haircuts', 'http://m.example.com/haircuts' ), self::createPriceOffering( 'Skin Care Package', 'Four times a month', 250000000, // 250 USD 'USD', PriceExtensionPriceUnit::PER_MONTH, 'http://www.example.com/skincarepackage' ) ]); // Wraps the PriceAsset in an Asset. $asset = new Asset([ 'price_asset' => $priceAsset, 'tracking_url_template' => 'http://tracker.example.com/?u={lpurl}' ]); // Creates an asset operation. $assetOperation = new AssetOperation(); $assetOperation->setCreate($asset); // Issues a mutate request to add the asset and print its information. $assetServiceClient = $googleAdsClient->getAssetServiceClient(); $response = $assetServiceClient->mutateAssets( MutateAssetsRequest::build($customerId, [$assetOperation]) ); $assetResourceName = $response->getResults()[0]->getResourceName(); printf( "Created price asset with resource name: '%s'.%s", $assetResourceName, PHP_EOL ); return $assetResourceName; } /** * Links an asset to customer, allowing it to serve in all campaigns under the customer. * * @param GoogleAdsClient $googleAdsClient the Google Ads API client * @param string $priceAssetResourceName the price asset's resource name to link * @param int $customerId the customer ID to link the price asset to */ private static function linkPriceAssetToCustomer( GoogleAdsClient $googleAdsClient, string $priceAssetResourceName, int $customerId ) { // Creates the CustomerAsset. $customerAsset = new CustomerAsset([ 'asset' => $priceAssetResourceName, 'field_type' => AssetFieldType::PRICE ]); // Creates a customer asset operation. $customerAssetOperation = new CustomerAssetOperation(); $customerAssetOperation->setCreate($customerAsset); // Issues a mutate request to add the customer asset and print its information. $customerAssetServiceClient = $googleAdsClient->getCustomerAssetServiceClient(); $response = $customerAssetServiceClient->mutateCustomerAssets( MutateCustomerAssetsRequest::build($customerId, [$customerAssetOperation]) ); printf( "Created customer asset with resource name: '%s'.%s", $response->getResults()[0]->getResourceName(), PHP_EOL ); } /** * Creates a price offering with the specified parameters. * * @param string $header the header * @param string $description the description * @param int $priceInMicros the price in micros * @param string $currencyCode the currency code * @param int $unit the enum value of unit * @param string $finalUrl the final URL * @param null|string $finalMobileUrl the final mobile URL * @return PriceOffering the created price offering */ private static function createPriceOffering( string $header, string $description, int $priceInMicros, string $currencyCode, int $unit, string $finalUrl, string $finalMobileUrl = null ) { $priceOffering = new PriceOffering([ 'header' => $header, 'description' => $description, 'final_url' => $finalUrl, 'price' => new Money([ 'amount_micros' => $priceInMicros, 'currency_code' => $currencyCode ]), 'unit' => $unit ]); if (!is_null($finalMobileUrl)) { $priceOffering->setFinalMobileUrl($finalMobileUrl); } return $priceOffering; } } AddPrices::main();
Python
#!/usr/bin/env python # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """This example adds a price asset and associates it with an account.""" import argparse import sys from uuid import uuid4 from google.ads.googleads.client import GoogleAdsClient from google.ads.googleads.errors import GoogleAdsException def main(client, customer_id): """The main method that creates all necessary entities for the example. Args: client: an initialized GoogleAdsClient instance. customer_id: a client customer ID. """ # Create a new price asset. price_asset_resource_name = create_price_asset(client, customer_id) # Add the new price asset to the account. add_asset_to_account(client, customer_id, price_asset_resource_name) def create_price_asset(client, customer_id): """Creates a price asset and returns its resource name. Args: client: an initialized GoogleAdsClient instance. customer_id: a client customer ID. Returns: a PriceAsset resource name. """ # Create an asset operation. asset_operation = client.get_type("AssetOperation") # Create an asset. asset = asset_operation.create asset.name = f"Price Asset #{uuid4()}" asset.tracking_url_template = "http://tracker.example.com/?u={lpurl}" # Create the price asset. price_asset = asset.price_asset price_asset.type_ = client.enums.PriceExtensionTypeEnum.SERVICES # Price qualifier is optional. price_asset.price_qualifier = ( client.enums.PriceExtensionPriceQualifierEnum.FROM ) price_asset.language_code = "en" price_asset.price_offerings.extend( [ create_price_offering( client, "Scrubs", "Body Scrub, Salt Scrub", "http://www.example.com/scrubs", "http://m.example.com/scrubs", 60000000, # 60 USD "USD", client.enums.PriceExtensionPriceUnitEnum.PER_HOUR, ), create_price_offering( client, "Hair Cuts", "Once a month", "http://www.example.com/haircuts", "http://m.example.com/haircuts", 75000000, # 75 USD "USD", client.enums.PriceExtensionPriceUnitEnum.PER_MONTH, ), create_price_offering( client, "Skin Care Package", "Four times a month", "http://www.example.com/skincarepackage", None, 250000000, # 250 USD "USD", client.enums.PriceExtensionPriceUnitEnum.PER_MONTH, ), ] ) # Issue a mutate request to create the price asset. asset_service = client.get_service("AssetService") response = asset_service.mutate_assets( customer_id=customer_id, operations=[asset_operation] ) resource_name = response.results[0].resource_name print(f"Created a price asset with resource name '{resource_name}'.") return resource_name def create_price_offering( client, header, description, final_url, final_mobile_url, price_in_micros, currency_code, unit, ): """Creates a PriceOffering instance and returns it. Args: client: an initialized GoogleAdsClient instance. header: The header of the price offering. description: The description of the price offering. final_url: The final_url of the price offering. final_mobile_url: The final_mobile_url of the price offering. price_in_micros: The price of the price offering. currency_code: The currency_code of the price offering. unit: The price unit of the price offering. Returns: A PriceOffering instance. """ price_offering = client.get_type("PriceOffering") price_offering.header = header price_offering.description = description price_offering.final_url = final_url # Check if this exists, since we pass None for one of the PriceOfferings # in the _create_price_asset method and assigning None to this field # raises an error. if final_mobile_url: price_offering.final_mobile_url = final_mobile_url price_offering.price.amount_micros = price_in_micros price_offering.price.currency_code = currency_code price_offering.unit = unit return price_offering def add_asset_to_account(client, customer_id, price_asset_resource_name): """Adds a new Asset to the given user account. Adding the Asset to an account allows it to serve in all campaigns under that account. Args: client: an initialized GoogleAdsClient instance. customer_id: a client customer ID. price_asset_resource_name: a resource name for an Asset containing a PriceAsset. """ # Create a customer asset operation. customer_asset_operation = client.get_type("CustomerAssetOperation") # Create a customer asset, set its type to PRICE and attach price asset. asset = customer_asset_operation.create asset.field_type = client.enums.AssetFieldTypeEnum.PRICE asset.asset = price_asset_resource_name # Issue a mutate request to create the customer asset. customer_asset_service = client.get_service("CustomerAssetService") response = customer_asset_service.mutate_customer_assets( customer_id=customer_id, operations=[customer_asset_operation] ) resource_name = response.results[0].resource_name print( "Created customer asset with resource name " f"'{response.results[0].resource_name}'." ) if __name__ == "__main__": parser = argparse.ArgumentParser( description="Add price asset for the specified customer id." ) # 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", ) 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="v17") try: main(googleads_client, args.customer_id) except GoogleAdsException as ex: print( f'Request with ID "{ex.request_id}" failed with status ' f'"{ex.error.code().name}" and includes the following errors:' ) for error in ex.failure.errors: print(f'\tError with message "{error.message}".') if error.location: for field_path_element in error.location.field_path_elements: print(f"\t\tOn field: {field_path_element.field_name}") sys.exit(1)
Ruby
#!/usr/bin/env ruby # Encoding: utf-8 # # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # Adds a price asset and associates it with an account. require 'optparse' require 'google/ads/google_ads' require 'date' def add_prices(customer_id) # GoogleAdsClient will read a config file from # ENV['HOME']/google_ads_config.rb when called without parameters client = Google::Ads::GoogleAds::GoogleAdsClient.new # Create a new price asset. price_asset_resource_name = create_price_asset(client, customer_id) # Add the new price asset to the account. add_asset_to_account(client, customer_id, price_asset_resource_name) end def create_price_asset(client, customer_id) operation = client.operation.create_resource.asset do |asset| asset.name = "Price Asset ##{(Time.new.to_f * 1000).to_i}" asset.tracking_url_template = 'http://tracker.example.com/?u={lpurl}' asset.price_asset = client.resource.price_asset do |price| price.type = :SERVICES # Optional: set price qualifier. price.price_qualifier = :FROM price.language_code = 'en' # To create a price asset, at least three price offerings are needed. price.price_offerings << create_price_offer( client, 'Scrubs', 'Body Scrub, Salt Scrub', 60_000_000, # 60 USD 'USD', :PER_HOUR, 'http://www.example.com/scrubs', 'http://m.example.com/scrubs') price.price_offerings << create_price_offer( client, 'Hair Cuts', 'Once a month', 75_000_000, # 75 USD 'USD', :PER_MONTH, 'http://www.example.com/haircuts', 'http://m.example.com/haircuts') price.price_offerings << create_price_offer( client, 'Skin Care Package', 'Four times a month', 250_000_000, # 250 USD 'USD', :PER_MONTH, 'http://www.example.com/skincarepackage') end end response = client.service.asset.mutate_assets( customer_id: customer_id, operations: [operation], ) resource_name = response.results.first.resource_name puts "Created asset with resource name '#{resource_name}'" resource_name end def create_price_offer( client, header, description, price_in_micros, currency_code, unit, final_url, final_mobile_url=nil) client.resource.price_offering do |po| po.header = header po.description = description po.final_url = final_url po.price = client.resource.money do |pr| pr.amount_micros = price_in_micros pr.currency_code = currency_code end po.unit = unit # Optional: set the final mobile URLs unless final_mobile_url.nil? po.final_mobile_url = final_mobile_url end end end def add_asset_to_account(client, customer_id, asset) operation = client.operation.create_resource.customer_asset do |ca| ca.asset = asset ca.field_type = :PRICE end response = client.service.customer_asset.mutate_customer_assets( customer_id: customer_id, operations: [operation], ) puts "Created customer asset with resource name '#{response.results.first.resource_name}'" end if __FILE__ == $0 options = {} # The following parameter(s) should be provided to run the example. You can # either specify these by changing the INSERT_XXX_ID_HERE values below, or on # the command line. # # Parameters passed on the command line will override any parameters set in # code. # # Running the example with -h will print the command line usage. options[:customer_id] = 'INSERT_CUSTOMER_ID_HERE' OptionParser.new do |opts| opts.banner = sprintf('Usage: %s [options]', File.basename(__FILE__)) opts.separator '' opts.separator 'Options:' opts.on('-C', '--customer-id CUSTOMER-ID', String, 'Customer ID') do |v| options[:customer_id] = v end opts.separator '' opts.separator 'Help:' opts.on_tail('-h', '--help', 'Show this message') do puts opts exit end end.parse! begin add_prices(options.fetch(:customer_id).tr("-", "")) rescue Google::Ads::GoogleAds::Errors::GoogleAdsError => e e.failure.errors.each do |error| STDERR.printf("Error with message: %s\n", error.message) if error.location error.location.field_path_elements.each do |field_path_element| STDERR.printf("\tOn field: %s\n", field_path_element.field_name) end end error.error_code.to_h.each do |k, v| next if v == :UNSPECIFIED STDERR.printf("\tType: %s\n\tCode: %s\n", k, v) end end raise end end
Perl
#!/usr/bin/perl -w # # Copyright 2020, Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # This example adds a price asset and associates it with an account. 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::V17::Resources::Asset; use Google::Ads::GoogleAds::V17::Resources::CustomerAsset; use Google::Ads::GoogleAds::V17::Common::PriceAsset; use Google::Ads::GoogleAds::V17::Common::PriceOffering; use Google::Ads::GoogleAds::V17::Common::Money; use Google::Ads::GoogleAds::V17::Enums::PriceExtensionTypeEnum qw(SERVICES); use Google::Ads::GoogleAds::V17::Enums::PriceExtensionPriceQualifierEnum qw(FROM); use Google::Ads::GoogleAds::V17::Enums::PriceExtensionPriceUnitEnum qw(PER_HOUR PER_MONTH); use Google::Ads::GoogleAds::V17::Enums::AssetFieldTypeEnum qw(PRICE); use Google::Ads::GoogleAds::V17::Services::AssetService::AssetOperation; use Google::Ads::GoogleAds::V17::Services::CustomerAssetService::CustomerAssetOperation; use Getopt::Long qw(:config auto_help); use Pod::Usage; use Cwd qw(abs_path); use Data::Uniqid qw(uniqid); # The following parameter(s) should be provided to run the example. You can # either specify these by changing the INSERT_XXX_ID_HERE values below, or on # the command line. # # Parameters passed on the command line will override any parameters set in # code. # # Running the example with -h will print the command line usage. my $customer_id = "INSERT_CUSTOMER_ID_HERE"; sub add_prices { my ($api_client, $customer_id) = @_; # Create a new price asset. my $price_asset_resource_name = create_price_asset($api_client, $customer_id); # Add the new price asset to the account, so it will serve all campaigns # under the account. add_asset_to_account($api_client, $customer_id, $price_asset_resource_name); return 1; } # Creates a price asset. sub create_price_asset { my ($api_client, $customer_id) = @_; # Create the price asset. my $price_asset = Google::Ads::GoogleAds::V17::Common::PriceAsset->new({ type => SERVICES, # Price qualifier is optional. priceQualifier => FROM, languageCode => "en", priceOfferings => [ create_price_offering( "Scrubs", "Body Scrub, Salt Scrub", "http://www.example.com/scrubs", "http://m.example.com/scrubs", 60000000, # 60 USD "USD", PER_HOUR ), create_price_offering( "Hair Cuts", "Once a month", "http://www.example.com/haircuts", "http://m.example.com/haircuts", 75000000, # 75 USD "USD", PER_MONTH ), create_price_offering( "Skin Care Package", "Four times a month", "http://www.example.com/skincarepackage", undef, 250000000, # 250 USD "USD", PER_MONTH )]}); # Create an asset. my $asset = Google::Ads::GoogleAds::V17::Resources::Asset->new({ name => "Price Asset #" . uniqid(), trackingUrlTemplate => "http://tracker.example.com/?u={lpurl}", priceAsset => $price_asset }); # Create an asset operation. my $operation = Google::Ads::GoogleAds::V17::Services::AssetService::AssetOperation->new({ create => $asset }); # Issue a mutate request to add the price asset and print some information. my $response = $api_client->AssetService()->mutate({ customerId => $customer_id, operations => [$operation]}); printf "Created price asset with resource name '%s'.\n", $response->{results}[0]{resourceName}; return $response->{results}[0]{resourceName}; } # Adds the price asset to the customer account, allowing it to serve all campaigns # under the account. sub add_asset_to_account { my ($api_client, $customer_id, $price_asset_resource_name) = @_; # Create a customer asset, set its type to PRICE and attach the price asset. my $customer_asset = Google::Ads::GoogleAds::V17::Resources::CustomerAsset->new({ asset => $price_asset_resource_name, fieldType => PRICE }); # Create a customer asset operation. my $operation = Google::Ads::GoogleAds::V17::Services::CustomerAssetService::CustomerAssetOperation ->new({ create => $customer_asset }); # Issue a mutate request to add the customer asset and print some information. my $response = $api_client->CustomerAssetService()->mutate({ customerId => $customer_id, operations => [$operation]}); printf "Created customer asset with resource name '%s'.\n", $response->{results}[0]{resourceName}; } # Creates a new price offering with the specified attributes. sub create_price_offering { my ($header, $description, $final_url, $final_mobile_url, $price_in_micros, $currency_code, $unit) = @_; my $price_offering = Google::Ads::GoogleAds::V17::Common::PriceOffering->new({ header => $header, description => $description, finalUrl => $final_url, price => Google::Ads::GoogleAds::V17::Common::Money->new({ amountMicros => $price_in_micros, currencyCode => $currency_code } ), unit => $unit }); # Optional: set the final mobile URL. $price_offering->{finalMobileUrl} = $final_mobile_url if $final_mobile_url; return $price_offering; } # Don't run the example if the file is being included. if (abs_path($0) ne abs_path(__FILE__)) { return 1; } # Get Google Ads Client, credentials will be read from ~/googleads.properties. my $api_client = Google::Ads::GoogleAds::Client->new(); # By default examples are set to die on any server returned fault. $api_client->set_die_on_faults(1); # Parameters passed on the command line will override any parameters set in code. GetOptions("customer_id=s" => \$customer_id); # 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); # Call the example. add_prices($api_client, $customer_id =~ s/-//gr); =pod =head1 NAME add_prices =head1 DESCRIPTION This example adds a price asset and associates it with an account. =head1 SYNOPSIS add_prices.pl [options] -help Show the help message. -customer_id The Google Ads customer ID. =cut